-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·110 lines (87 loc) · 2.59 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env node
'use strict';
const cac = require('cac');
const fs = require('fs');
const chalk = require('chalk');
const ostap = require('./src');
const Confirm = require('prompt-confirm');
const pkg = require('./package.json');
const DEFAULT_OPTIONS = {
useCache: false,
viewFullLogs: false,
printSourceTreeDuplicates: false,
printOptimalTreeDuplicates: false,
};
const run = async (file, options) => {
try {
await fs.accessSync(file, fs.constants.R_OK);
} catch (error) {
throw 'no access for read, file: ' + file;
}
let treeRoot = {};
try {
treeRoot = JSON.parse(fs.readFileSync(file));
} catch (error) {
throw 'parse error file ' + file + '\n' + error;
}
let optimalTree = null;
try {
optimalTree = await ostap(treeRoot, options);
} catch (error) {
throw error;
}
if (optimalTree) {
const prompt = new Confirm({
message: 'Apply suggested update to original package.json file?',
default: false,
});
const answer = await prompt.run();
if (answer) {
try {
await fs.accessSync(file, fs.constants.W_OK);
} catch (error) {
throw 'no access for write, file: ' + file;
}
try {
fs.writeFileSync(file, JSON.stringify(optimalTree, null, 4));
} catch (error) {
throw 'write error' + file + '\n' + error;
}
console.log('changed package.json');
}
}
console.log('bye');
};
const printError = message => {
console.log(chalk.bgRed.black(' ERROR '));
console.log(message);
};
const cli = cac();
cli
.command('[...file]', 'Check project dependencies duplicates by package.json')
.option('-c, --use-cache', 'Use cache')
.option('-d, --duplicates', 'Show duplicates in source and optimal tree')
.option('-s, --source-tree-duplicates', 'Show duplicates in source tree')
.option('-o, --optimal-tree-duplicates', 'Show duplicates in optimal tree')
.example('ostap ./package.json')
.example('ostap ./package.json --use-cache')
.example('ostap /Users/frontend/monkey/package.json -d')
.action(([filePath], flags) => {
const file = filePath || './package.json';
let options = { ...DEFAULT_OPTIONS };
if (flags['useCache']) {
options.useCache = true;
}
if (flags['sourceTreeDuplicates'] || flags['duplicates']) {
options.printSourceTreeDuplicates = true;
}
if (flags['optimalTreeDuplicates'] || flags['duplicates']) {
options.printOptimalTreeDuplicates = true;
}
Promise.resolve()
.then(() => run(file, options))
.catch(printError);
});
cli.version(pkg.version);
cli.help();
cli.parse();