get-workspaces.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const { resolve } = require('path')
  2. const mapWorkspaces = require('@npmcli/map-workspaces')
  3. const minimatch = require('minimatch')
  4. const rpj = require('read-package-json-fast')
  5. // Returns an Map of paths to workspaces indexed by workspace name
  6. // { foo => '/path/to/foo' }
  7. const getWorkspaces = async (filters, { path, includeWorkspaceRoot }) => {
  8. // TODO we need a better error to be bubbled up here if this rpj call fails
  9. const pkg = await rpj(resolve(path, 'package.json'))
  10. const workspaces = await mapWorkspaces({ cwd: path, pkg })
  11. let res = new Map()
  12. if (includeWorkspaceRoot)
  13. res.set(pkg.name, path)
  14. if (!filters.length)
  15. res = new Map([...res, ...workspaces])
  16. for (const filterArg of filters) {
  17. for (const [workspaceName, workspacePath] of workspaces.entries()) {
  18. if (filterArg === workspaceName
  19. || resolve(path, filterArg) === workspacePath
  20. || minimatch(workspacePath, `${resolve(path, filterArg)}/*`))
  21. res.set(workspaceName, workspacePath)
  22. }
  23. }
  24. if (!res.size) {
  25. let msg = '!'
  26. if (filters.length) {
  27. msg = `:\n ${filters.reduce(
  28. (res, filterArg) => `${res} --workspace=${filterArg}`, '')}`
  29. }
  30. throw new Error(`No workspaces found${msg}`)
  31. }
  32. return res
  33. }
  34. module.exports = getWorkspaces