-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcommand.ts
More file actions
167 lines (150 loc) · 5.71 KB
/
command.ts
File metadata and controls
167 lines (150 loc) · 5.71 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import ansis from 'ansis';
import path from 'node:path';
type ArgumentValue = number | string | boolean | string[] | undefined;
export type CliArgsObject<T extends object = Record<string, ArgumentValue>> =
T extends never
? Record<string, ArgumentValue | undefined> | { _: string }
: T;
/**
* Escapes command line arguments that contain spaces, quotes, or other special characters.
*
* @param {string[]} args - Array of command arguments to escape.
* @returns {string[]} - Array of escaped arguments suitable for shell execution.
*/
export function escapeCliArgs(args: string[]): string[] {
return args.map(arg => {
if (arg.includes(' ') || arg.includes('"') || arg.includes("'")) {
return `"${arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
}
return arg;
});
}
/**
* Formats environment variable values for display by stripping quotes and then escaping.
*
* @param {string} value - Environment variable value to format.
* @returns {string} - Formatted and escaped value suitable for display.
*/
export function formatEnvValue(value: string): string {
// Strip quotes from the value for display
const cleanValue = value.replace(/"/g, '');
return escapeCliArgs([cleanValue])[0] ?? cleanValue;
}
/**
* Builds a command string by escaping arguments that contain spaces, quotes, or other special characters.
*
* @param {string} command - The base command to execute.
* @param {string[]} args - Array of command arguments.
* @returns {string} - The complete command string with properly escaped arguments.
*/
export function buildCommandString(
command: string,
args: string[] = [],
): string {
if (args.length === 0) {
return command;
}
return `${command} ${escapeCliArgs(args).join(' ')}`;
}
/**
* Options for formatting a command log.
*/
export interface FormatCommandLogOptions {
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string>;
}
/**
* Formats a command string with optional cwd prefix, environment variables, and ANSI colors.
*
* @param {FormatCommandLogOptions} options - Command formatting options.
* @returns {string} - ANSI-colored formatted command string.
*
* @example
*
* formatCommandLog({cwd: 'tools/api', env: {API_KEY='•••' NODE_ENV='prod'}, command: 'node', args: ['cli.js', '--do', 'thing', 'fast']})
* ┌─────────────────────────────────────────────────────────────────────────┐
* │ tools/api $ API_KEY="•••" NODE_ENV="prod" node cli.js --do thing fast │
* │ │ │ │ │ │ │
* │ └ cwd │ │ │ └ args. │
* │ │ │ └ command │
* │ │ └ env variables │
* │ └ prompt symbol ($) │
* └─────────────────────────────────────────────────────────────────────────┘
*/
export function formatCommandLog(options: FormatCommandLogOptions): string {
const { command, args = [], cwd = process.cwd(), env } = options;
const relativeDir = path.relative(process.cwd(), cwd);
return [
...(relativeDir && relativeDir !== '.'
? [ansis.italic(ansis.gray(relativeDir))]
: []),
ansis.yellow('$'),
...(env && Object.keys(env).length > 0
? Object.entries(env).map(([key, value]) => {
return ansis.gray(`${key}=${formatEnvValue(value)}`);
})
: []),
ansis.gray(command),
ansis.gray(args.join(' ')),
].join(' ');
}
/**
* Converts an object with different types of values into an array of command-line arguments.
*
* @example
* const args = objectToCliArgs({
* _: ['node', 'index.js'], // node index.js
* name: 'Juanita', // --name=Juanita
* formats: ['json', 'md'] // --format=json --format=md
* });
*/
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}`];
}
const prefix = key.length === 1 ? '-' : '--';
// "-*" arguments (shorthands)
if (Array.isArray(value)) {
return value.map(v => `${prefix}${key}="${v}"`);
}
// "--*" arguments ==========
if (typeof value === 'object') {
return Object.entries(value as Record<string, ArgumentValue>).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 (typeof value === 'undefined') {
return [];
}
throw new Error(`Unsupported type ${typeof value} for key ${key}`);
});
}
/**
* Converts a file path to a CLI argument by wrapping it in quotes to handle spaces.
*
* @param {string} filePath - The file path to convert to a CLI argument.
* @returns {string} - The quoted file path suitable for CLI usage.
*/
export function filePathToCliArg(filePath: string): string {
// needs to be escaped if spaces included
return `"${filePath}"`;
}