import { findPackageRoot , findProjectRoot } from '../paths' ; import fs from 'fs-extra' ; import path from 'path' ; import { getWorkspaces , listAllTrackedFiles } from 'workspace-tools' ; import { PackageInfos } from '../types/PackageInfo' ; import { infoFromPackageJson } from './infoFromPackageJson' ; /**
 * Get a mapping from package name to package info for all packages in the workspace
 * (reading from package.json files)
 */ export function getPackageInfos ( cwd ) { const projectRoot = findProjectRoot ( cwd ) ; const packageRoot = findPackageRoot ( cwd ) ; return ( ( projectRoot && getPackageInfosFromWorkspace ( projectRoot ) ) || ( projectRoot && getPackageInfosFromNonWorkspaceMonorepo ( projectRoot ) ) || ( packageRoot && getPackageInfosFromSingleRepo ( packageRoot ) ) || { } ) ; } function getPackageInfosFromWorkspace ( projectRoot ) { try { const packageInfos = { } ; const workspaceInfo = getWorkspaces ( projectRoot ) ; if ( workspaceInfo && workspaceInfo . length > 0 ) { workspaceInfo . forEach ( info => { const { path : packagePath , packageJson } = info ; const packageJsonPath = path . join ( packagePath , 'package.json' ) ; try { packageInfos [ packageJson . name ] = infoFromPackageJson ( packageJson , packageJsonPath ) ; } catch ( e ) { console . warn ( `Invalid package.json file detected ${ packageJsonPath }: ` , e ) ; } } ) ; return packageInfos ; } } catch ( e ) { } } function getPackageInfosFromNonWorkspaceMonorepo ( projectRoot ) { const packageJsonFiles = listAllTrackedFiles ( [ '**/package.json' , 'package.json' ] , projectRoot ) ; const packageInfos = { } ; if ( packageJsonFiles && packageJsonFiles . length > 0 ) { packageJsonFiles . forEach ( packageJsonPath => { try { const packageJsonFullPath = path . join ( projectRoot , packageJsonPath ) ; const packageJson = fs . readJSONSync ( packageJsonFullPath ) ; packageInfos [ packageJson . name ] = infoFromPackageJson ( packageJson , packageJsonFullPath ) ; } catch ( e ) { console . warn ( `Invalid package.json file detected ${ packageJsonPath }: ` , e ) ; } } ) ; return packageInfos ; } } function getPackageInfosFromSingleRepo ( packageRoot ) { const packageInfos = { } ; const packageJsonFullPath = path . resolve ( packageRoot , 'package.json' ) ; const packageJson = fs . readJSONSync ( packageJsonFullPath ) ; packageInfos [ packageJson . name ] = infoFromPackageJson ( packageJson , packageJsonFullPath ) ; return packageInfos ; }