summaryrefslogtreecommitdiffstats
path: root/lib/generators.nix
diff options
context:
space:
mode:
authorProfpatsch <mail@profpatsch.de>2017-06-06 22:41:22 +0200
committerProfpatsch <mail@profpatsch.de>2017-06-22 00:58:59 +0200
commitb1ffe5e4c029c9f5675bcc42997413fd1b21fbf1 (patch)
treef8569d068102606b54724713c1c6a51cc4f539dc /lib/generators.nix
parentdd3f2e648a6ee5dc7ba88bf2e3d13b6b47686350 (diff)
lib/generators: toPretty
`toPretty` implements a pretty printer for nix values.
Diffstat (limited to 'lib/generators.nix')
-rw-r--r--lib/generators.nix32
1 files changed, 32 insertions, 0 deletions
diff --git a/lib/generators.nix b/lib/generators.nix
index 4d3c920b0ae3..0e5ce864356a 100644
--- a/lib/generators.nix
+++ b/lib/generators.nix
@@ -90,4 +90,36 @@ rec {
* parsers as well.
*/
toYAML = {}@args: toJSON args;
+
+ # TODO we need some kind of pattern matching sometimes
+ /* Pretty print a value, akin to `builtins.trace`.
+ * Should probably be a builtin as well.
+ */
+ toPretty = {
+ /* If this option is true, attrsets like { __pretty = fn; val = …; }
+ will use fn to convert val to a pretty printed representation.
+ (This means fn is type Val -> String.) */
+ allowPrettyValues ? false
+ }@args: v: with builtins;
+ if isInt v then toString v
+ else if isBool v then (if v == true then "true" else "false")
+ else if isString v then "\"" + v + "\""
+ else if null == v then "null"
+ else if isFunction v then "<λ>"
+ else if isList v then "[ "
+ + libStr.concatMapStringsSep " " (toPretty args) v
+ + " ]"
+ else if isAttrs v then
+ # apply pretty values if allowed
+ if attrNames v == [ "__pretty" "val" ] && allowPrettyValues
+ then v.__pretty v.val
+ # TODO: there is probably a better representation?
+ else if v ? type && v.type == "derivation" then "<δ>"
+ else "{ "
+ + libStr.concatStringsSep " " (libAttr.mapAttrsToList
+ (name: value:
+ "${toPretty args name} = ${toPretty args value};") v)
+ + " }"
+ else "toPretty: should never happen (v = ${v})";
+
}