-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathargs.ts
More file actions
68 lines (55 loc) · 1.68 KB
/
Copy pathargs.ts
File metadata and controls
68 lines (55 loc) · 1.68 KB
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
import { parseArgs } from 'node:util';
type ParsedRstackArgs = {
args: string[];
configPath?: string;
};
export function parseCliArgs(args: string[]): ParsedRstackArgs {
const { tokens } = parseArgs({
args,
options: {
config: { type: 'string', short: 'c' },
},
strict: false,
allowPositionals: true,
tokens: true,
});
let removedIndexes: number[] | undefined;
let configPath: string | undefined;
for (const token of tokens) {
if (token.kind === 'option-terminator') {
break;
}
// parseArgs expands short option groups like `-abc`; only consume `-c` when it starts the raw arg.
if (
token.kind !== 'option' ||
token.name !== 'config' ||
(token.rawName === '-c' && !args[token.index].startsWith('-c'))
) {
continue;
}
if (token.value === undefined || token.value.length === 0) {
throw new Error(`Missing value for ${token.rawName}.`);
}
configPath = token.value;
const indexes = (removedIndexes ??= []);
indexes.push(token.index);
if (!token.inlineValue) {
indexes.push(token.index + 1);
}
}
if (!removedIndexes) {
return { args };
}
return {
args: args.filter((_, index) => !removedIndexes.includes(index)),
configPath,
};
}
export function insertConfigArg(args: string[], option: string, configPath: string): string[] {
// Keep the injected config before `--`; arguments after it must remain positional for the child CLI.
const terminatorIndex = args.indexOf('--');
if (terminatorIndex === -1) {
return [...args, option, configPath];
}
return [...args.slice(0, terminatorIndex), option, configPath, ...args.slice(terminatorIndex)];
}