get-workspaces.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const { resolve, relative } = require('node:path')
  2. const mapWorkspaces = require('@npmcli/map-workspaces')
  3. const { minimatch } = require('minimatch')
  4. const pkgJson = require('@npmcli/package-json')
  5. // minimatch wants forward slashes only for glob patterns
  6. const globify = pattern => pattern.split('\\').join('/')
  7. // Returns an Map of paths to workspaces indexed by workspace name
  8. // { foo => '/path/to/foo' }
  9. const getWorkspaces = async (filters, { path, includeWorkspaceRoot, relativeFrom }) => {
  10. // TODO we need a better error to be bubbled up here if this call fails
  11. const { content: pkg } = await pkgJson.normalize(path)
  12. const workspaces = await mapWorkspaces({ cwd: path, pkg })
  13. let res = new Map()
  14. if (includeWorkspaceRoot) {
  15. res.set(pkg.name, path)
  16. }
  17. if (!filters.length) {
  18. res = new Map([...res, ...workspaces])
  19. }
  20. for (const filterArg of filters) {
  21. for (const [workspaceName, workspacePath] of workspaces.entries()) {
  22. let relativePath = relative(relativeFrom, workspacePath)
  23. if (filterArg.startsWith('./')) {
  24. relativePath = `./${relativePath}`
  25. }
  26. const relativeFilter = relative(path, filterArg)
  27. if (filterArg === workspaceName
  28. || resolve(relativeFrom, filterArg) === workspacePath
  29. || minimatch(relativePath, `${globify(relativeFilter)}/*`)
  30. || minimatch(relativePath, `${globify(filterArg)}/*`)
  31. ) {
  32. res.set(workspaceName, workspacePath)
  33. }
  34. }
  35. }
  36. if (!res.size) {
  37. let msg = '!'
  38. if (filters.length) {
  39. msg = `:\n ${filters.reduce(
  40. (acc, filterArg) => `${acc} --workspace=${filterArg}`, '')}`
  41. }
  42. throw new Error(`No workspaces found${msg}`)
  43. }
  44. return res
  45. }
  46. module.exports = getWorkspaces