Factor out a `toGNUCommandLine` utility
... as suggested by @roberth
This commit is contained in:
parent
5edd4dd44c
commit
6d584c2614
18
lib/cli.nix
18
lib/cli.nix
|
@ -1,6 +1,7 @@
|
||||||
{ lib }:
|
{ lib }:
|
||||||
|
|
||||||
{ /* Automatically convert an attribute set to command-line options.
|
rec {
|
||||||
|
/* Automatically convert an attribute set to command-line options.
|
||||||
|
|
||||||
This helps protect against malformed command lines and also to reduce
|
This helps protect against malformed command lines and also to reduce
|
||||||
boilerplate related to command-line construction for simple use cases.
|
boilerplate related to command-line construction for simple use cases.
|
||||||
|
@ -22,21 +23,24 @@
|
||||||
|
|
||||||
verbose = true;
|
verbose = true;
|
||||||
};
|
};
|
||||||
=> " -X 'PUT' --data '{\"id\":0}' --retry '3' --url 'https://example.com/foo' --url 'https://example.com/bar' --verbose"
|
=> "'-X' 'PUT' '--data' '{\"id\":0}' '--retry' '3' '--url' 'https://example.com/foo' '--url' 'https://example.com/bar' '--verbose'"
|
||||||
*/
|
*/
|
||||||
encodeGNUCommandLine =
|
encodeGNUCommandLine =
|
||||||
|
options: attrs: lib.escapeShellArgs (toGNUCommandLine options attrs);
|
||||||
|
|
||||||
|
toGNUCommandLine =
|
||||||
{ renderKey ?
|
{ renderKey ?
|
||||||
key: if builtins.stringLength key == 1 then "-${key}" else "--${key}"
|
key: if builtins.stringLength key == 1 then "-${key}" else "--${key}"
|
||||||
|
|
||||||
, renderOption ?
|
, renderOption ?
|
||||||
key: value:
|
key: value:
|
||||||
if value == null
|
if value == null
|
||||||
then ""
|
then []
|
||||||
else " ${renderKey key} ${lib.escapeShellArg value}"
|
else [ (renderKey key) (builtins.toString value) ]
|
||||||
|
|
||||||
, renderBool ? key: value: if value then " ${renderKey key}" else ""
|
, renderBool ? key: value: lib.optional value (renderKey key)
|
||||||
|
|
||||||
, renderList ? key: value: lib.concatMapStrings (renderOption key) value
|
, renderList ? key: value: lib.concatMap (renderOption key) value
|
||||||
}:
|
}:
|
||||||
options:
|
options:
|
||||||
let
|
let
|
||||||
|
@ -48,5 +52,5 @@
|
||||||
else renderOption key value;
|
else renderOption key value;
|
||||||
|
|
||||||
in
|
in
|
||||||
lib.concatStrings (lib.mapAttrsToList render options);
|
builtins.concatLists (lib.mapAttrsToList render options);
|
||||||
}
|
}
|
||||||
|
|
|
@ -460,6 +460,6 @@ runTests {
|
||||||
verbose = true;
|
verbose = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
expected = " -X 'PUT' --data '{\"id\":0}' --retry '3' --url 'https://example.com/foo' --url 'https://example.com/bar' --verbose";
|
expected = "'-X' 'PUT' '--data' '{\"id\":0}' '--retry' '3' '--url' 'https://example.com/foo' '--url' 'https://example.com/bar' '--verbose'";
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue