forked from scinos/yarn-deduplicate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·73 lines (62 loc) · 2.26 KB
/
cli.js
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
#!/usr/bin/env node
const commander = require('commander');
const fs = require('fs');
const { fixDuplicates, listDuplicates } = require('./index');
const version = require('./package.json').version;
commander
.version(version)
.usage('[options] [yarn.lock path (default: yarn.lock)]')
.option(
'-s, --strategy <strategy>',
'deduplication strategy. Valid values: fewer, highest. Default is "highest"',
'highest'
)
.option('-l, --list', 'do not change yarn.lock, just output the diagnosis')
.option('-f, --fail', 'if there are duplicates in yarn.lock, exit 1 for failure')
.option(
'--packages <packages>',
'a comma separated list of packages to deduplicate. Defaults to all packages.',
val => val.split(',').map(v => v.trim())
)
.option('--print', 'instead of saving the deduplicated yarn.lock, print the result in stdout');
commander.parse(process.argv);
if (commander.strategy !== 'highest' && commander.strategy !== 'fewer') {
console.error(`Invalid strategy ${commander.strategy}`);
commander.help();
}
const file = commander.args.length ? commander.args[0] : 'yarn.lock';
try {
const yarnLock = fs.readFileSync(file, 'utf8');
const useMostCommon = commander.strategy === 'fewer';
if (commander.list) {
const duplicates = listDuplicates(yarnLock, {
useMostCommon,
includePackages: commander.packages,
});
duplicates.forEach(logLine => console.log(logLine));
if (commander.fail && duplicates.length > 0) {
process.exit(1);
}
} else {
let dedupedYarnLock = fixDuplicates(yarnLock, {
useMostCommon,
includePackages: commander.packages,
});
if (commander.print) {
console.log(dedupedYarnLock);
} else {
const eolMatch = yarnLock.match(/(\r?\n)/);
if (eolMatch && eolMatch[0] === '\r\n') {
dedupedYarnLock = dedupedYarnLock.replace(/\n/g, '\r\n');
}
fs.writeFileSync(file, dedupedYarnLock);
}
if (commander.fail && yarnLock !== dedupedYarnLock) {
process.exit(1);
}
}
process.exit(0);
} catch (e) {
console.error(e);
process.exit(1);
}