-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·258 lines (228 loc) · 8.11 KB
/
Copy pathindex.js
File metadata and controls
executable file
·258 lines (228 loc) · 8.11 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env node
import stableStringify from 'json-stable-stringify';
import { logger } from 'lognographer';
import { program } from 'commander';
import JSON5 from 'json5';
import path from 'path';
import fs from 'fs';
import generateReport from './src/js/report.js';
import asyncExec from './src/js/exec.js'
import packageJSON from './package.json' with { type: "json" };
const { version } = packageJSON;
// Parse options and provide helper text
const {
verbose,
silent,
report: reportFlag,
saveReportToFile,
overwrite: overwriteFlag,
upgrade,
runAudit: runAuditFlag,
fixAudit,
json,
} = program
.version(version)
.option('-v, --verbose', 'Show debug output')
.option('-w, --overwrite', 'Overwrite the existing package.json')
.option('-s, --silent', 'Silence all logging')
.option('-r --report', 'Generate a log of which modules were updated')
.option('-u --upgrade', 'Run npm install after updating the package.json')
.option('-a --runAudit', 'Generate an audit report')
.option('-j --json', 'Save the report to JSON file: updatedModules.json')
.option('-f --saveReportToFile', 'Save the report to file: updatedModules.html')
.option('-x --fixAudit', 'Run fix audit')
.parse(process.argv)
.opts();
// We can't upgrade of fixAudit unless overwrite is selected
const overwrite = upgrade || fixAudit || overwriteFlag;
// If we're gonna fix the audit, we've got to run the audit
const runAudit = runAuditFlag || fixAudit;
// If the save to file flag is on, we've got to generate a report
const report = reportFlag || saveReportToFile || runAuditFlag || json;
if (verbose && !silent) {
logger.debug(`Settings
• verbose: ${verbose ? 'yes' : 'nope'}
• overwrite: ${overwrite ? 'yes' : 'nope'}
• install new modules: ${overwrite && upgrade ? 'yes' : 'nope'}
• run audit: ${runAudit ? 'yes' : 'nope'}
• fix audit: ${runAudit && fixAudit ? 'yes' : 'nope'}
• generate report: ${report ? 'yes' : 'nope'}
• do what with report: ${saveReportToFile ? 'save it' : 'print it'}
`);
}
/**
* Command-line utility to upgrade all modules not explicitly versioned in the
* companion fixedModules.json file
*/
const parentDir = process.cwd(); // gets the directory where command was executed
let fixedModules = { dependencies: {}, devDependencies: {} };
const currentPackage = JSON.parse(fs.readFileSync(path.join(parentDir, 'package.json'), 'utf8'));
const fixedModulePath = path.join(parentDir, 'fixedModules');
if (fs.existsSync(`${fixedModulePath}.json`) || fs.existsSync(`${fixedModulePath}.json5`)) {
const isJSON5 = !!fs.existsSync(`${fixedModulePath}.json5`);
fixedModules = isJSON5
? JSON5.parse(fs.readFileSync(`${fixedModulePath}.json5`, 'utf8'))
: JSON.parse(fs.readFileSync(`${fixedModulePath}.json`, 'utf8'));
}
const filterIgnoredModules = (deps) => {
const newDeps = {};
Object.keys(deps).forEach((moduleName) => {
const value = deps[moduleName];
if (value !== '*') {
newDeps[moduleName] = value;
}
});
return newDeps;
};
const getAuditResults = async (when) => {
let audit = '{}';
try {
logger.info(`running '${when}' security review`);
const auditResults = await asyncExec('npm audit --json');
audit = auditResults.stdout;
} catch (error) {
if (error && error.stdout && error.stdout.length) {
logger.info(`Vulnerabilities found in '${when}'`);
audit = error.stdout;
} else {
logger.info(`Unable to generate audit '${when}':`, error);
}
}
return audit;
};
const getLatest = async (dependencies, fixedDependencies) => {
const newDependencies = {};
await Promise.all(Object.keys(dependencies).map(async (dependencyName) => {
let response = null;
if (fixedDependencies[dependencyName] === '*') {
logger.debug(`Updating of ${dependencyName} is set to skip.`);
newDependencies[dependencyName] = dependencies[dependencyName];
return;
}
try {
response = await asyncExec(`npm view ${dependencyName} version`);
} catch (err) {
if (verbose && !silent) {
logger.debug(`Unable to find version for package: ${dependencyName}`);
}
}
if (response && response.stdout && response.stdout.length) {
if (verbose && !silent) {
logger.debug(`Setting package to latest stable version: { ${dependencyName}: "${response.stdout.replace('\n', '')}" }`);
}
newDependencies[dependencyName] = response.stdout.replace('\n', '');
} else {
if (verbose && !silent) {
logger.debug(`Setting to existing package version:
{ ${dependencyName}: "${dependencies[dependencyName]}" }`);
}
newDependencies[dependencyName] = dependencies[dependencyName];
}
}));
return newDependencies;
};
const printReport = (text) => {
logger.info(`\n\n${text}`);
};
const saveJSON = (jsonReport) => {
const filePath = path.join(parentDir, 'updatedModules.json');
fs.writeFileSync(filePath, JSON.stringify(jsonReport));
};
const saveReport = (html) => {
const filePath = path.join(parentDir, 'updatedModules.html');
fs.writeFileSync(filePath, html);
};
const upgradePackage = async () => {
if (!silent) {
logger.info('Retrieving Primary and Dev Dependencies...');
}
let latestDevDeps = {};
let latestDeps = {};
let auditBefore;
// retrieve dependencies in parrallel
await Promise.all(
[auditBefore = runAudit ? await getAuditResults('before') : '{}'],
[latestDevDeps = await getLatest(currentPackage.devDependencies, fixedModules.devDependencies)],
[latestDeps = await getLatest(currentPackage.dependencies, fixedModules.dependencies)],
);
const newFixedDevDeps = filterIgnoredModules(fixedModules.devDependencies);
const newFixedDeps = filterIgnoredModules(fixedModules.dependencies);
const devDependencies = { ...latestDevDeps, ...newFixedDevDeps };
const dependencies = { ...latestDeps, ...newFixedDeps };
// decide wether or not to overwrite the current package or create a package.json.new
const fileName = `package.json${overwrite ? '' : '.new'}`;
const newPackagePath = path.join(parentDir, fileName);
const newPackage = stableStringify({
...currentPackage,
devDependencies,
dependencies,
}, { space: 2 });
fs.writeFile(newPackagePath, newPackage, async (err) => {
if (err) {
logger.error(`Problem writing new ${fileName} to:\n ${newPackagePath}`, err);
process.exit(1);
} else {
if (!silent) {
logger.info(`New ${fileName} saved to:\n ${newPackagePath}\n`);
}
let auditAfter = '{}';
let fixReport = '';
if (overwrite) {
if (!silent) {
logger.info('installing new modules');
}
if (upgrade) {
try {
await asyncExec('npm install');
} catch (error) {
logger.error('Failed to install new modules, aborting upgrade.', error);
process.exit(1);
}
}
if (runAudit) {
if (fixAudit) {
if (!silent) {
logger.info('checking module security');
}
try {
fixReport = (await asyncExec('npm audit fix')).stdout;
} catch (error) {
logger.error('Failed to fix node modules, aborting upgrade.', error);
process.exit(1);
}
if (verbose && !silent) {
logger.info('audit fix result:', fixReport);
}
}
auditAfter = await getAuditResults('after');
}
}
const { html, json: jsonReport, txt } = report
? generateReport(
currentPackage,
dependencies,
devDependencies,
latestDeps,
latestDevDeps,
auditBefore,
fixReport,
auditAfter,
)
: {};
if (json) {
saveJSON(jsonReport);
}
if (saveReportToFile) {
saveReport(html);
} else if (report) {
printReport(txt);
}
}
});
};
try {
upgradePackage();
} catch (err) {
logger.error('There was a problem upgrading your node modules:', err);
process.exit(1);
}