forked from fluid-project/fluid-publish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.js
417 lines (355 loc) · 14.7 KB
/
publish.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#! /usr/bin/env node
/*
Copyright 2015-2020 OCAD University
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
You may obtain a copy of the License at
https://raw.githubusercontent.com/fluid-project/fluid-publish/main/LICENSE
*/
/* eslint-env node */
"use strict";
var publish = {};
var path = require("path");
var extend = require("extend");
// Using the es6-template-strings module instead of the native ES6 Template Literals
// because Template Literals require the template to be surrounded in "`", which are not
// accepted as valid JSON ( the defaults are stored in the package.json file ).
var es6Template = require("es6-template-strings");
// execSync and log are added to the exported "publish" namespace so they can
// be stubbed in the tests.
publish.execSync = require("child_process").execSync;
publish.log = console.log; // eslint-disable-line no-console
/**
* Returns the contents of a package.json file as JSON object
*
* @param {String} moduleRoot - the path to the root where the package.json is
* located. Will use process.cwd() by default.
* @return {Object} - returns the contents of the package.json file as a JSON
* object.
*/
publish.getPkg = function (moduleRoot) {
moduleRoot = moduleRoot || process.cwd();
var modulePkgPath = path.join(moduleRoot, "package.json");
return require(modulePkgPath);
};
/**
* Processes the argv command line arguments into an object
* Options are expected to be key/value pairs in the format of `key=value`.
* When only a key is provided, that is no "=" symbol is found, the value
* is set to true.
*
* see: https://nodejs.org/docs/latest/api/process.html#process_process_argv
*
* @return {Object} - the CLI arguments as an options object
*/
publish.getCLIOpts = function () {
var opts = {};
process.argv.forEach(function (val, index) {
if (index > 1) {
var opt = val.split("=");
// convert "true" and "false" to the respective boolean value
if (opt[1] === "false") {
opt[1] = false;
} else if (opt[1] === "true") {
opt[1] = true;
}
opts[opt[0]] = opt.length < 2 ? true : opt[1];
}
});
return opts;
};
/**
* Creates a number with 0's padded on the left
*
* @param {Number} num - the number to padd with 0s
* @param {Number} width - the min-width of the number (default is 2),
* if the number is shorter it will be padded with zeros on the left.
* @return {String} - a string representation of the number with padding as needed
*/
publish.padZeros = function (num, width) {
width = width || 2;
var numstr = num ? num.toString() : "";
for (var i = numstr.length; i < width; i++) {
numstr = "0" + numstr;
}
return numstr;
};
/**
* Creates a date object from a git timestamp
*
* @param {String} timestamp - timestamp in seconds as returned by "git show -s --format=%ct HEAD"
* @return {Object} - an object of date properties
*/
publish.fromTimestamp = function (timestamp) {
var timestampInMS = Number(timestamp) * 1000;
var date = new Date(timestampInMS);
return {
year: date.getUTCFullYear(),
month: date.getUTCMonth() + 1, // months are zero based by default
day: date.getUTCDate(),
hours: date.getUTCHours(),
minutes: date.getUTCMinutes(),
seconds: date.getUTCSeconds()
};
};
/**
* Converts a git timestamp into a particular profile of ISO8601 timestamp,
* with the format yyyymmddThhmmssZ
*
* @param {String} timestamp - timestamp in seconds as returned by "git show -s --format=%ct HEAD"
* @return {String} - the time in the ISO8601 format yyyymmddThhmmssZ
*/
publish.convertToISO8601 = function (timestamp) {
var date = publish.fromTimestamp(timestamp);
for (var key in date) {
date[key] = publish.padZeros(date[key]);
}
return date.year + date.month + date.day + "T" + date.hours + date.minutes + date.seconds + "Z";
};
/**
* Calls publish.execSync with a command crafted from a template string.
* If it is a test run, the command will only be logged to the console.
*
* @param {String} cmdTemplate - A string template of the command to execute.
* Can provide tokens in the form ${tokenName}
* @param {Object} cmdValues - the tokens and their replacement.
* e.g. {tokenName: "value to insert"}
* @param {String} hint - A string template of a hint for recovering from an error thrown by the executed command.
* Can provide tokens in the form ${tokenName}
* @param {Boolean} isTest - indicates if this is a test run or not. If it is
* a test run, the command will be logged but not executed.
* @param {Object} options - provide options to underlying execSync command
*
* @return {Buffer|String} - the stdout from the command.
* @throws {Error} - will contain the entire result from node's child_process.execSync() error
*/
publish.execSyncFromTemplate = function (cmdTemplate, cmdValues, hint, isTest, options) {
var cmdStr = es6Template(cmdTemplate, cmdValues);
publish.log("Executing Command: " + cmdStr);
if (!isTest) {
try {
return publish.execSync(cmdStr, options);
} catch (error) {
var hintStr = es6Template(hint, cmdValues);
publish.log("Hint: " + hintStr);
throw (error);
}
}
};
/**
* Throws an error if there are any uncommitted changes
*
* @param {Object} options - e.g. {"changesCmd": "git status -s -uno", "changesHint": "change hint"}
* @throws {Error} - An error object with a message containing a list of uncommitted changes.
*/
publish.checkChanges = function (options) {
var changes = publish.execSyncFromTemplate(options.changesCmd);
if (changes.length) {
publish.log("Hint: " + options.changesHint);
throw new Error("You have uncommitted changes\n" + changes);
}
};
/**
* Checks that the remote exists. If it does not exist an error is thrown.
*
* @param {Object} options - e.g. {
* "checkRemoteCmd": "git ls-remote --exit-code ${remote}",
* "remoteName": "upstream",
* "checkRemoteHint": "check remote hint"
* }
*/
publish.checkRemote = function (options) {
publish.execSyncFromTemplate(options.checkRemoteCmd, {
remote: options.remoteName
}, options.checkRemoteHint);
};
/**
* Updates the package.json version to the specified version
* This does not commit the change, it will only modify the file.
*
* @param {String} version - the version to set in the package.json file
* @param {Object} options - e.g. {"versionCmd": "npm version --no-git-tag-version ${version}"}
*/
publish.setVersion = function (version, options) {
publish.execSyncFromTemplate(options.versionCmd, {
version: version
});
};
/**
* Calculates the current dev version of the package.
* Will include dev version name if run on a branch other than master or main, or if
* the devName option is provided.
*
* @param {String} moduleVersion - The version of the module (e.g. X.x.x)
* @param {Object} options - e.g. {
* "rawTimestampCmd": "git show -s --format=%ct HEAD",
* "revisionCmd": "git rev-parse --verify --short HEAD",
* "branchCmd": "git rev-parse --abbrev-ref HEAD",
* "devVersion": "${version}-${preRelease}.${timestamp}.${revision}",
* "devName": "",
* "devTag": "dev"
* }
* @return {String} - the current dev version number
*/
publish.getDevVersion = function (moduleVersion, options) {
var rawTimestamp = publish.execSyncFromTemplate(options.rawTimestampCmd);
var timestamp = publish.convertToISO8601(rawTimestamp);
var revision = publish.execSyncFromTemplate(options.revisionCmd).toString().trim();
var branch = publish.execSyncFromTemplate(options.branchCmd).toString().trim();
var newStr = es6Template(options.devVersion, {
version: moduleVersion,
preRelease: options.devTag,
timestamp: timestamp,
revision: revision
});
if (branch !== "master" && branch !== "main" || options.devName) {
newStr = newStr + "." + (options.devName || branch);
}
return newStr;
};
/**
* Publishes the module to npm using the current version number in pacakge.json.
* If isTest is specified, it will instead create a tarball in the local directory.
*
* @param {Boolean} isTest - indicates if this is a test run or not
* @param {Boolean} isDev - indicates if this is a development (true) or standard (false) release
* @param {Object} options - e.g. {
* "packCmd": "npm pack",
* "publishCmd": "npm publish",
* "publishDevCmd": "npm publish --tag",
* "publishHint": "publish hint",
* "publishDevHint": "publish dev hint",
* "devTag": "dev",
* "otpFlag": "${command} --otp=${otp}",
* "otp"=123456
* }
*/
publish.pubImpl = function (isTest, isDev, options) {
if (isTest) {
// create a local tarball
publish.execSyncFromTemplate(options.packCmd);
} else {
// publish to npm
var pubCmd = isDev ? options.publishDevCmd : options.publishCmd;
var pubHint = isDev ? options.publishDevHint : options.publishHint;
if (options.otp) {
pubCmd = es6Template(options.otpFlag, {command: pubCmd, otp: options.otp});
}
publish.execSyncFromTemplate(pubCmd, options, pubHint, false, {stdio: "inherit"});
}
};
/**
* Applies a version control tag to the latest commit
*
* @param {Boolean} isTest - indicates if this is a test run or not
* @param {String} version - a string indicating the version
* @param {Object} options - e.g. {
* "vcTagCmd": "git tag -a v${version} -m 'Tagging the ${version} release'",
* "pushVCTagCmd": "git push ${remote} v${version}",
* "remoteName": "upstream",
* "vcTagHint": "vc tag hint",
* "pushVCTagHint": "push vc tag hint"
* }
*/
publish.tagVC = function (isTest, version, options) {
publish.execSyncFromTemplate(options.vcTagCmd, {
version: version,
remote: options.remoteName
}, options.vcTagHint, isTest);
publish.execSyncFromTemplate(options.pushVCTagCmd, {
version: version,
remote: options.remoteName
}, options.pushVCTagHint, isTest);
};
/**
* Restore the package.json file to the latest committed version.
*
* Used internally to reset version number changes in package.json
* @param {String} moduleRoot - the directory where the package.json file to
clean is located in.
* @param {Object} options - e.g. {"cleanCmd": "git checkout -- package.json"}
*/
publish.clean = function (moduleRoot, options) {
var originalDir = process.cwd();
// change to the module root directory
process.chdir(moduleRoot || "./");
// run the clean command
publish.execSyncFromTemplate(options.cleanCmd);
// restore the working directory
process.chdir(originalDir);
};
publish.getPublishPkgVersion = function () {
var publishPkg = publish.getPkg(__dirname);
publish.log(publishPkg.name + " " + publishPkg.version);
return publishPkg.version;
};
/**
* Publishes a development build.
* This creates a release named after the version, but with the build stamp
* appended to the end. By default this will create a release with version
* X.x.x-prerelease.yyyymmddThhmmssZ.shortHash where X.x.x is sourced
* from the version number in the package.json file, -pre-release is from the
* devTag option (also applied as a tag to the release), and the build id
* (yyyymmddThhmmssZ.shortHash) is generated based on the latest commit.
*
* @param {Boolean} isTest - indicates if this is a test run
* @param {Object} options - see defaultOptions in package.json for possible values
*/
publish.dev = function (isTest, options) {
var publishPkg = publish.getPkg(__dirname);
var opts = extend(true, {}, publishPkg.defaultOptions, options);
// The package.json file of the top level package which is
// running this module.
var modulePkg = publish.getPkg(opts.moduleRoot);
// Ensure no uncommitted changes
publish.checkChanges(opts);
var devVersion = publish.getDevVersion(modulePkg.version, opts);
// set the version number
publish.setVersion(devVersion, opts);
try {
// publish
publish.pubImpl(isTest, true, opts);
} finally {
// cleanup changes
publish.clean(opts.moduleRoot, opts);
};
};
/**
* Publishes a standard release build.
* This creates a release named after the version in the package.json file.
* It will not increase the version number, this must be done separately.
* However, it will create a tag and publish this tag to the version control
* system.
*
* @param {Boolean} isTest - indicates if this is a test run
* @param {Object} options - see defaultOptions in package.json for possible values
*/
publish.standard = function (isTest, options) {
var publishPkg = publish.getPkg(__dirname);
var opts = extend(true, {}, publishPkg.defaultOptions, options);
// The package.json file of the top level package which is
// running this module.
var modulePkg = publish.getPkg(opts.moduleRoot);
// Ensure no uncommitted changes
publish.checkChanges(opts);
// Ensure that the specified remote repository exists
publish.checkRemote(opts);
// create version control tag
publish.tagVC (isTest, modulePkg.version, opts);
// publish
publish.pubImpl(isTest, false, opts);
};
module.exports = publish;
if (require.main === module) {
var opts = publish.getCLIOpts();
var isTest = opts["--test"];
// allow to use the more standard "--otp" form to provide the one-time password
opts.otp = opts.otp || opts["--otp"];
if (opts["--version"]) {
publish.getPublishPkgVersion();
} else if (opts["--standard"]) {
publish.standard(isTest, opts);
} else {
publish.dev(isTest, opts);
}
}