-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathlist-workspaces.mjs
More file actions
83 lines (71 loc) · 2.16 KB
/
list-workspaces.mjs
File metadata and controls
83 lines (71 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import path from 'node:path';
import { getFiles } from '../util/get-files.mjs';
import fs from 'node:fs';
import { toposort } from '../util/toposort.mjs';
export async function listWorkspaces() {
try {
const rootPackageJSON = JSON.parse(await fs.promises.readFile('package.json'));
const workspaces = rootPackageJSON.workspaces;
const packages = new Set();
for (const workspace of workspaces) {
if (workspace.endsWith('/*')) {
const packageDirs = await getFiles(workspace.slice(0, -2), false);
for (const packageDir of packageDirs) {
packages.add(
path.resolve(path.join(packageDir, 'package.json')),
);
}
} else {
packages.add(
path.resolve(path.join(workspace, 'package.json')),
);
}
}
for (const packagePath of packages.values()) {
if (!fs.existsSync(packagePath)) {
packages.delete(packagePath);
}
}
const result = [];
for (const packageJSONPath of Array.from(packages)) {
const packageJSON = JSON.parse(await fs.promises.readFile(packageJSONPath));
const packagePath = path.relative(process.cwd(), path.dirname(packageJSONPath));
result.push({
path: packagePath,
name: packageJSON.name,
unscopedName: packageJSON.name.replace(/^@[^/]+\//, ''),
private: packageJSON.private,
dependencies: [
...Object.keys(Object(packageJSON.dependencies)),
...Object.keys(Object(packageJSON.devDependencies)),
...Object.keys(Object(packageJSON.peerDependencies)),
],
});
}
const packageNames = result.map((x) => x.name);
result.forEach((x) => {
x.dependencies = x.dependencies.filter((y) => {
return packageNames.includes(y);
});
});
const dependencyGraphEdges = result.flatMap((x) => {
return x.dependencies.map((y) => {
return [y, x.name];
});
});
const sorted = toposort(packageNames, dependencyGraphEdges);
if (!sorted) {
throw new Error('Circular reference detected');
}
result.sort((a, b) => {
return sorted.indexOf(a) - sorted.indexOf(b);
});
return result;
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
throw new Error('failed to get the list of workspaces', {
cause: err,
});
}
}