diff --git a/pkgs/pkgs-lib/formats.nix b/pkgs/pkgs-lib/formats.nix index c99144d9351903..8f01b70d4301a0 100644 --- a/pkgs/pkgs-lib/formats.nix +++ b/pkgs/pkgs-lib/formats.nix @@ -517,4 +517,98 @@ rec { '') {}; }; + badgerfishToXml = {}: json {} // { + type = let + valueType = oneOf [ + bool + int + float + str + path + (attrsOf valueType) + (listOf valueType) + ] // { + description = "XML value"; + }; + in valueType; + + generate = name: value: pkgs.callPackage ({ runCommand, python3, libxml2Python }: runCommand name { + nativeBuildInputs = [ python3 python3.pkgs.xmltodict libxml2Python]; + value = builtins.toJSON value; + pythonGen = '' + import json + import os + import xmltodict + + with open(os.environ["valuePath"], "r") as f: + print(xmltodict.unparse(json.load(f), pretty=True, indent=" " * 2)) + ''; + passAsFile = [ "value" "pythonGen" ]; + preferLocalBuild = true; + } '' + python3 "$pythonGenPath" > $out + xmllint $out > /dev/null + '') {}; + }; + + xml = + { + format ? "badgerfish", + withHeader ? true, + }: + if format == "badgerfish" then + rec { + type = + oneOf [ + bool + int + float + str + path + (attrsOf type) + (listOf type) + ] + // { + description = "XML value"; + }; + + generate = + name: value: + pkgs.callPackage ( + { + runCommand, + python3, + libxml2Python, + }: + runCommand name + { + nativeBuildInputs = [ + python3 + python3.pkgs.xmltodict + libxml2Python + ]; + value = builtins.toJSON value; + pythonGen = '' + import json + import os + import xmltodict + + with open(os.environ["valuePath"], "r") as f: + print(xmltodict.unparse(json.load(f), full_document=${toString withHeader}, pretty=True, indent=" " * 2)) + ''; + passAsFile = [ + "value" + "pythonGen" + ]; + preferLocalBuild = true; + } + '' + python3 "$pythonGenPath" > $out + xmllint $out > /dev/null + '' + ) { }; + } + else + throw "Unknown format: ${format}"; + } diff --git a/pkgs/pkgs-lib/tests/formats.nix b/pkgs/pkgs-lib/tests/formats.nix index 86a35c6bf26dc3..1b445a1b76866a 100644 --- a/pkgs/pkgs-lib/tests/formats.nix +++ b/pkgs/pkgs-lib/tests/formats.nix @@ -469,4 +469,29 @@ in runBuildTests { ''; }; + badgerfishToXmlGenerate = shouldPass { + format = formats.xml { }; + input = { + root = { + "@id" = "123"; + "@class" = "example"; + child1 = { + "@name" = "child1Name"; + "#text" = "text node"; + }; + child2 = { + grandchild = "This is a grandchild text node."; + }; + }; + }; + expected = '' + + + text node + + This is a grandchild text node. + + + ''; + }; }