forked from rstackjs/rstack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargs.ts
More file actions
146 lines (119 loc) · 3.95 KB
/
Copy pathargs.ts
File metadata and controls
146 lines (119 loc) · 3.95 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
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
import {
parseArgs as nodeParseArgs,
type ParseArgsConfig as NodeParseArgsConfig,
type ParseArgsOptionDescriptor as NodeParseArgsOptionDescriptor,
type ParseArgsOptionsConfig,
} from 'node:util';
type ParseArgsOptionDescriptor = Omit<NodeParseArgsOptionDescriptor, 'default'> & {
default?: never;
};
type ParseArgsConfig = Omit<NodeParseArgsConfig, 'options'> & {
options?: Record<string, ParseArgsOptionDescriptor>;
};
type CamelCase<Value extends string> = Value extends `${infer Head}-${infer Tail}`
? `${Head}${Capitalize<CamelCase<Tail>>}`
: Value;
type NodeParseArgsResult<Config extends ParseArgsConfig> = ReturnType<typeof nodeParseArgs<Config>>;
type ParseArgsResult<Config extends ParseArgsConfig> = Omit<
NodeParseArgsResult<Config>,
'values'
> & {
values: {
[
Name in keyof NodeParseArgsResult<Config>['values'] as CamelCase<Name & string>
]: NodeParseArgsResult<Config>['values'][Name];
};
};
const KEBAB_CASE_REGEXP = /-([a-z])/g;
const toCamelCase = (value: string): string =>
value.includes('-')
? value.replace(KEBAB_CASE_REGEXP, (_, character: string) => character.toUpperCase())
: value;
export function parseArgs<const Config extends ParseArgsConfig = ParseArgsConfig>(
config?: Config,
): ParseArgsResult<Config> {
const options: ParseArgsOptionsConfig = {};
const optionNames: [originalName: string, camelName: string][] = [];
for (const [originalName, descriptor] of Object.entries(config?.options ?? {})) {
const camelName = toCamelCase(originalName);
optionNames.push([originalName, camelName]);
options[originalName] = descriptor;
if (camelName !== originalName) {
options[camelName] = descriptor;
}
}
const parsed = nodeParseArgs({
...config,
options,
});
const values: Record<string, unknown> = {};
for (const [originalName, camelName] of optionNames) {
const originalValue = parsed.values[originalName];
const camelValue = camelName === originalName ? undefined : parsed.values[camelName];
const value =
Array.isArray(originalValue) && Array.isArray(camelValue)
? [...originalValue, ...camelValue]
: (originalValue ?? camelValue);
if (value !== undefined) {
values[camelName] = value;
}
}
return {
...parsed,
values,
} as unknown as ParseArgsResult<Config>;
}
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)];
}