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 Jan 8, 2025
1 parent c817d7f commit a353c23
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
14 changes: 14 additions & 0 deletions nixos/doc/manual/development/settings-options.section.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,20 @@ have a predefined type and string generator already declared under
and returning a set with TOML-specific attributes `type` and
`generate` as specified [below](#pkgs-formats-result).

`pkgs.formats.xml` { format ? "badgerfish", withHeader ? true}

: A function taking an attribute set with values
and returning a set with XML-specific attributes `type` and
`generate` as specified [below](#pkgs-formats-result).

`format`

: Input format. Because XML can not be translated one-to-one, we have to use intermediate formats. Possible values `["badgerfish"]`.

`withHeader`

: Outputs the xml with header.

`pkgs.formats.elixirConf { elixir ? pkgs.elixir }`

: A function taking an attribute set with values
Expand Down
47 changes: 47 additions & 0 deletions pkgs/pkgs-lib/formats.nix
Original file line number Diff line number Diff line change
Expand Up @@ -504,4 +504,51 @@ rec {
'') {};
};

xml =
{
format ? "badgerfish",
withHeader ? true,
}:
if format == "badgerfish" then
rec {
type = mkStructuredType { typeName = "XML"; };
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}";

}
27 changes: 27 additions & 0 deletions pkgs/pkgs-lib/tests/formats.nix
Original file line number Diff line number Diff line change
Expand Up @@ -469,4 +469,31 @@ 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.";
};
nulltest = null;
};
};
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>
<nulltest></nulltest>
</root>
'';
};
}

0 comments on commit a353c23

Please sign in to comment.