-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (52 loc) · 1.85 KB
/
index.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
const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
const _ = require('lodash');
function parseJsonFile(filename) {
let obj = {};
try {
const file = fs.readFileSync(path.resolve(process.cwd(), filename), 'utf8');
obj = JSON.parse(file);
} catch (error) {
throw new Error(`${filename} could not be parsed.`);
}
return obj;
}
function getDependencyVersions(dependencies) {
return _.reduce(dependencies, (result, pkg, name) => {
const version = pkg.version || pkg;
result[name] = _.head(version.match(/(\d+\.\d+\.\d+(?:-.+)?)/));
return result;
}, {});
}
function objectMergeLeft(a, b) {
return _.reduce(a, (result, value, key) => {
result[key] = value;
if (!_.isEqual(value, b[key])) {
result[key] = b[key];
}
return result;
}, {});
}
function updatePackageJson(shrinkwrapFile, packageFile) {
const shrinkwrapJson = parseJsonFile(shrinkwrapFile);
const packageJson = parseJsonFile(packageFile);
const shrinkwrapVersions = getDependencyVersions(shrinkwrapJson.dependencies);
if (packageJson.dependencies) {
const dependencyVersions = getDependencyVersions(packageJson.dependencies);
packageJson.dependencies = objectMergeLeft(dependencyVersions, shrinkwrapVersions);
}
if (packageJson.devDependencies) {
const devDependencyVersions = getDependencyVersions(packageJson.devDependencies);
packageJson.devDependencies = objectMergeLeft(devDependencyVersions, shrinkwrapVersions);
}
fs.writeFileSync(path.resolve(__dirname, 'package.json'), JSON.stringify(packageJson, null, 2));
}
function createLockFile() {
exec('yarn install');
}
function shrinkwrapToLockfile(shrinkwrap = 'npm-shrinkwrap.json', packageJson = 'package.json') {
updatePackageJson(shrinkwrap, packageJson);
createLockFile();
}
module.exports = shrinkwrapToLockfile;