@intellectual-frontiers/terminal 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/args.d.ts +240 -0
- package/dist/args.js +328 -0
- package/dist/commands.d.ts +103 -0
- package/dist/commands.js +127 -0
- package/dist/mod.d.ts +19 -0
- package/dist/mod.js +20 -0
- package/dist/palette.d.ts +44 -0
- package/dist/palette.js +84 -0
- package/dist/vt.d.ts +78 -0
- package/dist/vt.js +486 -0
- package/dist/width.d.ts +63 -0
- package/dist/width.js +170 -0
- package/package.json +63 -4
- package/src/args.ts +547 -0
- package/src/commands.ts +182 -0
- package/src/mod.ts +20 -0
- package/src/palette.ts +104 -0
- package/src/vt.ts +497 -0
- package/src/width.ts +181 -0
package/src/args.ts
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-001
|
|
2
|
+
/**
|
|
3
|
+
* A typed command-line parser (commons 0005-typescript-runtime FR-047): a command's options are declared once as data (`flag`, `value`,
|
|
4
|
+
* `many`), the type of what `parseArgs` gives is inferred from that declaration, and a command line that does not fit is a `UsageError`,
|
|
5
|
+
* a union told apart by `kind` that `formatUsageError` says in one sentence; `helpText` writes the help from the same declaration. It
|
|
6
|
+
* unifies the parsers of two harnesses: erga's `@erga/agent` `args.ts` (declared options, an undeclared option refused with a "did you mean", help that
|
|
7
|
+
* wins over everything and runs nothing: erga 247-ergactl FR-006 and FR-007) and Stolos's `parseArgs` (short letters, required options, defaults, repeatable options). It is pure: the
|
|
8
|
+
* caller passes the words, `proc.args` from `runtime/proc.ts`.
|
|
9
|
+
*
|
|
10
|
+
* The grammar: `--name VALUE` and `--name=VALUE`; `-x VALUE`; bundled short flags `-abc`, whose last letter may take the next word as its
|
|
11
|
+
* value; `--no-name` for a flag declared `negatable`; `--` ends the options, and the words after it are kept apart as `rest`; `-` and a
|
|
12
|
+
* word such as `-5` are arguments, since no option is a digit. A short option's value is never attached (`-ofile`, `-o=file`), which other
|
|
13
|
+
* parsers read differently. A value-taking option takes the next word whatever it is, as getopt does. Every option is given at most once
|
|
14
|
+
* (a `many` option as often as wanted): a second value would otherwise silently replace the first. `--help`, or a short word with the
|
|
15
|
+
* letter `h`, anywhere before `--` asks for help, which wins over every other word and every error, so `-h` and the name `help` are
|
|
16
|
+
* reserved.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { flag, integerText, many, parseArgs, value } from "./args.ts";
|
|
21
|
+
* const spec = {
|
|
22
|
+
* verbose: flag({ short: "v", help: "Say more." }),
|
|
23
|
+
* out: value({ short: "o", help: "Where to write.", valueName: "FILE" }),
|
|
24
|
+
* tag: many({ help: "A tag." }),
|
|
25
|
+
* jobs: value({ help: "How many at once.", parse: integerText, default: 4 }),
|
|
26
|
+
* };
|
|
27
|
+
* parseArgs(["-v", "--tag", "a", "--tag=b", "--jobs", "8", "--", "x"], spec);
|
|
28
|
+
* // { kind: "ok", value: { kind: "args", options: { verbose: true, out: undefined, tag: ["a", "b"], jobs: 8 }, positionals: [], rest: ["x"] } }
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @module
|
|
32
|
+
*/
|
|
33
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
34
|
+
import type { DecodeError } from "@intellectual-frontiers/core";
|
|
35
|
+
|
|
36
|
+
/** A short option's letter: any ASCII letter but `h`, which is help's. */
|
|
37
|
+
export type ShortName =
|
|
38
|
+
| "a"
|
|
39
|
+
| "b"
|
|
40
|
+
| "c"
|
|
41
|
+
| "d"
|
|
42
|
+
| "e"
|
|
43
|
+
| "f"
|
|
44
|
+
| "g"
|
|
45
|
+
| "i"
|
|
46
|
+
| "j"
|
|
47
|
+
| "k"
|
|
48
|
+
| "l"
|
|
49
|
+
| "m"
|
|
50
|
+
| "n"
|
|
51
|
+
| "o"
|
|
52
|
+
| "p"
|
|
53
|
+
| "q"
|
|
54
|
+
| "r"
|
|
55
|
+
| "s"
|
|
56
|
+
| "t"
|
|
57
|
+
| "u"
|
|
58
|
+
| "v"
|
|
59
|
+
| "w"
|
|
60
|
+
| "x"
|
|
61
|
+
| "y"
|
|
62
|
+
| "z"
|
|
63
|
+
| "A"
|
|
64
|
+
| "B"
|
|
65
|
+
| "C"
|
|
66
|
+
| "D"
|
|
67
|
+
| "E"
|
|
68
|
+
| "F"
|
|
69
|
+
| "G"
|
|
70
|
+
| "H"
|
|
71
|
+
| "I"
|
|
72
|
+
| "J"
|
|
73
|
+
| "K"
|
|
74
|
+
| "L"
|
|
75
|
+
| "M"
|
|
76
|
+
| "N"
|
|
77
|
+
| "O"
|
|
78
|
+
| "P"
|
|
79
|
+
| "Q"
|
|
80
|
+
| "R"
|
|
81
|
+
| "S"
|
|
82
|
+
| "T"
|
|
83
|
+
| "U"
|
|
84
|
+
| "V"
|
|
85
|
+
| "W"
|
|
86
|
+
| "X"
|
|
87
|
+
| "Y"
|
|
88
|
+
| "Z";
|
|
89
|
+
|
|
90
|
+
/** What turns an option's text into its value: a function of the text, or any of the kernel's decoders (`./decode.ts`), which take it as `unknown`. */
|
|
91
|
+
export type Parser<T> = (text: string) => Result<T, string | DecodeError>;
|
|
92
|
+
|
|
93
|
+
/** What an option is when the command line does not give it: nothing (`undefined`), a usage error, or a default. */
|
|
94
|
+
export type Presence = "none" | "required" | "default";
|
|
95
|
+
|
|
96
|
+
/** The fallback of an option of presence `P`: the default's value is kept with it. */
|
|
97
|
+
export type Fallback<T, P extends Presence> = P extends "none"
|
|
98
|
+
? { readonly kind: "none" }
|
|
99
|
+
: P extends "required"
|
|
100
|
+
? { readonly kind: "required" }
|
|
101
|
+
: { readonly kind: "default"; readonly value: T };
|
|
102
|
+
|
|
103
|
+
/** A switch that takes no value: `true` when given, `false` with `--no-name` where it is negatable, else its fallback. */
|
|
104
|
+
export type FlagOption<P extends "none" | "default" = "none" | "default", L extends ShortName = ShortName> = {
|
|
105
|
+
readonly kind: "flag";
|
|
106
|
+
readonly short: L | undefined;
|
|
107
|
+
readonly help: string;
|
|
108
|
+
readonly negatable: boolean;
|
|
109
|
+
readonly fallback: Fallback<boolean, P>;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** An option given at most once with one value, parsed into a `T`. */
|
|
113
|
+
export type ValueOption<T, P extends Presence = Presence, L extends ShortName = ShortName> = {
|
|
114
|
+
readonly kind: "value";
|
|
115
|
+
readonly short: L | undefined;
|
|
116
|
+
readonly help: string;
|
|
117
|
+
readonly valueName: string;
|
|
118
|
+
readonly parse: Parser<T>;
|
|
119
|
+
readonly fallback: Fallback<T, P>;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** An option given any number of times, each value parsed into a `T`, kept in the order given. */
|
|
123
|
+
export type ManyOption<T, L extends ShortName = ShortName> = {
|
|
124
|
+
readonly kind: "many";
|
|
125
|
+
readonly short: L | undefined;
|
|
126
|
+
readonly help: string;
|
|
127
|
+
readonly valueName: string;
|
|
128
|
+
readonly parse: Parser<T>;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** One declared option. */
|
|
132
|
+
export type Option = FlagOption | ValueOption<unknown> | ManyOption<unknown>;
|
|
133
|
+
|
|
134
|
+
/** A command's options, by name: the key `dryRun` is the option `--dry-run`. */
|
|
135
|
+
export type Spec = { readonly [name: string]: Option };
|
|
136
|
+
|
|
137
|
+
/** The value an option gives, as its declaration says. */
|
|
138
|
+
export type OptionValue<O> = O extends { readonly kind: "flag"; readonly fallback: infer F }
|
|
139
|
+
? [F] extends [{ readonly kind: "none" }]
|
|
140
|
+
? boolean | undefined
|
|
141
|
+
: boolean
|
|
142
|
+
: O extends { readonly kind: "many"; readonly parse: Parser<infer T> }
|
|
143
|
+
? readonly T[]
|
|
144
|
+
: O extends { readonly kind: "value"; readonly parse: Parser<infer T>; readonly fallback: infer F }
|
|
145
|
+
? [F] extends [{ readonly kind: "none" }]
|
|
146
|
+
? T | undefined
|
|
147
|
+
: T
|
|
148
|
+
: never;
|
|
149
|
+
|
|
150
|
+
/** The values of a spec's options, by the same names. */
|
|
151
|
+
export type OptionValues<S extends Spec> = { readonly [K in keyof S]: OptionValue<S[K]> };
|
|
152
|
+
|
|
153
|
+
/** The short letter an option declares, if any. */
|
|
154
|
+
type ShortOf<O> = O extends { readonly short: infer L } ? Exclude<L, undefined> : never;
|
|
155
|
+
|
|
156
|
+
/** The short letters that two options of a spec declare. */
|
|
157
|
+
type RepeatedShorts<S> = { [K in keyof S]: ShortOf<S[K]> & ShortOf<S[Exclude<keyof S, K>]> }[keyof S];
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* `unknown` where a spec is well formed, else a type naming what is wrong, which the spec then does not satisfy: a short letter declared
|
|
161
|
+
* twice, a name written with a dash (names are camelCase keys), or the name `help`, which is reserved.
|
|
162
|
+
*/
|
|
163
|
+
export type SpecCheck<S> = [RepeatedShorts<S>] extends [never]
|
|
164
|
+
? [Extract<keyof S, `${string}-${string}`>] extends [never]
|
|
165
|
+
? ["help"] extends [keyof S]
|
|
166
|
+
? { readonly "help is reserved": never }
|
|
167
|
+
: unknown
|
|
168
|
+
: { readonly "option names are camelCase keys": Extract<keyof S, `${string}-${string}`> }
|
|
169
|
+
: { readonly "a short letter is declared twice": RepeatedShorts<S> };
|
|
170
|
+
|
|
171
|
+
/** A word, or words, that a command takes after its options: exactly one, at most one, or any number. */
|
|
172
|
+
export type Operand = { readonly name: string; readonly help: string; readonly arity: "one" | "optional" | "many" };
|
|
173
|
+
|
|
174
|
+
/** A command line that fits its spec: the options' values, the arguments, and the words after `--`. */
|
|
175
|
+
export type Args<S extends Spec> = {
|
|
176
|
+
readonly kind: "args";
|
|
177
|
+
readonly options: OptionValues<S>;
|
|
178
|
+
readonly positionals: readonly string[];
|
|
179
|
+
readonly rest: readonly string[];
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** What a command line asks: help, which runs nothing else (erga 247-ergactl FR-006), or the command with its arguments. */
|
|
183
|
+
export type Parsed<S extends Spec> = { readonly kind: "help" } | Args<S>;
|
|
184
|
+
|
|
185
|
+
/** Why a command line does not fit its spec. `option` is the option as it was written, or its long name where it was given twice or not at all. */
|
|
186
|
+
export type UsageError =
|
|
187
|
+
| { readonly kind: "unknown-option"; readonly option: string; readonly suggestion: string | undefined }
|
|
188
|
+
| { readonly kind: "missing-value"; readonly option: string }
|
|
189
|
+
| { readonly kind: "unexpected-value"; readonly option: string; readonly value: string }
|
|
190
|
+
| { readonly kind: "attached-value"; readonly option: string; readonly word: string }
|
|
191
|
+
| { readonly kind: "invalid-value"; readonly option: string; readonly value: string; readonly reason: string }
|
|
192
|
+
| { readonly kind: "repeated-option"; readonly option: string }
|
|
193
|
+
| { readonly kind: "missing-option"; readonly option: string }
|
|
194
|
+
| { readonly kind: "missing-argument"; readonly argument: string }
|
|
195
|
+
| { readonly kind: "unexpected-argument"; readonly argument: string; readonly takes: readonly string[] };
|
|
196
|
+
|
|
197
|
+
/** The fields every option declares. */
|
|
198
|
+
type Common<L extends ShortName> = { readonly short?: L; readonly help: string };
|
|
199
|
+
|
|
200
|
+
/** The fields an option with a value declares: the name of its value in the help, `VALUE` by default. */
|
|
201
|
+
type Valued<L extends ShortName> = Common<L> & { readonly valueName?: string };
|
|
202
|
+
|
|
203
|
+
/** A flag: `false` when not given; with `negatable`, `--no-name` gives `false` and an absent flag gives `undefined`, or the `default`. */
|
|
204
|
+
export function flag<L extends ShortName = never>(
|
|
205
|
+
o: Common<L> & { readonly negatable: true; readonly default: boolean },
|
|
206
|
+
): FlagOption<"default", L>;
|
|
207
|
+
/** A negatable flag with no default. */
|
|
208
|
+
export function flag<L extends ShortName = never>(o: Common<L> & { readonly negatable: true }): FlagOption<"none", L>;
|
|
209
|
+
/** A flag that cannot be negated. */
|
|
210
|
+
export function flag<L extends ShortName = never>(o: Common<L>): FlagOption<"default", L>;
|
|
211
|
+
/** The implementation of `flag`. */
|
|
212
|
+
export function flag(o: Common<ShortName> & { readonly negatable?: true; readonly default?: boolean }): FlagOption {
|
|
213
|
+
const negatable = o.negatable === true;
|
|
214
|
+
return {
|
|
215
|
+
kind: "flag",
|
|
216
|
+
short: o.short,
|
|
217
|
+
help: o.help,
|
|
218
|
+
negatable,
|
|
219
|
+
fallback: negatable && o.default === undefined ? { kind: "none" } : { kind: "default", value: o.default ?? false },
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** An option with one value, parsed by `parse`, that must be given. */
|
|
224
|
+
export function value<T, L extends ShortName = never>(
|
|
225
|
+
o: Valued<L> & { readonly parse: Parser<T>; readonly required: true },
|
|
226
|
+
): ValueOption<T, "required", L>;
|
|
227
|
+
/** An option with one value, parsed by `parse`, and a default. */
|
|
228
|
+
export function value<T, L extends ShortName = never>(
|
|
229
|
+
o: Valued<L> & { readonly parse: Parser<T>; readonly default: NoInfer<T> },
|
|
230
|
+
): ValueOption<T, "default", L>;
|
|
231
|
+
/** An option with one value, parsed by `parse`, `undefined` when not given. */
|
|
232
|
+
export function value<T, L extends ShortName = never>(o: Valued<L> & { readonly parse: Parser<T> }): ValueOption<T, "none", L>;
|
|
233
|
+
/** An option with one text value that must be given. */
|
|
234
|
+
export function value<L extends ShortName = never>(o: Valued<L> & { readonly required: true }): ValueOption<string, "required", L>;
|
|
235
|
+
/** An option with one text value and a default. */
|
|
236
|
+
export function value<L extends ShortName = never>(o: Valued<L> & { readonly default: string }): ValueOption<string, "default", L>;
|
|
237
|
+
/** An option with one text value, `undefined` when not given. */
|
|
238
|
+
export function value<L extends ShortName = never>(o: Valued<L>): ValueOption<string, "none", L>;
|
|
239
|
+
/** The implementation of `value`. */
|
|
240
|
+
export function value(
|
|
241
|
+
o: Valued<ShortName> & { readonly parse?: Parser<unknown>; readonly required?: true; readonly default?: unknown },
|
|
242
|
+
): ValueOption<unknown> {
|
|
243
|
+
return {
|
|
244
|
+
kind: "value",
|
|
245
|
+
short: o.short,
|
|
246
|
+
help: o.help,
|
|
247
|
+
valueName: o.valueName ?? "VALUE",
|
|
248
|
+
parse: o.parse ?? text,
|
|
249
|
+
fallback: o.required === true ? { kind: "required" } : "default" in o ? { kind: "default", value: o.default } : { kind: "none" },
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** An option given any number of times, each value parsed by `parse`. */
|
|
254
|
+
export function many<T, L extends ShortName = never>(o: Valued<L> & { readonly parse: Parser<T> }): ManyOption<T, L>;
|
|
255
|
+
/** An option given any number of times, each value its text. */
|
|
256
|
+
export function many<L extends ShortName = never>(o: Valued<L>): ManyOption<string, L>;
|
|
257
|
+
/** The implementation of `many`. */
|
|
258
|
+
export function many(o: Valued<ShortName> & { readonly parse?: Parser<unknown> }): ManyOption<unknown> {
|
|
259
|
+
return { kind: "many", short: o.short, help: o.help, valueName: o.valueName ?? "VALUE", parse: o.parse ?? text };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The parser of a text value: the text itself. */
|
|
263
|
+
const text: Parser<string> = (t) => ok(t);
|
|
264
|
+
|
|
265
|
+
/** A parser of an integer written in decimal, with an optional `-`, within the safe integers. */
|
|
266
|
+
export function integerText(t: string): Result<number, string> {
|
|
267
|
+
return /^-?(0|[1-9][0-9]*)$/.test(t) && Number.isSafeInteger(Number(t)) ? ok(Number(t)) : err("expected an integer");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The long option of a spec's key: `dryRun` is `--dry-run`. */
|
|
271
|
+
export function longName(key: string): string {
|
|
272
|
+
return `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The number of insertions, deletions and substitutions that turn `a` into `b` (Levenshtein). */
|
|
276
|
+
export function editDistance(a: string, b: string): number {
|
|
277
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
278
|
+
for (let i = 1; i <= a.length; i++) {
|
|
279
|
+
const row = [i];
|
|
280
|
+
for (let j = 1; j <= b.length; j++) {
|
|
281
|
+
row.push(Math.min((prev[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)));
|
|
282
|
+
}
|
|
283
|
+
prev = row;
|
|
284
|
+
}
|
|
285
|
+
return prev[b.length] ?? 0;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The candidate nearest `word` by edit distance, the first of equals, if it is within two edits or half the word's length; else nothing. */
|
|
289
|
+
export function suggest(word: string, candidates: readonly string[]): string | undefined {
|
|
290
|
+
let best: string | undefined;
|
|
291
|
+
let bestDistance = Number.POSITIVE_INFINITY;
|
|
292
|
+
for (const c of candidates) {
|
|
293
|
+
const d = editDistance(word, c);
|
|
294
|
+
if (d < bestDistance) {
|
|
295
|
+
best = c;
|
|
296
|
+
bestDistance = d;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return bestDistance <= Math.max(2, Math.floor(word.length / 2)) ? best : undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Whether a word asks for help: `--help`, or a short word with the letter `h` (`-h`, `-vh`). */
|
|
303
|
+
function asksHelp(word: string): boolean {
|
|
304
|
+
return word === "--help" || /^-[A-Za-z]*h[A-Za-z]*$/.test(word);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** One declared option with its key and long name. */
|
|
308
|
+
type Entry = { readonly key: string; readonly long: string; readonly option: Option };
|
|
309
|
+
|
|
310
|
+
/** The words an operand is shown as: `FILE`, `[FILE]`, `[FILE...]`. */
|
|
311
|
+
function operandWord(o: Operand): string {
|
|
312
|
+
switch (o.arity) {
|
|
313
|
+
case "one":
|
|
314
|
+
return o.name;
|
|
315
|
+
case "optional":
|
|
316
|
+
return `[${o.name}]`;
|
|
317
|
+
case "many":
|
|
318
|
+
return `[${o.name}...]`;
|
|
319
|
+
default:
|
|
320
|
+
return absurd(o.arity);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Parses `argv` against `spec`, and the arguments against `operands` (none by default): help where it is asked for, else every option's
|
|
326
|
+
* value with the arguments and the words after `--`, or the first thing that does not fit.
|
|
327
|
+
*/
|
|
328
|
+
export function parseArgs<S extends Spec>(
|
|
329
|
+
argv: readonly string[],
|
|
330
|
+
spec: S & SpecCheck<S>,
|
|
331
|
+
operands: readonly Operand[] = [],
|
|
332
|
+
): Result<Parsed<S>, UsageError> {
|
|
333
|
+
const end = argv.indexOf("--");
|
|
334
|
+
if ((end < 0 ? argv : argv.slice(0, end)).some(asksHelp)) return ok({ kind: "help" });
|
|
335
|
+
const entries: readonly Entry[] = Object.keys(spec).flatMap((key) => {
|
|
336
|
+
const option = spec[key];
|
|
337
|
+
return option === undefined ? [] : [{ key, long: longName(key), option }];
|
|
338
|
+
});
|
|
339
|
+
const longs = [
|
|
340
|
+
...entries.flatMap((e) => (e.option.kind === "flag" && e.option.negatable ? [e.long, `--no-${e.long.slice(2)}`] : [e.long])),
|
|
341
|
+
"--help",
|
|
342
|
+
];
|
|
343
|
+
const given = new Map<string, unknown>();
|
|
344
|
+
const listed = new Map<string, unknown[]>();
|
|
345
|
+
const positionals: string[] = [];
|
|
346
|
+
let rest: readonly string[] = [];
|
|
347
|
+
let i = 0;
|
|
348
|
+
|
|
349
|
+
/** Records the value of `e`, written `written`, whose text is `inline` or else the next word. */
|
|
350
|
+
const take = (e: Entry, written: string, inline: string | undefined, negated: boolean): UsageError | undefined => {
|
|
351
|
+
const o = e.option;
|
|
352
|
+
if (o.kind !== "many" && given.has(e.key)) return { kind: "repeated-option", option: e.long };
|
|
353
|
+
if (o.kind === "flag") {
|
|
354
|
+
if (inline !== undefined) return { kind: "unexpected-value", option: written, value: inline };
|
|
355
|
+
given.set(e.key, !negated);
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
const t = inline ?? argv[++i];
|
|
359
|
+
if (t === undefined) return { kind: "missing-value", option: written };
|
|
360
|
+
const parsed = o.parse(t);
|
|
361
|
+
if (parsed.kind === "err") {
|
|
362
|
+
const reason = typeof parsed.error === "string" ? parsed.error : `expected ${parsed.error.expected}, found ${parsed.error.found}`;
|
|
363
|
+
return { kind: "invalid-value", option: written, value: t, reason };
|
|
364
|
+
}
|
|
365
|
+
if (o.kind === "value") given.set(e.key, parsed.value);
|
|
366
|
+
else listed.set(e.key, [...(listed.get(e.key) ?? []), parsed.value]);
|
|
367
|
+
return undefined;
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
for (; i < argv.length; i++) {
|
|
371
|
+
const word = argv[i] ?? "";
|
|
372
|
+
if (word === "--") {
|
|
373
|
+
rest = argv.slice(i + 1);
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
if (word.startsWith("--")) {
|
|
377
|
+
const eq = word.indexOf("=");
|
|
378
|
+
const name = eq < 0 ? word : word.slice(0, eq);
|
|
379
|
+
const inline = eq < 0 ? undefined : word.slice(eq + 1);
|
|
380
|
+
if (name === "--help") return err({ kind: "unexpected-value", option: name, value: inline ?? "" });
|
|
381
|
+
const direct = entries.find((e) => e.long === name);
|
|
382
|
+
const positive = name.startsWith("--no-") ? entries.find((e) => e.long === `--${name.slice(5)}`) : undefined;
|
|
383
|
+
const negated = direct === undefined && positive !== undefined && positive.option.kind === "flag" && positive.option.negatable;
|
|
384
|
+
const e = direct ?? (negated ? positive : undefined);
|
|
385
|
+
if (e === undefined) return err({ kind: "unknown-option", option: name, suggestion: suggest(name, longs) });
|
|
386
|
+
const problem = take(e, name, inline, negated);
|
|
387
|
+
if (problem !== undefined) return err(problem);
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
if (word.length < 2 || !word.startsWith("-") || /^-[0-9]/.test(word)) {
|
|
391
|
+
positionals.push(word);
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
for (let j = 1; j < word.length; j++) {
|
|
395
|
+
const letter = word.charAt(j);
|
|
396
|
+
const written = `-${letter}`;
|
|
397
|
+
const e = entries.find((x) => x.option.short === letter);
|
|
398
|
+
if (e === undefined) return err({ kind: "unknown-option", option: written, suggestion: suggest(`-${word}`, longs) });
|
|
399
|
+
const after = word.slice(j + 1);
|
|
400
|
+
if (e.option.kind === "flag") {
|
|
401
|
+
if (after.startsWith("=")) return err({ kind: "unexpected-value", option: written, value: after.slice(1) });
|
|
402
|
+
} else if (after !== "") {
|
|
403
|
+
return err({ kind: "attached-value", option: written, word });
|
|
404
|
+
}
|
|
405
|
+
const problem = take(e, written, undefined, false);
|
|
406
|
+
if (problem !== undefined) return err(problem);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const values: [string, unknown][] = [];
|
|
411
|
+
for (const e of entries) {
|
|
412
|
+
const o = e.option;
|
|
413
|
+
switch (o.kind) {
|
|
414
|
+
case "many":
|
|
415
|
+
values.push([e.key, listed.get(e.key) ?? []]);
|
|
416
|
+
break;
|
|
417
|
+
case "flag":
|
|
418
|
+
case "value": {
|
|
419
|
+
if (given.has(e.key)) {
|
|
420
|
+
values.push([e.key, given.get(e.key)]);
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
const f = o.fallback;
|
|
424
|
+
switch (f.kind) {
|
|
425
|
+
case "none":
|
|
426
|
+
values.push([e.key, undefined]);
|
|
427
|
+
break;
|
|
428
|
+
case "default":
|
|
429
|
+
values.push([e.key, f.value]);
|
|
430
|
+
break;
|
|
431
|
+
case "required":
|
|
432
|
+
return err({ kind: "missing-option", option: e.long });
|
|
433
|
+
default:
|
|
434
|
+
return absurd(f);
|
|
435
|
+
}
|
|
436
|
+
break;
|
|
437
|
+
}
|
|
438
|
+
default:
|
|
439
|
+
return absurd(o);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const least = operands.filter((o) => o.arity === "one");
|
|
444
|
+
const most = operands.some((o) => o.arity === "many") ? Number.POSITIVE_INFINITY : operands.filter((o) => o.arity !== "many").length;
|
|
445
|
+
const missing = least[positionals.length];
|
|
446
|
+
if (missing !== undefined) return err({ kind: "missing-argument", argument: missing.name });
|
|
447
|
+
const extra = positionals[most];
|
|
448
|
+
if (extra !== undefined) return err({ kind: "unexpected-argument", argument: extra, takes: operands.map(operandWord) });
|
|
449
|
+
|
|
450
|
+
// The one assertion: each value above was computed from its own key's declaration, as `OptionValue` describes, which the compiler cannot follow through `Object.fromEntries`.
|
|
451
|
+
const options = Object.fromEntries(values) as OptionValues<S>;
|
|
452
|
+
return ok({ kind: "args", options, positionals, rest });
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** A usage error as one sentence; `command` names the command (`ergactl toolchain list`), "this command" by default. */
|
|
456
|
+
export function formatUsageError(e: UsageError, command = "this command"): string {
|
|
457
|
+
switch (e.kind) {
|
|
458
|
+
case "unknown-option":
|
|
459
|
+
return `${e.option} is not an option of ${command}${e.suggestion === undefined ? "" : `; did you mean ${e.suggestion}?`}`;
|
|
460
|
+
case "missing-value":
|
|
461
|
+
return `${e.option} needs a value`;
|
|
462
|
+
case "unexpected-value":
|
|
463
|
+
return `${e.option} takes no value, but was given ${JSON.stringify(e.value)}`;
|
|
464
|
+
case "attached-value":
|
|
465
|
+
return `${e.option} takes its value as the next word, not attached as in ${e.word}`;
|
|
466
|
+
case "invalid-value":
|
|
467
|
+
return `${JSON.stringify(e.value)} is not a valid value of ${e.option}: ${e.reason}`;
|
|
468
|
+
case "repeated-option":
|
|
469
|
+
return `${e.option} is given more than once`;
|
|
470
|
+
case "missing-option":
|
|
471
|
+
return `${e.option} is required`;
|
|
472
|
+
case "missing-argument":
|
|
473
|
+
return `${command} needs ${e.argument}`;
|
|
474
|
+
case "unexpected-argument":
|
|
475
|
+
return `${command} does not take ${e.argument}: ${e.takes.length === 0 ? "it takes no arguments" : `it takes ${e.takes.join(" ")}`}`;
|
|
476
|
+
default:
|
|
477
|
+
return absurd(e);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** A default as the help shows it: text and numbers as they are, anything else as JSON. */
|
|
482
|
+
function shown(v: unknown): string {
|
|
483
|
+
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : JSON.stringify(v);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** The left column of an option's line in the help, and what follows its description. */
|
|
487
|
+
function optionLine(e: Entry): { readonly left: string; readonly note: string } {
|
|
488
|
+
const o = e.option;
|
|
489
|
+
const short = o.short === undefined ? " " : `-${o.short}, `;
|
|
490
|
+
switch (o.kind) {
|
|
491
|
+
case "flag":
|
|
492
|
+
return {
|
|
493
|
+
left: `${short}${o.negatable ? `--[no-]${e.long.slice(2)}` : e.long}`,
|
|
494
|
+
note: o.negatable && o.fallback.kind === "default" ? ` (default: ${o.fallback.value ? e.long : `--no-${e.long.slice(2)}`})` : "",
|
|
495
|
+
};
|
|
496
|
+
case "value": {
|
|
497
|
+
const f = o.fallback;
|
|
498
|
+
const note = f.kind === "default" ? ` (default: ${shown(f.value)})` : f.kind === "required" ? " (required)" : "";
|
|
499
|
+
return { left: `${short}${e.long} ${o.valueName}`, note };
|
|
500
|
+
}
|
|
501
|
+
case "many":
|
|
502
|
+
return { left: `${short}${e.long} ${o.valueName}`, note: " (repeatable)" };
|
|
503
|
+
default:
|
|
504
|
+
return absurd(o);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Lines of two columns, the second aligned two spaces after the widest first. */
|
|
509
|
+
function columns(rows: readonly (readonly [string, string])[]): readonly string[] {
|
|
510
|
+
const width = Math.max(0, ...rows.map(([l]) => l.length));
|
|
511
|
+
return rows.map(([l, r]) => ` ${l.padEnd(width)} ${r}`.trimEnd());
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** The help of a command: its summary, its usage, its options aligned with their defaults, and its arguments. */
|
|
515
|
+
export function helpText<S extends Spec>(
|
|
516
|
+
program: string,
|
|
517
|
+
summary: string,
|
|
518
|
+
spec: S & SpecCheck<S>,
|
|
519
|
+
operands: readonly Operand[] = [],
|
|
520
|
+
): string {
|
|
521
|
+
return helpOf(program, summary, spec, operands);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** The help of a command whose spec was checked where it was declared (a verb of `./commands.ts`), as `helpText` gives it. */
|
|
525
|
+
export function helpOf(program: string, summary: string, spec: Spec, operands: readonly Operand[] = []): string {
|
|
526
|
+
const entries: readonly Entry[] = Object.keys(spec).flatMap((key) => {
|
|
527
|
+
const option = spec[key];
|
|
528
|
+
return option === undefined ? [] : [{ key, long: longName(key), option }];
|
|
529
|
+
});
|
|
530
|
+
const required = entries.flatMap((e) =>
|
|
531
|
+
e.option.kind === "value" && e.option.fallback.kind === "required" ? [`${e.long} ${e.option.valueName}`] : [],
|
|
532
|
+
);
|
|
533
|
+
const usage = [program, "[OPTIONS]", ...required, ...operands.map(operandWord)].join(" ");
|
|
534
|
+
const rows = entries.map((e): readonly [string, string] => {
|
|
535
|
+
const line = optionLine(e);
|
|
536
|
+
return [line.left, `${e.option.help}${line.note}`];
|
|
537
|
+
});
|
|
538
|
+
return [
|
|
539
|
+
`${program}: ${summary}`,
|
|
540
|
+
"",
|
|
541
|
+
`Usage: ${usage}`,
|
|
542
|
+
"",
|
|
543
|
+
"Options:",
|
|
544
|
+
...columns([...rows, ["-h, --help", "Show this help and do nothing else."]]),
|
|
545
|
+
...(operands.length === 0 ? [] : ["", "Arguments:", ...columns(operands.map((o) => [operandWord(o), o.help]))]),
|
|
546
|
+
].join("\n");
|
|
547
|
+
}
|