-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathprune.ts
80 lines (69 loc) · 2.08 KB
/
prune.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
import { normalizePath, warning } from './common';
import { DestroyerOfModules, DepType, Module, ModuleMap } from 'galactus';
import fs from 'fs-extra';
import path from 'path';
const ELECTRON_MODULES = ['electron', 'electron-nightly'];
export class Pruner {
baseDir: string;
galactus: DestroyerOfModules;
modules = new Set<string>();
quiet: boolean;
walkedTree = false;
constructor(dir: string, quiet: boolean) {
this.baseDir = normalizePath(dir);
this.quiet = quiet;
this.galactus = new DestroyerOfModules({
rootDirectory: dir,
shouldKeepModuleTest: (module, isDevDep) =>
this.shouldKeepModule(module, isDevDep),
});
}
setModules(moduleMap: ModuleMap) {
const modulePaths = Array.from(moduleMap.keys()).map(
(modulePath) => `/${normalizePath(modulePath)}`,
);
this.modules = new Set(modulePaths);
this.walkedTree = true;
}
async pruneModule(name: string) {
if (this.walkedTree) {
return this.isProductionModule(name);
} else {
const moduleMap = await this.galactus.collectKeptModules({
relativePaths: true,
});
this.setModules(moduleMap);
return this.isProductionModule(name);
}
}
shouldKeepModule(module: Module, isDevDep: boolean) {
if (isDevDep || module.depType === DepType.ROOT) {
return false;
}
if (ELECTRON_MODULES.includes(module.name)) {
warning(
`Found '${module.name}' but not as a devDependency, pruning anyway`,
this.quiet,
);
return false;
}
return true;
}
isProductionModule(name: string) {
return this.modules.has(name);
}
}
function isNodeModuleFolder(pathToCheck: string) {
return (
path.basename(path.dirname(pathToCheck)) === 'node_modules' ||
(path.basename(path.dirname(pathToCheck)).startsWith('@') &&
path.basename(path.resolve(pathToCheck, `..${path.sep}..`)) ===
'node_modules')
);
}
export async function isModule(pathToCheck: string) {
return (
(await fs.pathExists(path.join(pathToCheck, 'package.json'))) &&
isNodeModuleFolder(pathToCheck)
);
}