-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
208 lines (183 loc) · 6.65 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/**
* @copyright Copyright 2017-2021 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
* @module procore-docs-to-openapi/cli.js
*/
import { readFile } from 'node:fs/promises';
import { format } from 'node:util';
import { Command } from 'commander';
import combineOpenapi from './combine.js';
import ProcoreFixupsTransformer from './fixups.js';
import ProcoreApiDocToOpenApiTransformer from './index.js';
import { procoreApiDocToOpenApiTransformerMockSymbol } from './lib/symbols.js';
import toJsonPointer from './lib/to-json-pointer.js';
/** 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);
}
function streamToString(readable) {
return new Promise((resolve, reject) => {
let str = '';
readable.on('data', (data) => {
// Converting Buffer to string here could break multi-byte chars.
// It's also inefficient. Require callers to .setEncoding().
if (typeof data !== 'string') {
readable.destroy(new TypeError(
`expected string, got ${typeof data} from stream`,
));
}
str += data;
});
readable.once('error', reject);
readable.once('end', () => resolve(str));
});
}
async function streamToJson(stream) {
try {
const json = await streamToString(stream);
return JSON.parse(json);
} catch (err) {
const filename = stream.path || '-';
err.message += ` in ${filename}`;
throw err;
}
}
/** 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 procoreDocsToOpenapiMain(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: .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;
});
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 filenames = command.args;
if (filenames.length === 0) {
if (options.stdin.isTTY) {
options.stderr.write(
'Warning: No filename given. Reading Procore API JSON from stdin.\n',
);
}
filenames.push('-');
}
const verbosity = (argOpts.verbose || 0) - (argOpts.quiet || 0);
try {
const docs = await Promise.all(filenames.map((filename) => {
if (filename === '-') {
options.stdin.setEncoding('utf8');
return streamToJson(options.stdin);
}
return readJson(filename);
}));
const ProcoreApiDocToOpenApiTransformerOrMock =
options[procoreApiDocToOpenApiTransformerMockSymbol]
|| ProcoreApiDocToOpenApiTransformer;
const transformer = new ProcoreApiDocToOpenApiTransformerOrMock();
const openapiDocs = docs.map((doc, i) => {
if (verbosity >= 0) {
transformer.warn = function(...values) {
options.stderr.write(
`${filenames[i]}:${toJsonPointer(this.transformPath)}: ${
format(...values)}\n`,
);
};
}
return transformer.transformApiDoc(doc);
});
const combined = openapiDocs.length < 2 ? openapiDocs[0]
: combineOpenapi(openapiDocs);
const fixed = new ProcoreFixupsTransformer().transformOpenApi(combined);
options.stdout.write(JSON.stringify(fixed, undefined, 2));
return 0;
} catch (err) {
options.stderr.write(`${err}\n`);
return 1;
}
}