summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorProfpatsch <mail@profpatsch.de>2020-01-22 23:24:06 +0100
committerProfpatsch <mail@profpatsch.de>2020-01-23 14:47:38 +0100
commit582354d3b6161384cf69a90f6c00d7e29382950a (patch)
treee38cd6623da82c4154a3aae433e2db7fba7e4d9a
parent88a7f65c834ec09ce9df0c23c9935630e17a0c4a (diff)
lib/cli: encodeGNUCommandLine -> toGNUCommandLineShell
The semantic difference between `encode` and `to` is not apparent. Users are likely to confuse both functions (which leads to unexpected error messages about the wrong types). Like in `generators.nix`, all functions should be prefixed by `to`. Furthermore, converting to a string depends on the target context. In this case, it’s a POSIX shell, so we should name it that (compare `escapeShellArg` in `strings.nix`). We can later add versions that escape for embedding in e.g. python scripts or similar.
-rw-r--r--lib/cli.nix26
-rw-r--r--lib/tests/misc.nix29
2 files changed, 51 insertions, 4 deletions
diff --git a/lib/cli.nix b/lib/cli.nix
index f47625d2f537..32d24a00ceb0 100644
--- a/lib/cli.nix
+++ b/lib/cli.nix
@@ -6,8 +6,29 @@ rec {
This helps protect against malformed command lines and also to reduce
boilerplate related to command-line construction for simple use cases.
+ `toGNUCommandLine` returns a list of nix strings.
+ `toGNUCommandLineShell` returns an escaped shell string.
+
Example:
- encodeGNUCommandLine
+ toGNUCommandLine
+ { }
+ { 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;
+ };
+ => [ "-X" "PUT" "--data" "{\"id\":0}" "--retry" "3" "--url" "https://example.com/foo" "--url" "https://example.com/bar" "--verbose" ]
+
+ toGNUCommandLineShell
{ }
{ data = builtins.toJSON { id = 0; };
@@ -24,8 +45,9 @@ rec {
verbose = true;
};
=> "'-X' 'PUT' '--data' '{\"id\":0}' '--retry' '3' '--url' 'https://example.com/foo' '--url' 'https://example.com/bar' '--verbose'"
+
*/
- encodeGNUCommandLine =
+ toGNUCommandLineShell =
options: attrs: lib.escapeShellArgs (toGNUCommandLine options attrs);
toGNUCommandLine =
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index e47b48b5017d..b320839b2ac7 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -441,9 +441,34 @@ runTests {
expected = "«foo»";
};
- testRenderOptions = {
+
+# CLI
+
+ testToGNUCommandLine = {
+ expr =
+ cli.toGNUCommandLine
+ { }
+ { 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 =
- encodeGNUCommandLine
+ cli.toGNUCommandLineShell
{ }
{ data = builtins.toJSON { id = 0; };