forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackage-tree.ts
86 lines (75 loc) · 2.35 KB
/
package-tree.ts
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
84
85
86
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as fs from 'node:fs';
import { dirname, join } from 'node:path';
import * as resolve from 'resolve';
import { NgAddSaveDependency } from './package-metadata';
interface PackageJson {
name: string;
version: string;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
'ng-update'?: {
migrations?: string;
};
'ng-add'?: {
save?: NgAddSaveDependency;
};
}
function getAllDependencies(pkg: PackageJson): Set<[string, string]> {
return new Set([
...Object.entries(pkg.dependencies || []),
...Object.entries(pkg.devDependencies || []),
...Object.entries(pkg.peerDependencies || []),
...Object.entries(pkg.optionalDependencies || []),
]);
}
export interface PackageTreeNode {
name: string;
version: string;
path: string;
package: PackageJson | undefined;
}
export async function readPackageJson(packageJsonPath: string): Promise<PackageJson | undefined> {
try {
return JSON.parse((await fs.promises.readFile(packageJsonPath)).toString()) as PackageJson;
} catch {
return undefined;
}
}
export function findPackageJson(workspaceDir: string, packageName: string): string | undefined {
try {
// avoid require.resolve here, see: https://github.com/angular/angular-cli/pull/18610#issuecomment-681980185
const packageJsonPath = resolve.sync(`${packageName}/package.json`, { basedir: workspaceDir });
return packageJsonPath;
} catch {
return undefined;
}
}
export async function getProjectDependencies(dir: string): Promise<Map<string, PackageTreeNode>> {
const pkg = await readPackageJson(join(dir, 'package.json'));
if (!pkg) {
throw new Error('Could not find package.json');
}
const results = new Map<string, PackageTreeNode>();
for (const [name, version] of getAllDependencies(pkg)) {
const packageJsonPath = findPackageJson(dir, name);
if (!packageJsonPath) {
continue;
}
results.set(name, {
name,
version,
path: dirname(packageJsonPath),
package: await readPackageJson(packageJsonPath),
});
}
return results;
}