-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
index.js
233 lines (187 loc) · 6.73 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
"use strict";
const _ = require("lodash");
const dedent = require("dedent");
const execa = require("execa");
const log = require("npmlog");
const PackageGraph = require("@lerna/package-graph");
const Project = require("@lerna/project");
const writeLogFile = require("@lerna/write-log-file");
const ValidationError = require("@lerna/validation-error");
const cleanStack = require("./lib/clean-stack");
const logPackageError = require("./lib/log-package-error");
const warnIfHanging = require("./lib/warn-if-hanging");
const DEFAULT_CONCURRENCY = 4;
class Command {
constructor(argv) {
log.pause();
log.heading = "lerna";
this._argv = argv;
log.silly("argv", argv);
// "FooCommand" => "foo"
this.name = this.constructor.name.replace(/Command$/, "").toLowerCase();
// composed commands are called from other commands, like publish -> version
this.composed = typeof argv.composed === "string" && argv.composed !== this.name;
if (!this.composed) {
// composed commands have already logged the lerna version
log.notice("cli", `v${argv.lernaVersion}`);
}
// launch the command
let runner = new Promise((resolve, reject) => {
// run everything inside a Promise chain
let chain = Promise.resolve();
chain = chain.then(() => {
this.project = new Project(argv.cwd);
});
chain = chain.then(() => this.configureOptions());
chain = chain.then(() => this.configureProperties());
chain = chain.then(() => this.configureLogging());
chain = chain.then(() => this.runValidations());
chain = chain.then(() => this.runPreparations());
chain = chain.then(() => this.runCommand());
chain.then(
result => {
warnIfHanging();
resolve(result);
},
err => {
if (err.pkg) {
// Cleanly log specific package error details
logPackageError(err);
} else if (err.name !== "ValidationError") {
// npmlog does some funny stuff to the stack by default,
// so pass it directly to avoid duplication.
log.error("", cleanStack(err, this.constructor.name));
}
// ValidationError does not trigger a log dump, nor do external package errors
if (err.name !== "ValidationError" && !err.pkg) {
writeLogFile(this.project.rootPath);
}
warnIfHanging();
// error code is handled by cli.fail()
reject(err);
}
);
});
// passed via yargs context in tests, never actual CLI
/* istanbul ignore else */
if (argv.onResolved || argv.onRejected) {
runner = runner.then(argv.onResolved, argv.onRejected);
// when nested, never resolve inner with outer callbacks
delete argv.onResolved; // eslint-disable-line no-param-reassign
delete argv.onRejected; // eslint-disable-line no-param-reassign
}
// proxy "Promise" methods to "private" instance
this.then = (onResolved, onRejected) => runner.then(onResolved, onRejected);
this.catch = onRejected => runner.catch(onRejected);
}
get requiresGit() {
return true;
}
// Override this to inherit config from another command.
// For example `changed` inherits config from `publish`.
get otherCommandConfigs() {
return [];
}
configureOptions() {
// Command config object normalized to "command" namespace
const commandConfig = this.project.config.command || {};
// The current command always overrides otherCommandConfigs
const overrides = [this.name, ...this.otherCommandConfigs].map(key => commandConfig[key]);
this.options = _.defaults(
{},
// CLI flags, which if defined overrule subsequent values
this._argv,
// Namespaced command options from `lerna.json`
...overrides,
// Global options from `lerna.json`
this.project.config
);
}
configureProperties() {
const { concurrency, sort, maxBuffer } = this.options;
this.concurrency = Math.max(1, +concurrency || DEFAULT_CONCURRENCY);
this.toposort = sort === undefined || sort;
this.execOpts = {
cwd: this.project.rootPath,
maxBuffer,
};
}
configureLogging() {
const { loglevel } = this.options;
if (loglevel) {
log.level = loglevel;
}
// handle log.success()
log.addLevel("success", 3001, { fg: "green", bold: true });
// create logger that subclasses use
this.logger = log.newGroup(this.name);
// emit all buffered logs at configured level and higher
log.resume();
}
enableProgressBar() {
// istanbul ignore else
if (this.options.progress) {
this.logger.enableProgress();
}
}
gitInitialized() {
const opts = {
cwd: this.project.rootPath,
// don't throw, just want boolean
reject: false,
// only return code, no stdio needed
stdio: "ignore",
};
return execa.sync("git", ["rev-parse"], opts).code === 0;
}
runValidations() {
if ((this.options.since !== undefined || this.requiresGit) && !this.gitInitialized()) {
throw new ValidationError("ENOGIT", "The git binary was not found, or this is not a git repository.");
}
if (!this.project.manifest) {
throw new ValidationError("ENOPKG", "`package.json` does not exist, have you run `lerna init`?");
}
if (!this.project.version) {
throw new ValidationError("ENOLERNA", "`lerna.json` does not exist, have you run `lerna init`?");
}
if (this.options.independent && !this.project.isIndependent()) {
throw new ValidationError(
"EVERSIONMODE",
dedent`
You ran lerna with --independent or -i, but the repository is not set to independent mode.
To use independent mode you need to set lerna.json's "version" property to "independent".
Then you won't need to pass the --independent or -i flags.
`
);
}
}
runPreparations() {
if (!this.composed && this.project.isIndependent()) {
// composed commands have already logged the independent status
log.info("versioning", "independent");
}
let chain = Promise.resolve();
chain = chain.then(() => this.project.getPackages());
chain = chain.then(packages => {
this.packageGraph = new PackageGraph(packages);
});
return chain;
}
runCommand() {
return Promise.resolve()
.then(() => this.initialize())
.then(proceed => {
if (proceed !== false) {
return this.execute();
}
// early exits set their own exitCode (if non-zero)
});
}
initialize() {
throw new ValidationError(this.name, "initialize() needs to be implemented.");
}
execute() {
throw new ValidationError(this.name, "execute() needs to be implemented.");
}
}
module.exports = Command;