mirror of
https://github.com/NixOS/nixpkgs.git
synced 2024-11-25 16:33:15 +00:00
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.
This commit is contained in:
parent
88a7f65c83
commit
582354d3b6
26
lib/cli.nix
26
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 =
|
||||
|
@ -441,9 +441,34 @@ runTests {
|
||||
expected = "«foo»";
|
||||
};
|
||||
|
||||
testRenderOptions = {
|
||||
|
||||
# CLI
|
||||
|
||||
testToGNUCommandLine = {
|
||||
expr =
|
||||
encodeGNUCommandLine
|
||||
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 =
|
||||
cli.toGNUCommandLineShell
|
||||
{ }
|
||||
{ data = builtins.toJSON { id = 0; };
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user