Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib/cli: add wrappingValueString option to toGNUCommandLineShell #373332

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions lib/cli.nix
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ rec {
By default, there is no separator, so option `-c` and value `5` would become ["-c" "5"].
This is useful if the command requires equals, for example, `-c=5`.

`wrappingValueString`

: The string to surround an option's value with.
Values aren't quoted by default, so option `foo` and value `bar` would become ["--foo bar"]
This is useful if your value could be misinterpreted by your shell without quoting.
For example, if you wanted a result of `["--foo \"bar\" "]`, you could set `wrappingValueString` to a literal quote.

# Examples
:::{.example}
## `lib.cli.toGNUCommandLine` usage example
Expand Down Expand Up @@ -118,19 +125,32 @@ rec {

mkList ? k: v: lib.concatMap (mkOption k) v,

optionValueSeparator ? null,

wrappingValueString ? "",

mkOption ?
k: v:
let
surroundedString =
wrappingValueString + lib.generators.mkValueStringDefault { } v + wrappingValueString;
in
if v == null then
[ ]
# We need the option and its value in different list elements, to play nice with `lib.escapeShellArgs`
else if optionValueSeparator == null then
[
(mkOptionName k)
(lib.generators.mkValueStringDefault { } v)
surroundedString
]
else
[ "${mkOptionName k}${optionValueSeparator}${lib.generators.mkValueStringDefault { } v}" ],

optionValueSeparator ? null,
[
(lib.concatStrings [
(mkOptionName k)
optionValueSeparator
surroundedString
])
],
}:
options:
let
Expand Down
21 changes: 21 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -1832,6 +1832,27 @@ runTests {
];
};

testToGNUCommandLineWrapped = {
expr = cli.toGNUCommandLine { wrappingValueString = "\""; } {
data = builtins.toJSON { id = 0; };
X = "PUT";
retry = 3;
retry-delay = null;
url = [ "https://example.com/foo" "https://example.com/bar" ];
silent = false;
verbose = true;
};

expected = [
"-X" "\"PUT\""
"--data" "\"{\"id\":0}\""
"--retry" "\"3\""
"--url" "\"https://example.com/foo\""
"--url" "\"https://example.com/bar\""
"--verbose"
];
};

testToGNUCommandLineShell = {
expr = cli.toGNUCommandLineShell {} {
data = builtins.toJSON { id = 0; };
Expand Down