about summary refs log tree commit diff
path: root/lib/cli.nix
blob: f3a81cb9e9c479ce863354078c2ceae47177f925 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{ lib }:

{ /* Automatically convert an attribute set to command-line options.

     This helps protect against malformed command lines and also to reduce
     boilerplate related to command-line construction for simple use cases.

     Example:
       encodeGNUCommandLine { } { foo = "A"; bar = 1; baz = null; qux = true; v = true; }
       => " --bar '1' --foo 'A' --qux -v"
  */
  encodeGNUCommandLine =
    { renderKey ?
        key: if builtins.stringLength key == 1 then "-${key}" else "--${key}"

    , renderOption ?
        key: value:
          if value == null
          then ""
          else " ${renderKey key} ${lib.escapeShellArg value}"

    , renderBool ? key: value: if value then " ${renderKey key}" else ""

    , renderList ? key: value: lib.concatMapStrings renderOption value
    }:
    options:
      let
        render = key: value:
                 if builtins.isBool value
            then renderBool key value
            else if builtins.isList value
            then renderList key value
            else renderOption key value;

      in
        lib.concatStrings (lib.mapAttrsToList render options);
}