-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcli.ts
More file actions
77 lines (66 loc) · 2.12 KB
/
cli.ts
File metadata and controls
77 lines (66 loc) · 2.12 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
export function createCliCommandString(options?: {
args?: Record<string, unknown>;
command?: string;
bin?: string;
}): string {
const { bin = '@code-pushup/cli', command, args } = options ?? {};
return `npx ${bin} ${objectToCliArgs({ _: command ?? [], ...args }).join(
' ',
)}`;
}
export function createCliCommandObject(options?: {
args?: Record<string, unknown>;
command?: string;
bin?: string;
}): import('@code-pushup/utils').ProcessConfig {
const { bin = '@code-pushup/cli', command, args } = options ?? {};
return {
command: 'npx',
args: [bin, ...objectToCliArgs({ _: command ?? [], ...args })],
};
}
type ArgumentValue = number | string | boolean | string[];
export type CliArgsObject<T extends object = Record<string, ArgumentValue>> =
T extends never
? Record<string, ArgumentValue | undefined> | { _: string }
: T;
// @TODO import from @code-pushup/utils => get rid of poppins for cjs support
export function objectToCliArgs<
T extends object = Record<string, ArgumentValue>,
>(params?: CliArgsObject<T>): string[] {
if (!params) {
return [];
}
return Object.entries(params).flatMap(([key, value]) => {
// process/file/script
if (key === '_') {
return (Array.isArray(value) ? value : [`${value}`]).filter(
v => v != null,
);
}
const prefix = key.length === 1 ? '-' : '--';
// "-*" arguments (shorthands)
if (Array.isArray(value)) {
return value.map(v => `${prefix}${key}="${v}"`);
}
if (typeof value === 'object') {
return Object.entries(value as Record<string, unknown>).flatMap(
// transform nested objects to the dot notation `key.subkey`
([k, v]) => objectToCliArgs({ [`${key}.${k}`]: v }),
);
}
if (typeof value === 'string') {
return [`${prefix}${key}="${value}"`];
}
if (typeof value === 'number') {
return [`${prefix}${key}=${value}`];
}
if (typeof value === 'boolean') {
return [`${prefix}${value ? '' : 'no-'}${key}`];
}
if (value === undefined) {
return [];
}
throw new Error(`Unsupported type ${typeof value} for key ${key}`);
});
}