-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
134 lines (119 loc) · 4.36 KB
/
cli.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
/**
* @copyright Copyright 2017-2021 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
* @module modulename/cli.js
*/
import { Command } from 'commander';
// TODO [engine:node@>=14]: import { readFile } from 'fs/promises'
import { promises as fsPromises } from 'fs';
import modulename from './index.js';
import { modulenameMockSymbol } from './lib/symbols.js';
const { readFile } = fsPromises;
/** Option parser to count the number of occurrences of the option.
*
* @private
* @param {boolean|string} optarg Argument passed to option (ignored).
* @param {number=} previous Previous value of option (counter).
* @returns {number} previous + 1.
*/
function countOption(optarg, previous) {
return (previous || 0) + 1;
}
async function readJson(pathOrUrl, options) {
const content = await readFile(pathOrUrl, { encoding: 'utf8', ...options });
return JSON.parse(content);
}
/** Options for command entry points.
*
* @typedef {{
* env: !object<string,string>,
* stdin: !module:stream.Readable,
* stdout: !module:stream.Writable,
* stderr: !module:stream.Writable
* }} CommandOptions
* @property {!object<string,string>} env Environment variables.
* @property {!module:stream.Readable} stdin Stream from which input is read.
* @property {!module:stream.Writable} stdout Stream to which output is
* written.
* @property {!module:stream.Writable} stderr Stream to which errors and
* non-output status messages are written.
*/
// const CommandOptions;
/** Entry point for this command.
*
* @param {!Array<string>} args Command-line arguments.
* @param {!CommandOptions} options Options.
* @returns {!Promise<number>} Promise for exit code. Only rejected for
* arguments with invalid type (or args.length < 2).
*/
export default async function modulenameMain(args, options) {
if (!Array.isArray(args) || args.length < 2) {
throw new TypeError('args must be an Array with at least 2 items');
}
if (!options || typeof options !== 'object') {
throw new TypeError('options must be an object');
}
if (!options.stdin || typeof options.stdin.on !== 'function') {
throw new TypeError('options.stdin must be a stream.Readable');
}
if (!options.stdout || typeof options.stdout.write !== 'function') {
throw new TypeError('options.stdout must be a stream.Writable');
}
if (!options.stderr || typeof options.stderr.write !== 'function') {
throw new TypeError('options.stderr must be a stream.Writable');
}
let errVersion;
const command = new Command()
.exitOverride()
.configureOutput({
writeOut: (str) => options.stdout.write(str),
writeErr: (str) => options.stderr.write(str),
getOutHelpWidth: () => options.stdout.columns,
getErrHelpWidth: () => options.stderr.columns,
})
.arguments('[file...]')
.allowExcessArguments(false)
.description('Command description.')
.option('-q, --quiet', 'print less output', countOption)
.option('-v, --verbose', 'print more output', countOption)
// TODO: Replace with .version(packageJson.version) loaded as JSON module
// https://github.com/nodejs/node/issues/37141
.option('-V, --version', 'output the version number')
// throw exception to stop option parsing early, as commander does
// (e.g. to avoid failing due to missing required arguments)
.on('option:version', () => {
errVersion = new Error('version');
throw errVersion;
});
try {
command.parse(args);
} catch (errParse) {
if (errVersion) {
const packageJson =
await readJson(new URL('package.json', import.meta.url));
options.stdout.write(`${packageJson.version}\n`);
return 0;
}
// If a non-Commander error was thrown, treat it as unhandled.
// It probably represents a bug and has not been written to stdout/stderr.
// throw commander.{CommanderError,InvalidArgumentError} to avoid.
if (typeof errParse.code !== 'string'
|| !errParse.code.startsWith('commander.')) {
throw errParse;
}
return errParse.exitCode !== undefined ? errParse.exitCode : 1;
}
const argOpts = command.opts();
const cmdOpts = {
files: command.args,
verbosity: (argOpts.verbose || 0) - (argOpts.quiet || 0),
};
const modulenameOrMock = options[modulenameMockSymbol] || modulename;
try {
await modulenameOrMock(cmdOpts);
return 0;
} catch (err) {
options.stderr.write(`${err}\n`);
return 1;
}
}