-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
184 lines (165 loc) · 5.75 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
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
/**
* @copyright Copyright 2017-2021 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
* @module "hub-ci-status/cli.js"
*/
import {
Command,
InvalidArgumentError,
Option,
} from 'commander';
import hubCiStatus from './index.js';
import getPackageJson from './lib/get-package-json.js';
// Same --color options as hub(1)
const colorOptions = ['always', 'never', 'auto'];
function coerceWait(arg) {
if (arg === true) {
// Treat --wait without argument as infinite wait.
return Infinity;
}
// Note: Don't treat '' as 0 (no wait), since it's more likely user error
const val = Number(arg);
if (arg === '' || Number.isNaN(val)) {
throw new InvalidArgumentError(`Invalid number "${arg}"`);
}
if (val < 0) {
throw new InvalidArgumentError('--wait must not be negative');
}
return val;
}
/** 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;
}
/** Options for command entry points.
*
* @typedef {{
* env: Object<string,string>|undefined,
* 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 hubCiStatusMain(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('[ref]')
.allowExcessArguments(false)
.description('Command description.')
.addOption(
new Option('--color [when]', 'Colorize verbose output')
.choices(colorOptions),
)
.option('-q, --quiet', 'print less output', countOption)
.option('-v, --verbose', 'print more output', countOption)
// TODO: .version(packageJson.version) from JSON import
// Requires Node.js ^16.14 || >=17.5:
// https://github.com/nodejs/node/pull/41736
// https://nodejs.org/api/esm.html#json-modules
// Won't be supported by ESLint until proposal reaches Stage 4:
// https://github.com/eslint/eslint/issues/15623
// https://github.com/tc39/proposal-import-attributes
.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;
})
.option(
'-w, --wait [seconds]',
'retry while combined status is pending (with optional max time in sec)',
coerceWait,
)
.option(
'-W, --wait-all',
'retry while any status is pending (implies --wait)',
);
try {
command.parse(args);
} catch (errParse) {
if (errVersion) {
const packageJson = await getPackageJson();
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 maxTotalMs =
typeof argOpts.wait === 'number' ? argOpts.wait * 1000
: argOpts.wait || argOpts.waitAll ? Infinity
: undefined;
const useColor =
argOpts.color === 'never' ? false
: argOpts.color === 'always' || argOpts.color === true ? true
: undefined;
const ref = command.args[0];
const verbosity = (argOpts.verbose || 0) - (argOpts.quiet || 0);
const gcs = options.hubCiStatus || hubCiStatus;
try {
return await gcs(ref, {
octokitOptions: {
auth: options.env ? options.env.GITHUB_TOKEN : undefined,
},
stderr: options.stderr,
stdout: options.stdout,
useColor,
verbosity,
wait: maxTotalMs === undefined ? undefined : { maxTotalMs },
waitAll: !!argOpts.waitAll,
});
} catch (err) {
options.stderr.write(`${verbosity > 1 ? err.stack : err}\n`);
return 1;
}
}