From 26eb10e771c2e7abdfe79d7f3db472af2e56a9fd Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Sun, 6 Nov 2016 14:14:24 +0100 Subject: [PATCH] lib: add generator functions for toJSON & toYAML They both reference the toJSON builtin, so we get semantic identifiers that express the intent of the generation. Both should be able to map each nix value (minus functions) to the destination config files. Includes two invocation unit tests. --- lib/generators.nix | 16 +++++++++++++++- lib/tests.nix | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/generators.nix b/lib/generators.nix index 90dd3371454..a1396873695 100644 --- a/lib/generators.nix +++ b/lib/generators.nix @@ -10,7 +10,7 @@ let flipMapAttrs = flip libAttr.mapAttrs; in -{ +rec { /* Generates an INI-style config file from an * attrset of sections to an attrset of key-value pairs. @@ -50,4 +50,18 @@ in in # map input to ini sections mapAttrsToStringsSep "\n" mkSection attrsOfAttrs; + + + /* Generates JSON from an arbitrary (non-function) value. + * For more information see the documentation of the builtin. + */ + toJSON = {}: builtins.toJSON; + + + /* YAML has been a strict superset of JSON since 1.2, so we + * use toJSON. Before it only had a few differences referring + * to implicit typing rules, so it should work with older + * parsers as well. + */ + toYAML = {}@args: toJSON args; } diff --git a/lib/tests.nix b/lib/tests.nix index b5513dcb5ff..d59814987ed 100644 --- a/lib/tests.nix +++ b/lib/tests.nix @@ -181,4 +181,27 @@ runTests { ''; }; + /* right now only invocation check */ + testToJSONSimple = + let val = { + foobar = [ "baz" 1 2 3 ]; + }; + in { + expr = generators.toJSON {} val; + # trival implementation + expected = builtins.toJSON val; + }; + + /* right now only invocation check */ + testToYAMLSimple = + let val = { + list = [ { one = 1; } { two = 2; } ]; + all = 42; + }; + in { + expr = generators.toYAML {} val; + # trival implementation + expected = builtins.toJSON val; + }; + }