diff options
| author | Gabriella Gonzalez <GenuineGabriella@gmail.com> | 2024-08-16 16:26:08 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-08-16 16:26:08 +0200 |
| commit | 75c122699aa9b111b20124af29873762479c6cff (patch) | |
| tree | f124cdc995232248c858b9c22282c9ab3b3225dd /lib/strings.nix | |
| parent | Merge staging-next into staging (diff) | |
| download | nixpkgs-75c122699aa9b111b20124af29873762479c6cff.tar.gz | |
lib.cli.escapeShellArg{,s}: Only escape when necessary (#333744)
These utilities will now leave the string undisturbed if it doesn't need to be quoted (because it doesn't have any special characters). This can help generate nicer-looking command lines.
This also transitively improves the output of `lib.toGNUCommandLine` which uses `escapeShellArg` internally
Diffstat (limited to 'lib/strings.nix')
| -rw-r--r-- | lib/strings.nix | 16 |
1 files changed, 12 insertions, 4 deletions
diff --git a/lib/strings.nix b/lib/strings.nix index aafbdffaa7bc..54a5b9c67434 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -1026,7 +1026,8 @@ rec { replaceStrings (builtins.attrNames toEscape) (lib.mapAttrsToList (_: c: "%${fixedWidthString 2 "0" (lib.toHexString c)}") toEscape); /** - Quote `string` to be used safely within the Bourne shell. + Quote `string` to be used safely within the Bourne shell if it has any + special characters. # Inputs @@ -1051,10 +1052,17 @@ rec { ::: */ - escapeShellArg = arg: "'${replaceStrings ["'"] ["'\\''"] (toString arg)}'"; + escapeShellArg = arg: + let + string = toString arg; + in + if match "[[:alnum:],._+:@%/-]+" string == null + then "'${replaceStrings ["'"] ["'\\''"] string}'" + else string; /** - Quote all arguments to be safely passed to the Bourne shell. + Quote all arguments that have special characters to be safely passed to the + Bourne shell. # Inputs @@ -1073,7 +1081,7 @@ rec { ```nix escapeShellArgs ["one" "two three" "four'five"] - => "'one' 'two three' 'four'\\''five'" + => "one 'two three' 'four'\\''five'" ``` ::: |
