From 1cd48efa96bc677bfbf7111bd116d092521c3914 Mon Sep 17 00:00:00 2001 From: Emery Hemingway Date: Wed, 24 Mar 2021 11:20:36 +0100 Subject: [PATCH] lib/generators: add toDhall --- lib/generators.nix | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/generators.nix b/lib/generators.nix index 501a23599f4..c8144db50ac 100644 --- a/lib/generators.nix +++ b/lib/generators.nix @@ -307,4 +307,28 @@ rec { ${expr "" v} ''; + /* Translate a simple Nix expression to Dhall notation. + * Note that integers are translated to Integer and never + * the Natural type. + */ + toDhall = { }@args: v: + with builtins; + let concatItems = lib.strings.concatStringsSep ", "; + in if isAttrs v then + "{ ${ + concatItems (lib.attrsets.mapAttrsToList + (key: value: "${key} = ${toDhall args value}") v) + } }" + else if isList v then + "[ ${concatItems (map (toDhall args) v)} ]" + else if isInt v then + "${if v < 0 then "" else "+"}${toString v}" + else if isBool v then + (if v then "True" else "False") + else if isFunction v then + abort "generators.toDhall: cannot convert a function to Dhall" + else if isNull v then + abort "generators.toDhall: cannot convert a null to Dhall" + else + builtins.toJSON v; }