Skip to content

Commit

Permalink
pkgs-lib.formats.xml: init
Browse files Browse the repository at this point in the history
  • Loading branch information
Stunkymonkey committed Oct 1, 2024
1 parent bff640b commit 84aa26c
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 0 deletions.
94 changes: 94 additions & 0 deletions pkgs/pkgs-lib/formats.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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}";

}
25 changes: 25 additions & 0 deletions pkgs/pkgs-lib/tests/formats.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ''
<?xml version="1.0" encoding="utf-8"?>
<root class="example" id="123">
<child1 name="child1Name">text node</child1>
<child2>
<grandchild>This is a grandchild text node.</grandchild>
</child2>
</root>
'';
};
}

0 comments on commit 84aa26c

Please sign in to comment.