/ utils / bash / shellPrefix.ts
shellPrefix.ts
 1  import { quote } from './shellQuote.js'
 2  
 3  /**
 4   * Parses a shell prefix that may contain an executable path and arguments.
 5   *
 6   * Examples:
 7   * - "bash" -> quotes as 'bash'
 8   * - "/usr/bin/bash -c" -> quotes as '/usr/bin/bash' -c
 9   * - "C:\Program Files\Git\bin\bash.exe -c" -> quotes as 'C:\Program Files\Git\bin\bash.exe' -c
10   *
11   * @param prefix The shell prefix string containing executable and optional arguments
12   * @param command The command to be executed
13   * @returns The properly formatted command string with quoted components
14   */
15  export function formatShellPrefixCommand(
16    prefix: string,
17    command: string,
18  ): string {
19    // Split on the last space before a dash to separate executable from arguments
20    const spaceBeforeDash = prefix.lastIndexOf(' -')
21    if (spaceBeforeDash > 0) {
22      const execPath = prefix.substring(0, spaceBeforeDash)
23      const args = prefix.substring(spaceBeforeDash + 1)
24      return `${quote([execPath])} ${args} ${quote([command])}`
25    } else {
26      return `${quote([prefix])} ${quote([command])}`
27    }
28  }