-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
command.ts
362 lines (302 loc) · 10.2 KB
/
command.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
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
import cloneDeep from 'clone-deep';
import dedent from 'dedent';
import execa from 'execa';
import log, { Logger } from 'npmlog';
import os from 'os';
import { cleanStack } from './utils/clean-stack';
import { logExecCommand } from './child-process';
import { logPackageError } from './utils/log-package-error';
import { warnIfHanging } from './utils/warn-if-hanging';
import { writeLogFile } from './utils/write-log-file';
import { Project } from './project/project';
import { ValidationError } from './validation-error';
import {
ChangedCommandOption,
CommandType,
DiffCommandOption,
ExecCommandOption,
ExecOpts,
InitCommandOption,
ListCommandOption,
ProjectConfig,
PublishCommandOption,
VersionCommandOption,
} from './models';
import { PackageGraph } from './package-graph/package-graph';
// maxBuffer value for running exec
const DEFAULT_CONCURRENCY = os.cpus().length;
type AvailableCommandOption =
| ChangedCommandOption
| DiffCommandOption
| ExecCommandOption
| InitCommandOption
| ListCommandOption
| PublishCommandOption
| VersionCommandOption;
export class Command<T extends AvailableCommandOption> {
argv: any;
concurrency!: number;
envDefaults: any;
sort: any;
toposort?: boolean;
execOpts!: ExecOpts;
commandName: CommandType = '';
composed;
logger!: Logger;
options!: T & ExecOpts & ProjectConfig;
project!: Project;
packageGraph!: PackageGraph;
runner?: Promise<any>;
constructor(_argv: AvailableCommandOption) {
log.pause();
log.heading = 'lerna-lite';
const argv = cloneDeep(_argv) as ProjectConfig;
log.silly('argv', argv.toString());
// 'FooCommand' => 'foo'
this.commandName = this.constructor.name.replace(/Command$/, '').toLowerCase() as CommandType;
// composed commands are called from other commands, like publish -> version
this.composed = typeof argv.composed === 'string' && argv.composed !== this.commandName;
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<any> = Promise.resolve();
chain = chain.then(() => (this.project = new Project(argv.cwd)));
chain = chain.then(() => this.configureEnvironment());
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, this.options.stream);
} 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);
if (err.name === 'ValidationError') {
log.error(err.code, (err.body && err.body.error) || err.message);
}
}
);
});
// 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
}
// 'hide' irrelevant argv keys from options
for (const key of ['cwd', '$0']) {
Object.defineProperty(argv, key, { enumerable: false });
}
Object.defineProperty(this, 'argv', {
value: Object.freeze(argv),
});
Object.defineProperty(this, 'runner', {
value: runner,
});
}
// proxy 'Promise' methods to 'private' instance
then(onResolved: typeof Promise.resolve, onRejected: typeof Promise.reject) {
return this.runner?.then(onResolved, onRejected);
}
/* istanbul ignore next */
catch(onRejected: typeof Promise.reject) {
return this.runner?.catch(onRejected);
}
get requiresGit() {
return true;
}
// Override this to inherit config from another command.
// For example `changed` inherits config from `publish`.
get otherCommandConfigs(): string[] {
return [];
}
configureEnvironment() {
// eslint-disable-next-line global-require
const ci = require('is-ci');
let loglevel;
let progress;
/* istanbul ignore next */
if (ci || !process.stderr.isTTY || process.env.TERM === 'dumb') {
log.disableColor();
progress = false;
} else if (!process.stdout.isTTY) {
// stdout is being piped, don't log non-errors or progress bars
progress = false;
loglevel = 'error';
} else if (process.stderr.isTTY) {
log.enableColor();
log.enableUnicode();
}
Object.defineProperty(this, 'envDefaults', {
value: {
ci,
progress,
loglevel,
},
});
}
configureOptions() {
// Command config object normalized to 'command' namespace
const commandConfig = this.project.config.command || {};
// The current command always overrides otherCommandConfigs
const overrides = [this.commandName, ...this.otherCommandConfigs].map((key) => (commandConfig as any)[key]);
this.options = defaultOptions(
// 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,
// Environmental defaults prepared in previous step
this.envDefaults
);
}
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
Object.defineProperty(this, 'logger', {
value: log.newGroup(this.commandName),
});
// emit all buffered logs at configured level and higher
log.resume();
}
enableProgressBar() {
/* istanbul ignore next */
if (this.options.progress !== false) {
log.enableProgress();
}
}
gitInitialized() {
const opts: execa.SyncOptions<string> = {
cwd: this.project.rootPath ?? '',
// don't throw, just want boolean
reject: false,
// only return code, no stdio needed
stdio: 'ignore',
};
const gitCommand = 'git';
const gitArgs = ['rev-parse'];
if ((this.options as unknown as PublishCommandOption).gitDryRun) {
logExecCommand(gitCommand, gitArgs);
return true;
}
return execa.sync(gitCommand, gitArgs, opts).exitCode === 0;
}
runValidations() {
if (this.commandName === 'info') {
return;
}
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',
'No `package.json` file found, make sure it exist in the root of your project.'
);
}
if (!this.project.version) {
throw new ValidationError(
'ENOLERNA',
'No `lerna.json` file exist, please create one in the root of your project.'
);
}
if ((this.options as InitCommandOption).independent && !this.project.isIndependent()) {
throw new ValidationError(
'EVERSIONMODE',
dedent`
You ran lerna-lite 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(): Promise<any> | void {
if (!this.composed && this.project.isIndependent()) {
// composed commands have already logged the independent status
log.info('versioning', 'independent');
}
if (!this.composed && this.options.ci) {
log.info('ci', 'enabled');
}
let chain: Promise<any> = Promise.resolve();
if (this.commandName !== 'info') {
chain = chain.then(() => this.project.getPackages());
chain = chain.then((packages) => {
this.packageGraph = new PackageGraph(packages || []);
});
}
return chain;
}
async 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(): any | Promise<any> {
throw new ValidationError(this.commandName, 'initialize() needs to be implemented.');
}
execute(): any | Promise<any> {
throw new ValidationError(this.commandName, 'execute() needs to be implemented.');
}
}
// _.defaults(), but simplified:
// * All inputs are plain objects
// * Only own keys, not inherited
function defaultOptions(...sources: any) {
const options: any = {};
for (const source of sources) {
if (source !== null && source !== undefined) {
for (const key of Object.keys(source)) {
if (options[key] === undefined) {
options[key] = source[key];
}
}
}
}
return options;
}