shell-quote.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Shell-escape an array of arguments into a single string that, when parsed
  3. * by a POSIX shell (`sh -c`, `bash -c`, `zsh -c`), yields exactly the
  4. * original argument list.
  5. *
  6. * This intentionally replaces the npm `shell-quote` package. Its quote()
  7. * switches to a double-quote + backslash strategy whenever an argument
  8. * contains a single quote, and in that mode it backslash-escapes `!` — a
  9. * guard against history expansion that only applies to *interactive*
  10. * shells. Every string this library produces is executed through a
  11. * non-interactive `<shell> -c`, where bash treats `\!` inside double quotes
  12. * as two literal characters (the backslash is NOT removed). The wrapped
  13. * user command almost always contains a single quote, so every `!` in it
  14. * reached the program corrupted to `\!`: heredoc-written source like
  15. * `if (!x)` became unparseable, and `jq 'a != b'`, `awk '!seen[$0]++'`,
  16. * and `find ! -name` filters were silently rewritten.
  17. *
  18. * Single-quoting never has that problem. Inside POSIX single quotes every
  19. * byte is literal, so nothing needs escaping; the only character that
  20. * needs handling is the single quote itself, emitted as the standard
  21. * `'"'"'` sequence (close the quote, a double-quoted `'`, reopen).
  22. *
  23. * @param args - The argument list to escape
  24. * @returns A single space-joined string safe to pass to `<shell> -c`
  25. */
  26. export function quote(args: readonly string[]): string {
  27. return args
  28. .map((arg) => {
  29. if (arg === "") {
  30. return "''";
  31. }
  32. // Bare fast path: nothing in this character set is special to a
  33. // POSIX shell (no whitespace, globs, expansions, quotes, or
  34. // operators), so the bare word re-parses to exactly itself. The one
  35. // position-sensitive case is a LEADING "=": zsh (a common binShell,
  36. // even non-interactive `zsh -c`) performs "equals expansion" on an
  37. // unquoted word starting with "=" (`=ls` becomes /bin/ls; an unknown
  38. // name aborts the whole command line), so such a word must be quoted.
  39. // "=" elsewhere in the word (NAME=value env assignments) is fine.
  40. if (/^[A-Za-z0-9_./:@+,-][A-Za-z0-9_./:=@+,-]*$/.test(arg)) {
  41. return arg;
  42. }
  43. return "'" + arg.replace(/'/g, `'"'"'`) + "'";
  44. })
  45. .join(" ");
  46. }