From 183a99734f666b6bd508f4c81e887dbc746fec69 Mon Sep 17 00:00:00 2001 From: Gabriel Gonzalez Date: Wed, 11 Dec 2019 16:30:05 -0800 Subject: Add `pkgs.lib.renderOptions` This adds a new utility to intelligently convert Nix records to command line options to reduce boilerplate for simple use cases and to also reduce the likelihood of malformed command lines --- lib/cli.nix | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lib/cli.nix (limited to 'lib/cli.nix') diff --git a/lib/cli.nix b/lib/cli.nix new file mode 100644 index 00000000000..d794778b21a --- /dev/null +++ b/lib/cli.nix @@ -0,0 +1,33 @@ +{ 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: + renderOptions { foo = "A"; bar = 1; baz = null; qux = true; v = true; } + => " --bar '1' --foo 'A' --qux -v" + */ + renderOptions = + options: + let + render = key: value: + let + hyphenate = + k: if builtins.stringLength k == 1 then "-${k}" else "--${k}"; + + renderOption = v: if v == null then "" else " ${hyphenate key} ${lib.escapeShellArg v}"; + + renderSwitch = if value then " ${hyphenate key}" else ""; + + in + if builtins.isBool value + then renderSwitch + else if builtins.isList value + then lib.concatMapStrings renderOption value + else renderOption value; + + in + lib.concatStrings (lib.mapAttrsToList render options); +} -- cgit 1.4.1