/
index.js
432 lines (343 loc) · 14 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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"use strict";
const os = require("os");
const path = require("path");
const pFinally = require("p-finally");
const pMap = require("p-map");
const pReduce = require("p-reduce");
const semver = require("semver");
const Command = require("@lerna/command");
const childProcess = require("@lerna/child-process");
const output = require("@lerna/output");
const collectUpdates = require("@lerna/collect-updates");
const npmDistTag = require("@lerna/npm-dist-tag");
const npmPublish = require("@lerna/npm-publish");
const { createRunner } = require("@lerna/run-lifecycle");
const batchPackages = require("@lerna/batch-packages");
const runParallelBatches = require("@lerna/run-parallel-batches");
const versionCommand = require("@lerna/version");
const createTempLicenses = require("./lib/create-temp-licenses");
const getCurrentSHA = require("./lib/get-current-sha");
const getCurrentTags = require("./lib/get-current-tags");
const getTaggedPackages = require("./lib/get-tagged-packages");
const getPackagesWithoutLicense = require("./lib/get-packages-without-license");
const gitCheckout = require("./lib/git-checkout");
const removeTempLicenses = require("./lib/remove-temp-licenses");
const verifyNpmRegistry = require("./lib/verify-npm-registry");
const verifyNpmPackageAccess = require("./lib/verify-npm-package-access");
module.exports = factory;
function factory(argv) {
return new PublishCommand(argv);
}
class PublishCommand extends Command {
get otherCommandConfigs() {
// back-compat
return ["version"];
}
initialize() {
if (this.options.skipNpm) {
this.logger.warn("deprecated", "Instead of --skip-npm, call `lerna version` directly");
return versionCommand(this._argv).then(() => false);
}
if (this.options.canary) {
this.logger.info("canary", "enabled");
}
if (this.options.requireScripts) {
this.logger.info("require-scripts", "enabled");
}
// https://docs.npmjs.com/misc/config#save-prefix
this.savePrefix = this.options.exact ? "" : "^";
this.npmConfig = {
npmClient: this.options.npmClient || "npm",
registry: this.options.registry,
};
return Promise.resolve(this.findVersionedUpdates()).then(result => {
if (!result) {
// early return from nested VersionCommand
return false;
}
if (!result.updates.length) {
this.logger.success("No updated packages to publish");
// still exits zero, aka "ok"
return false;
}
this.updates = result.updates;
this.updatesVersions = new Map(result.updatesVersions);
this.runPackageLifecycle = createRunner(this.options);
this.packagesToPublish = this.updates.map(({ pkg }) => pkg).filter(pkg => !pkg.private);
this.batchedPackages = this.toposort
? batchPackages(
this.packagesToPublish,
this.options.rejectCycles,
// Don't sort based on devDependencies because that would increase the chance of dependency cycles
// causing less-than-ideal a publishing order.
"dependencies"
)
: [this.packagesToPublish];
return Promise.resolve()
.then(() => this.prepareRegistryActions())
.then(() => this.prepareLicenseActions());
});
}
execute() {
this.enableProgressBar();
this.logger.info("publish", "Publishing packages to npm...");
let chain = Promise.resolve();
if (this.options.canary) {
chain = chain.then(() => this.updateCanaryVersions());
}
chain = chain.then(() => this.resolveLocalDependencyLinks());
chain = chain.then(() => this.annotateGitHead());
chain = chain.then(() => this.npmPublish());
chain = chain.then(() => this.resetChanges());
if (this.options.tempTag) {
chain = chain.then(() => this.npmUpdateAsLatest());
}
return chain.then(() => {
const count = this.packagesToPublish.length;
const message = this.packagesToPublish.map(pkg => ` - ${pkg.name}@${pkg.version}`);
output("Successfully published:");
output(message.join(os.EOL));
this.logger.success("published", "%d %s", count, count === 1 ? "package" : "packages");
});
}
findVersionedUpdates() {
if (this.options.bump === "from-git") {
return this.detectFromGit();
}
if (this.options.canary) {
// TODO: throw useful error when canary attempted on tagged release?
return this.detectCanaryVersions();
}
return versionCommand(this._argv);
}
detectFromGit() {
let chain = Promise.resolve();
chain = chain.then(() => getCurrentTags(this.execOpts));
chain = chain.then(taggedPackageNames => {
if (!taggedPackageNames.length) {
this.logger.notice("from-git", "No tagged release found");
return [];
}
if (this.project.isIndependent()) {
return taggedPackageNames.map(name => this.packageGraph.get(name));
}
return getTaggedPackages(this.packageGraph, this.project.rootPath, this.execOpts);
});
return chain.then(updates => {
const updatesVersions = updates.map(({ pkg }) => [pkg.name, pkg.version]);
return { updates, updatesVersions };
});
}
detectCanaryVersions() {
const { bump = "prepatch", preid = "alpha" } = this.options;
// "prerelease" and "prepatch" are identical, for our purposes
const release = bump.startsWith("pre") ? bump.replace("release", "patch") : `pre${bump}`;
let chain = Promise.resolve();
// find changed packages since last release, if any
chain = chain.then(() =>
collectUpdates(this.filteredPackages, this.packageGraph, this.execOpts, {
bump: "prerelease",
canary: true,
ignoreChanges: this.options.ignoreChanges,
})
);
const makeVersion = described => {
// FIXME: this will blow up when `described` doesn't match the regex (returns null)
const [, baseVersion, refCount, buildMeta] = /^(?:.*@)?(.*)-(\d+)-g([0-9a-f]+)$/.exec(described);
// the next version is bumped without concern for preid or current index
const nextVersion = semver.inc(baseVersion, release.replace("pre", ""));
// semver.inc() starts a new prerelease at .0, git describe starts at .1
// and build metadata is always ignored when comparing dependency ranges
return `${nextVersion}-${preid}.${refCount - 1}+${buildMeta}`;
};
const gitDescribeMatching = globFilter =>
childProcess.execSync("git", ["describe", "--match", globFilter], this.execOpts);
if (this.project.isIndependent()) {
// each package is described against its tags only
chain = chain.then(updates =>
pMap(updates, ({ pkg }) => {
const described = gitDescribeMatching(`${pkg.name}@*`);
const version = makeVersion(described);
return [pkg.name, version];
}).then(updatesVersions => ({ updates, updatesVersions }))
);
} else {
// all packages are described against the last tag
chain = chain.then(updates => {
const described = gitDescribeMatching(`${this.options.tagVersionPrefix}*.*.*`);
const version = makeVersion(described);
const updatesVersions = updates.map(({ pkg }) => [pkg.name, version]);
return { updates, updatesVersions };
});
}
return chain;
}
prepareLicenseActions() {
return Promise.resolve()
.then(() => getPackagesWithoutLicense(this.project, this.packagesToPublish))
.then(packagesWithoutLicense => {
if (packagesWithoutLicense.length && !this.project.licensePath) {
this.packagesToBeLicensed = [];
this.logger.warn(
"ENOLICENSE",
`Packages ${packagesWithoutLicense.map(pkg => pkg.name).join(", ")} are missing a license`
);
} else {
this.packagesToBeLicensed = packagesWithoutLicense;
}
});
}
prepareRegistryActions() {
return Promise.resolve()
.then(() => verifyNpmRegistry(this.project.rootPath, this.npmConfig))
.then(() => verifyNpmPackageAccess(this.packagesToPublish, this.project.rootPath, this.npmConfig));
}
updateCanaryVersions() {
const publishableUpdates = this.updates.filter(node => !node.pkg.private);
return pMap(publishableUpdates, ({ pkg, localDependencies }) => {
pkg.version = this.updatesVersions.get(pkg.name);
for (const [depName, resolved] of localDependencies) {
// other canary versions need to be updated, non-canary is a no-op
const depVersion = this.updatesVersions.get(depName) || this.packageGraph.get(depName).pkg.version;
// it no longer matters if we mutate the shared Package instance
pkg.updateLocalDependency(resolved, depVersion, this.savePrefix);
}
// writing changes to disk handled in annotateGitHead()
});
}
resolveLocalDependencyLinks() {
// resolve relative file: links to their actual version range
const updatesWithLocalLinks = this.updates.filter(
({ pkg, localDependencies }) =>
!pkg.private &&
localDependencies.size &&
Array.from(localDependencies.values()).some(({ type }) => type === "directory")
);
return pMap(updatesWithLocalLinks, ({ pkg, localDependencies }) => {
for (const [depName, resolved] of localDependencies) {
// regardless of where the version comes from, we can't publish "file:../sibling-pkg" specs
const depVersion = this.updatesVersions.get(depName) || this.packageGraph.get(depName).pkg.version;
// it no longer matters if we mutate the shared Package instance
pkg.updateLocalDependency(resolved, depVersion, this.savePrefix);
}
// writing changes to disk handled in annotateGitHead()
});
}
annotateGitHead() {
const gitHead = getCurrentSHA(this.execOpts);
return pMap(this.packagesToPublish, pkg => {
// provide gitHead property that is normally added during npm publish
pkg.set("gitHead", gitHead);
return pkg.serialize();
});
}
resetChanges() {
// the package.json files are changed (by gitHead if not --canary)
// and we should always leave the working tree clean
return pReduce(this.project.packageConfigs, (_, pkgGlob) =>
gitCheckout(`${pkgGlob}/package.json`, this.execOpts)
).then(() =>
// --skip-git should not leave unstaged changes behind
gitCheckout(this.project.manifest.location, this.execOpts)
);
}
execScript(pkg, script) {
const scriptLocation = path.join(pkg.location, "scripts", script);
try {
// eslint-disable-next-line import/no-dynamic-require, global-require
require(scriptLocation);
} catch (ex) {
this.logger.silly("execScript", `No ${script} script found at ${scriptLocation}`);
}
}
runPrepublishScripts(pkg) {
return Promise.resolve()
.then(() => this.runPackageLifecycle(pkg, "prepare"))
.then(() => this.runPackageLifecycle(pkg, "prepublishOnly"));
}
removeTempLicensesOnError(error) {
return Promise.resolve()
.then(() =>
removeTempLicenses(this.packagesToBeLicensed).catch(removeError => {
this.logger.error(
"licenses",
"error removing temporary license files",
removeError.stack || removeError
);
})
)
.then(() => {
// restore original error into promise chain
throw error;
});
}
npmPublish() {
const tracker = this.logger.newItem("npmPublish");
// if we skip temp tags we should tag with the proper value immediately
const distTag = this.options.tempTag ? "lerna-temp" : this.getDistTag();
let chain = Promise.resolve();
chain = chain.then(() => createTempLicenses(this.project.licensePath, this.packagesToBeLicensed));
chain = chain.then(() => this.runPrepublishScripts(this.project.manifest));
chain = chain.then(() =>
pMap(this.updates, ({ pkg }) => {
if (this.options.requireScripts) {
this.execScript(pkg, "prepublish");
}
return this.runPrepublishScripts(pkg);
})
);
tracker.addWork(this.packagesToPublish.length);
const mapPackage = pkg => {
tracker.verbose("publishing", pkg.name);
return npmPublish(pkg, distTag, this.npmConfig).then(() => {
tracker.info("published", pkg.name);
tracker.completeWork(1);
if (this.options.requireScripts) {
this.execScript(pkg, "postpublish");
}
return this.runPackageLifecycle(pkg, "postpublish");
});
};
chain = chain.then(() => runParallelBatches(this.batchedPackages, this.concurrency, mapPackage));
chain = chain.then(() => this.runPackageLifecycle(this.project.manifest, "postpublish"));
chain = chain.then(() => removeTempLicenses(this.packagesToBeLicensed));
// remove temporary license files if _any_ error occurs _anywhere_ in the promise chain
chain = chain.catch(error => this.removeTempLicensesOnError(error));
return pFinally(chain, () => tracker.finish());
}
npmUpdateAsLatest() {
const distTag = this.getDistTag() || "latest";
const tracker = this.logger.newItem("npmUpdateAsLatest");
tracker.addWork(this.packagesToPublish.length);
let chain = Promise.resolve();
chain = chain.then(() =>
runParallelBatches(this.batchedPackages, this.concurrency, pkg =>
this.updateTag(pkg, distTag).then(() => {
tracker.info("dist-tag", "%s@%s => %j", pkg.name, pkg.version, distTag);
tracker.completeWork(1);
})
)
);
return pFinally(chain, () => tracker.finish());
}
updateTag(pkg, distTag) {
return Promise.resolve()
.then(() => npmDistTag.check(pkg, "lerna-temp", this.npmConfig))
.then(exists => {
if (exists) {
return npmDistTag.remove(pkg, "lerna-temp", this.npmConfig);
}
})
.then(() => npmDistTag.add(pkg, distTag, this.npmConfig));
}
getDistTag() {
if (this.options.npmTag) {
return this.options.npmTag;
}
if (this.options.canary) {
return "canary";
}
// undefined defaults to "latest" OR whatever is in pkg.publishConfig.tag
}
}
module.exports.PublishCommand = PublishCommand;