forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-dependency.ts
executable file
·217 lines (189 loc) · 6.03 KB
/
update-dependency.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
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
#!/usr/bin/env node
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import * as path from 'path';
import * as utils from './utils';
import packageJson from 'package-json';
import commander from 'commander';
import semver from 'semver';
let versionCache = new Map();
const tags = /^([~^]?)([\w.]*)$/;
async function getVersion(pkg: string, specifier: string) {
let key = JSON.stringify([pkg, specifier]);
if (versionCache.has(key)) {
return versionCache.get(key);
}
if (semver.validRange(specifier) === null) {
// We have a tag, with possibly a range specifier, such as ^latest
let match = specifier.match(tags);
if (match === null) {
throw Error(`Invalid version specifier: ${specifier}`);
}
// Look up the actual version corresponding to the tag
let { version } = await packageJson(pkg, { version: match[2] });
specifier = match[1] + version;
}
versionCache.set(key, specifier);
return specifier;
}
/**
* A very simple subset comparator
*
* @returns true if we can determine if range1 is a subset of range2, otherwise false
*
* #### Notes
* This will not be able to determine if range1 is a subset of range2 in many cases.
*/
function subset(range1: string, range2: string): boolean {
try {
const [, r1, version1] = range1.match(tags);
const [, r2] = range2.match(tags);
return (
['', '~', '^'].indexOf(r1) >= 0 &&
r1 === r2 &&
semver.valid(version1) &&
semver.satisfies(version1, range2)
);
} catch (e) {
return false;
}
}
async function handleDependency(
dependencies: { [key: string]: string },
dep: string,
specifier: string,
minimal: boolean
): Promise<{ updated: boolean; log: string[] }> {
let log = [];
let updated = false;
let newRange = await getVersion(dep, specifier);
let oldRange = dependencies[dep];
if (minimal && subset(newRange, oldRange)) {
log.push(`SKIPPING ${dep} ${oldRange} -> ${newRange}`);
} else {
log.push(`${dep} ${oldRange} -> ${newRange}`);
dependencies[dep] = newRange;
updated = true;
}
return { updated, log };
}
/**
* Handle an individual package on the path - update the dependency.
*/
async function handlePackage(
name: string | RegExp,
specifier: string,
packagePath: string,
dryRun = false,
minimal = false
) {
let fileUpdated = false;
let fileLog: string[] = [];
// Read in the package.json.
packagePath = path.join(packagePath, 'package.json');
let data: any;
try {
data = utils.readJSONFile(packagePath);
} catch (e) {
console.log('Skipping package ' + packagePath);
return;
}
// Update dependencies as appropriate.
for (let dtype of ['dependencies', 'devDependencies']) {
let deps = data[dtype] || {};
if (typeof name === 'string') {
let dep = name;
if (dep in deps) {
let { updated, log } = await handleDependency(
deps,
dep,
specifier,
minimal
);
if (updated) {
fileUpdated = true;
}
fileLog.push(...log);
}
} else {
let keys = Object.keys(deps);
keys.sort();
for (let dep of keys) {
if (dep.match(name)) {
let { updated, log } = await handleDependency(
deps,
dep,
specifier,
minimal
);
if (updated) {
fileUpdated = true;
}
fileLog.push(...log);
}
}
}
}
if (fileLog.length > 0) {
console.log(packagePath);
console.log(fileLog.join('\n'));
console.log();
}
// Write the file back to disk.
if (!dryRun && fileUpdated) {
utils.writePackageData(packagePath, data);
}
}
commander
.description('Update dependency versions')
.usage('[options] <package> [versionspec], versionspec defaults to ^latest')
.option('--dry-run', 'Do not perform actions, just print output')
.option('--regex', 'Package is a regular expression')
.option('--lerna', 'Update dependencies in all lerna packages')
.option('--path <path>', 'Path to package or monorepo to update')
.option('--minimal', 'only update if the change is substantial')
.arguments('<package> [versionspec]')
.action(
async (name: string | RegExp, version: string = '^latest', args: any) => {
let basePath = path.resolve(args.path || '.');
let pkg = args.regex ? new RegExp(name) : name;
if (args.lerna) {
let paths = utils.getLernaPaths(basePath).sort();
// We use a loop instead of Promise.all so that the output is in
// alphabetical order.
for (let pkgPath of paths) {
await handlePackage(pkg, version, pkgPath, args.dryRun, args.minimal);
}
}
await handlePackage(pkg, version, basePath, args.dryRun, args.minimal);
}
);
commander.on('--help', function() {
console.log(`
Examples
--------
Update the package 'webpack' to a specific version range:
update-dependency webpack ^4.0.0
Update all packages to the latest version, with a caret.
Only update if the update is substantial:
update-dependency --minimal --regex '.*' ^latest
Print the log of the above without actually making any changes.
update-dependency --dry-run --minimal --regex '.*' ^latest
Update all packages starting with '@jupyterlab/' to the version
the 'latest' tag currently points to, with a caret range:
update-dependency --regex '^@jupyterlab/' ^latest
Update all packages starting with '@jupyterlab/' in all lerna
workspaces and the root package.json to whatever version the 'next'
tag for each package currently points to (with a caret tag).
Update the version range only if the change is substantial.
update-dependency --lerna --regex --minimal '^@jupyterlab/' ^next
`);
});
commander.parse(process.argv);
// If no arguments supplied
if (!process.argv.slice(2).length) {
commander.outputHelp();
process.exit(1);
}