From 57cad0cd859177a246390c3f77d1891bc3d2f788 Mon Sep 17 00:00:00 2001 From: niten Date: Tue, 21 Jun 2022 11:56:49 -0700 Subject: [PATCH] Initial commit --- flake.nix | 13 +++++++++++++ to-formatted-xml.nix | 5 +++++ to-xml-file.nix | 10 ++++++++++ to-xml.nix | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 flake.nix create mode 100644 to-formatted-xml.nix create mode 100644 to-xml-file.nix create mode 100644 to-xml.nix diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..a6f2037 --- /dev/null +++ b/flake.nix @@ -0,0 +1,13 @@ +{ + description = "Nix-to-XML converter."; + + inputs = { + nixpkgs.url = "nixpkgs/nixos-22.05"; + utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, utils }: { + lib.toXML = import ./to-xml.nix { inherit (nixpkgs) lib; }; + overlay = final: prev: { lib = prev.lib // { toXML = self.lib.toXML; }; }; + }; +} diff --git a/to-formatted-xml.nix b/to-formatted-xml.nix new file mode 100644 index 0000000..ebabc54 --- /dev/null +++ b/to-formatted-xml.nix @@ -0,0 +1,5 @@ +{ lib, toXMLFile, ... }: + +content: +let xmlFile = toXMLFile "formatted-xml" content; +in lib.readFile xmlFile diff --git a/to-xml-file.nix b/to-xml-file.nix new file mode 100644 index 0000000..f513901 --- /dev/null +++ b/to-xml-file.nix @@ -0,0 +1,10 @@ +{ lib, pkgs, toXML, ... }: + +name: content: +let preformatXML = pkgs.writeText "${name}-preformat.xml" (toXML content); +in pkgs.stdenv.mkDerivation { + name = "${name}.xml"; + phases = [ "installPhase" ]; + buildInputs = with pkgs; [ xmlformat ]; + installPhase = "xmlformat ${preformatXML} > $out"; +} diff --git a/to-xml.nix b/to-xml.nix new file mode 100644 index 0000000..eb3fa46 --- /dev/null +++ b/to-xml.nix @@ -0,0 +1,33 @@ +{ config, lib, pkgs, ... }: + +with lib; +let + isEmpty = lst: (length lst) == 0; + isEmptyAttrs = attrs: (length (attrNames attrs)) == 0; + renderAttr = name: value: ''${name}="${value}"''; + renderAttrs = attrs: + if (isEmptyAttrs attrs) then + "" + else + " " + concatStringsSep " " (mapAttrsToList renderAttr attrs); + renderTag = tag: attrs: body: "<${tag}${renderAttrs attrs}>${body}"; + # renderLoneTag = tag: attrs: "<${tag}${renderAttrs attrs} />"; + toXML = { tag, attrs ? { }, children ? [ ] }: + let + renderElement = el: if isString el then el else toXML el; + body = concatStringsSep "" (map renderElement children); + in renderTag tag attrs body; + + toXMLFile = name: content: + let preformatXML = pkgs.writeText "${name}-preformat.xml" (toXML content); + in pkgs.stdenv.mkDerivation { + name = "${name}.xml"; + phases = [ "installPhase" ]; + buildInputs = with pkgs; [ xmlformat ]; + installPhase = "xmlformat ${preformatXML} > $out"; + }; + + toFormattedXML = content: + let xmlFile = toXMLFile "formatted-xml" content; + in readFile xmlFile; +in { inherit toXML toXMLFile toFormattedXML; }