-
Notifications
You must be signed in to change notification settings - Fork 3
/
ver.js
executable file
·339 lines (295 loc) · 9.21 KB
/
ver.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/usr/bin/env node
"use strict";
const minOpts = {
boolean: [
"g", "gitless",
"h", "help",
"P", "packageless",
"p", "prefix",
"v", "version",
],
string: [
"b", "base",
"c", "command",
"d", "date",
"r", "replace",
"_",
],
alias: {
b: "base",
c: "command",
d: "date",
g: "gitless",
h: "help",
P: "packageless",
p: "prefix",
r: "replace",
v: "version",
}
};
const commands = ["patch", "minor", "major"];
let args = require("minimist")(process.argv.slice(2), minOpts);
args = fixArgs(commands, args, minOpts);
let [level, ...files] = args._;
if (args.version) {
console.info(require(require("path").join(__dirname, "package.json")).version);
process.exit(0);
}
if (!commands.includes(level) || args.help) {
console.info(`usage: ver [options] command [files...]
Semantically increment a project's version in multiple files.
Commands:
patch Increment patch 0.0.x version
minor Increment minor 0.x.0 version
major Increment major x.0.0 version
Arguments:
files Files to do version replacement in. The nearest package.json and
package-lock.json will always be included unless the -P argument is given.
Options:
-b, --base <version> Base version to use. Default is parsed from the nearest package.json
-c, --command <command> Run a command after files are updated but before git commit and tag
-d, --date [<date>] Replace dates in format YYYY-MM-DD with current or given date
-r, --replace <str> Additional replacement in the format "s#regexp#replacement#flags"
-P, --packageless Do not include package.json and package-lock.json unless explicitely given
-g, --gitless Do not create a git commit and tag
-p, --prefix Prefix git tags with a "v" character
-v, --version Print the version
-h, --help Print this help
Examples:
$ ver patch
$ ver minor build.js
$ ver major -p build.js
$ ver patch -c 'npm run build'`);
exit();
}
const replacements = [];
if (args.replace) {
args.replace = Array.isArray(args.replace) ? args.replace : [args.replace];
for (const replaceStr of args.replace) {
let [_, re, replacement, flags] = (/^s#(.+?)#(.+?)#(.*?)$/.exec(replaceStr) || []);
if (!re || !replacement) {
exit(new Error(`Invalid replace string: ${replaceStr}`));
}
re = new RegExp(re, flags || undefined);
replacements.push({re, replacement});
}
}
let date = parseMixedArg(args.date);
if (date) {
if (date === true) {
date = (new Date()).toISOString().substring(0, 10);
} else if (Array.isArray(date)) {
date = date[date.length - 1];
}
if (typeof date !== "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(date)) {
exit(`Invalid date argument: ${date}`);
}
}
const {promisify} = require("util");
const readFile = promisify(require("fs").readFile);
const writeFile = promisify(require("fs").writeFile);
const truncate = promisify(require("fs").truncate);
const stat = promisify(require("fs").stat);
const realpath = promisify(require("fs").realpath);
const semver = require("semver");
const {basename, dirname, join} = require("path");
const findUp = require("find-up");
function find(name, base) {
if (!base) {
return findUp(name);
} else {
return findUp(directory => {
if (directory.length < base.length) {
return findUp.stop;
} else {
return findUp.exists(join(directory, name));
}
});
}
}
async function main() {
let packageFile = await find("package.json");
if (packageFile) packageFile = await realpath(packageFile);
// try to open package.json if it exists
let pkg, pkgStr;
if (packageFile) {
try {
pkgStr = await readFile(packageFile, "utf8");
pkg = JSON.parse(pkgStr);
} catch (err) {
throw new Error(`Error reading ${packageFile}: ${err.message}`);
}
}
// obtain old version
let baseVersion;
if (!args.base) {
if (pkg) {
if (pkg.version) {
baseVersion = pkg.version;
} else {
throw new Error(`No "version" field found in ${packageFile}`);
}
} else {
throw new Error(`Unable to obtain base version, either create package.json or specify --base`);
}
} else {
baseVersion = args.base;
}
// validate old version
if (!semver.valid(baseVersion)) {
throw new Error(`Invalid base version: ${baseVersion}`);
}
// de-glob files args which is needed for dumb shells like
// powershell that do not support globbing
files = await require("fast-glob")(files);
// convert paths to absolute
files = await Promise.all(files.map(file => realpath(file)));
// remove duplicate paths
files = Array.from(new Set(files));
if (!args.packageless) {
// include package.json if present
if (packageFile && !files.includes(packageFile)) {
files.push(packageFile);
}
// include package-lock.json if present
let packageLockFile = await find("package-lock.json", dirname(packageFile));
if (packageLockFile) packageLockFile = await realpath(packageLockFile);
if (packageLockFile && !files.includes(packageLockFile)) {
files.push(packageLockFile);
}
}
if (!files.length) {
throw new Error(`Found no files to do replacements in`);
}
// verify files exist
for (const file of files) {
const stats = await stat(file);
if (!stats.isFile() && !stats.isSymbolicLink()) {
throw new Error(`${file} is not a file`);
}
}
// update files
const newVersion = semver.inc(baseVersion, level);
for (const file of files) {
if (basename(file) === "package.json") {
await updateFile({file, baseVersion, newVersion, replacements, pkgStr});
} else {
await updateFile({file, baseVersion, newVersion, replacements});
}
}
if (args.command) {
await run(args.command);
}
if (!args["gitless"]) {
// create git commit and tag
const tagName = args["prefix"] ? `v${newVersion}` : newVersion;
try {
await run(`git commit -a -m ${newVersion}`);
await run(`git tag -f -m ${newVersion} ${tagName}`);
} catch (err) {
return process.exit(1);
}
}
exit();
}
async function run(cmd) {
console.info(`+ ${cmd}`);
const child = require("execa")(cmd, {shell: true});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
await child;
}
async function updateFile({file, baseVersion, newVersion, replacements, pkgStr}) {
let oldData;
if (pkgStr) {
oldData = pkgStr;
} else {
oldData = await readFile(file, "utf8");
}
let newData;
if (pkgStr) {
const re = new RegExp(`("version":[^]*?")${esc(baseVersion)}(")`);
newData = pkgStr.replace(re, (_, p1, p2) => `${p1}${newVersion}${p2}`);
} else if (basename(file) === "package-lock.json") {
// special case for package-lock.json which contains a lot of version
// strings which make regexp replacement risky. From a few tests on
// Node.js 12, key order seems to be preserved through parse and stringify.
newData = JSON.parse(oldData);
newData.version = newVersion;
newData = JSON.stringify(newData, null, 2) + "\n";
} else {
const re = new RegExp(esc(baseVersion), "g");
newData = oldData.replace(re, newVersion);
}
if (date) {
const re = /([^0-9]|^)[0-9]{4}-[0-9]{2}-[0-9]{2}([^0-9]|$)/g;
newData = newData.replace(re, (_, p1, p2) => `${p1}${date}${p2}`);
}
if (replacements.length) {
for (const replacement of replacements) {
newData = newData.replace(replacement.re, replacement.replacement);
}
}
if (oldData === newData) {
throw new Error(`No replacement made in ${file}`);
} else {
await write(file, newData);
}
}
async function write(file, content) {
if (require("os").platform() === "win32") {
// truncate and append on windows to preserve file metadata
await truncate(file, 0);
await writeFile(file, content, {encoding: "utf8", flag: "r+"});
} else {
await writeFile(file, content, {encoding: "utf8"});
}
}
function parseMixedArg(arg) {
if (arg === "") {
return true;
} else if (typeof arg === "string") {
return arg.includes(",") ? arg.split(",") : [arg];
} else if (Array.isArray(arg)) {
return arg;
} else {
return Boolean(arg);
}
}
// handle minimist parsing error like '-d patch'
function fixArgs(commands, args, minOpts) {
for (const key of Object.keys(minOpts.alias)) {
delete args[key];
}
if (commands.includes(args.date)) {
args._ = [args.date, ...args._];
args.date = true;
}
if (commands.includes(args.base)) {
args._ = [args.base, ...args._];
args.base = true;
}
if (commands.includes(args.command)) {
args._ = [args.command, ...args._];
args.command = "";
}
if (commands.includes(args.replace)) {
args._ = [args.replace, ...args._];
args.replace = "";
}
if (commands.includes(args.packageless)) {
args._ = [args.packageless, ...args._];
args.packageless = true;
}
return args;
}
function esc(str) {
return str.replace(/[|\\{}()[\]^$+*?.-]/g, "\\$&");
}
function exit(err) {
if (err) {
console.info(String(err.message || err).trim());
}
process.exit(err ? 1 : 0);
}
main().then(exit).catch(exit);