|
| 1 | +import ansis from 'ansis'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +type ArgumentValue = number | string | boolean | string[] | undefined; |
| 5 | +export type CliArgsObject<T extends object = Record<string, ArgumentValue>> = |
| 6 | + T extends never |
| 7 | + ? Record<string, ArgumentValue | undefined> | { _: string } |
| 8 | + : T; |
| 9 | + |
| 10 | +/** |
| 11 | + * Escapes command line arguments that contain spaces, quotes, or other special characters. |
| 12 | + * |
| 13 | + * @param {string[]} args - Array of command arguments to escape. |
| 14 | + * @returns {string[]} - Array of escaped arguments suitable for shell execution. |
| 15 | + */ |
| 16 | +export function escapeCliArgs(args: string[]): string[] { |
| 17 | + return args.map(arg => { |
| 18 | + if (arg.includes(' ') || arg.includes('"') || arg.includes("'")) { |
| 19 | + return `"${arg.replace(/"/g, '\\"')}"`; |
| 20 | + } |
| 21 | + return arg; |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Formats environment variable values for display by stripping quotes and then escaping. |
| 27 | + * |
| 28 | + * @param {string} value - Environment variable value to format. |
| 29 | + * @returns {string} - Formatted and escaped value suitable for display. |
| 30 | + */ |
| 31 | +export function formatEnvValue(value: string): string { |
| 32 | + // Strip quotes from the value for display |
| 33 | + const cleanValue = value.replace(/"/g, ''); |
| 34 | + return escapeCliArgs([cleanValue])[0] ?? cleanValue; |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Builds a command string by escaping arguments that contain spaces, quotes, or other special characters. |
| 39 | + * |
| 40 | + * @param {string} command - The base command to execute. |
| 41 | + * @param {string[]} args - Array of command arguments. |
| 42 | + * @returns {string} - The complete command string with properly escaped arguments. |
| 43 | + */ |
| 44 | +export function buildCommandString( |
| 45 | + command: string, |
| 46 | + args: string[] = [], |
| 47 | +): string { |
| 48 | + if (args.length === 0) { |
| 49 | + return command; |
| 50 | + } |
| 51 | + |
| 52 | + return `${command} ${escapeCliArgs(args).join(' ')}`; |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Options for formatting a command log. |
| 57 | + */ |
| 58 | +export interface FormatCommandLogOptions { |
| 59 | + command: string; |
| 60 | + args?: string[]; |
| 61 | + cwd?: string; |
| 62 | + env?: Record<string, string>; |
| 63 | +} |
| 64 | + |
| 65 | +/** |
| 66 | + * Formats a command string with optional cwd prefix, environment variables, and ANSI colors. |
| 67 | + * |
| 68 | + * @param {FormatCommandLogOptions} options - Command formatting options. |
| 69 | + * @returns {string} - ANSI-colored formatted command string. |
| 70 | + */ |
| 71 | +export function formatCommandLog(options: FormatCommandLogOptions): string { |
| 72 | + const { command, args = [], cwd = process.cwd(), env } = options; |
| 73 | + const relativeDir = path.relative(process.cwd(), cwd); |
| 74 | + |
| 75 | + return [ |
| 76 | + ...(relativeDir && relativeDir !== '.' |
| 77 | + ? [ansis.italic(ansis.gray(relativeDir))] |
| 78 | + : []), |
| 79 | + ansis.yellow('$'), |
| 80 | + ...(env && Object.keys(env).length > 0 |
| 81 | + ? Object.entries(env).map(([key, value]) => { |
| 82 | + return ansis.gray(`${key}=${formatEnvValue(value)}`); |
| 83 | + }) |
| 84 | + : []), |
| 85 | + ansis.gray(command), |
| 86 | + ansis.gray(escapeCliArgs(args).join(' ')), |
| 87 | + ].join(' '); |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Converts an object with different types of values into an array of command-line arguments. |
| 92 | + * |
| 93 | + * @example |
| 94 | + * const args = objectToCliArgs({ |
| 95 | + * _: ['node', 'index.js'], // node index.js |
| 96 | + * name: 'Juanita', // --name=Juanita |
| 97 | + * formats: ['json', 'md'] // --format=json --format=md |
| 98 | + * }); |
| 99 | + */ |
| 100 | +export function objectToCliArgs< |
| 101 | + T extends object = Record<string, ArgumentValue>, |
| 102 | +>(params?: CliArgsObject<T>): string[] { |
| 103 | + if (!params) { |
| 104 | + return []; |
| 105 | + } |
| 106 | + |
| 107 | + return Object.entries(params).flatMap(([key, value]) => { |
| 108 | + // process/file/script |
| 109 | + if (key === '_') { |
| 110 | + return Array.isArray(value) ? value : [`${value}`]; |
| 111 | + } |
| 112 | + const prefix = key.length === 1 ? '-' : '--'; |
| 113 | + // "-*" arguments (shorthands) |
| 114 | + if (Array.isArray(value)) { |
| 115 | + return value.map(v => `${prefix}${key}="${v}"`); |
| 116 | + } |
| 117 | + // "--*" arguments ========== |
| 118 | + |
| 119 | + if (typeof value === 'object') { |
| 120 | + return Object.entries(value as Record<string, ArgumentValue>).flatMap( |
| 121 | + // transform nested objects to the dot notation `key.subkey` |
| 122 | + ([k, v]) => objectToCliArgs({ [`${key}.${k}`]: v }), |
| 123 | + ); |
| 124 | + } |
| 125 | + |
| 126 | + if (typeof value === 'string') { |
| 127 | + return [`${prefix}${key}="${value}"`]; |
| 128 | + } |
| 129 | + |
| 130 | + if (typeof value === 'number') { |
| 131 | + return [`${prefix}${key}=${value}`]; |
| 132 | + } |
| 133 | + |
| 134 | + if (typeof value === 'boolean') { |
| 135 | + return [`${prefix}${value ? '' : 'no-'}${key}`]; |
| 136 | + } |
| 137 | + |
| 138 | + if (typeof value === 'undefined') { |
| 139 | + return []; |
| 140 | + } |
| 141 | + |
| 142 | + throw new Error(`Unsupported type ${typeof value} for key ${key}`); |
| 143 | + }); |
| 144 | +} |
| 145 | + |
| 146 | +/** |
| 147 | + * Converts a file path to a CLI argument by wrapping it in quotes to handle spaces. |
| 148 | + * |
| 149 | + * @param {string} filePath - The file path to convert to a CLI argument. |
| 150 | + * @returns {string} - The quoted file path suitable for CLI usage. |
| 151 | + */ |
| 152 | +export function filePathToCliArg(filePath: string): string { |
| 153 | + // needs to be escaped if spaces included |
| 154 | + return `"${filePath}"`; |
| 155 | +} |
0 commit comments