query
On this page

toCommandLine

lib.cli.toCommandLine

Docs pulled from | This Revision | 4 days ago


Converts an attribute set into a list of command line options.

toCommandLine returns a list of string arguments.

Inputs

optionFormat

The option format that describes how options and their arguments should be formatted.

attrs

The attributes to transform into arguments.

Examples

lib.cli.toCommandLine usage example

let
  optionFormat = optionName: {
    option = "-${optionName}";
    sep = "=";
    explicitBool = true;
  };
in lib.cli.toCommandLine optionFormat {
  v = true;
  verbose = [true true false null];
  i = ".bak";
  testsuite = ["unit" "integration"];
  e = ["s/a/b/" "s/b/c/"];
  n = false;
  data = builtins.toJSON {id = 0;};
}
=> [
  "-data={\"id\":0}"
  "-e=s/a/b/"
  "-e=s/b/c/"
  "-i=.bak"
  "-n=false"
  "-testsuite=unit"
  "-testsuite=integration"
  "-v=true"
  "-verbose=true"
  "-verbose=true"
  "-verbose=false"
]

Noogle detected

Implementation

The following is the current implementation of this function.

toCommandLine =
    optionFormat: attrs:
    let
      handlePair =
        k: v:
        if k == "" then
          lib.throw "lib.cli.toCommandLine only accepts non-empty option names."
        else if builtins.isList v then
          builtins.concatMap (handleOption k) v
        else
          handleOption k v;

      handleOption = k: renderOption (optionFormat k) k;

      renderOption =
        {
          option,
          sep,
          explicitBool,
          formatArg ? lib.generators.mkValueStringDefault { },
        }:
        k: v:
        if v == null || (!explicitBool && v == false) then
          [ ]
        else if !explicitBool && v == true then
          [ option ]
        else
          let
            arg = formatArg v;
          in
          if sep != null then
            [ "${option}${sep}${arg}" ]
          else
            [
              option
              arg
            ];
    in
    builtins.concatLists (lib.mapAttrsToList handlePair attrs);