summaryrefslogtreecommitdiffstats
path: root/lib/xml.nix
blob: 16052445b3e565b354d593ad54f5f6d95eedd154 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
{ lib }:
with lib;
with builtins;
rec {

  # Use `term` to construct XML.
  #
  # Examples:
  #
  #   (term "bool" null null)
  #   (term "cool" null [])
  #   (term "fool" { hurr = "durr"; } null)
  #   (term "hool" null [
  #     (term "tool" null null)
  #   ])
  #
  # See `render` for how these get transformed into actuall XML documents.
  #
  term = name: attrs: content: {
    inherit name attrs content;
  };

  empty = term null null null;

  # Ref http://www.w3.org/TR/xml/#syntax
  #
  # Example:
  #
  #   (quote "<cheez!>")                 #===>   &lt;cheez!&gt;
  #
  quote = let
    sub = {
      "&" = "&amp;";
      "<" = "&lt;";
      ">" = "&gt;";
      "'" = "&apos;";
      "\"" = "&quot;";
    };
  in
    stringAsChars (c: sub.${c} or c);

  # Turn an XML element to an XML document string.
  doc = t:
    "<?xml version='1.0' encoding='UTF-8'?>${render t}";

  # Render an XML element to a string.
  #
  # Rendering `empty` yields the empty string.
  #
  # Examples:
  #
  #   (term "bool" null null)                 #===>   <bool/>
  #   (term "cool" null [])                   #===>   <cool></cool>
  #   (term "fool" { hurr = "durr"; } null)   #===>   <fool hurr="durr"/>
  #   (term "hool" null [
  #     (term "tool" null null)
  #   ])                                      #===>   <hool><tool/></hool>
  #
  render = let
    render-attrs = attrs:
      getAttr (typeOf attrs) {
        null = "";
        set = concatStrings (mapAttrsToList (n: v: " ${n}=\"${v}\"") attrs);
      };

    render-content = content:
      getAttr (typeOf content) {
        bool = toJSON content;
        int = toJSON content;
        list = concatMapStrings render content;
        string = quote content;
      };
  in
    { name, attrs, content }:
    # XXX we're currently encoding too much information with `null`..
    if name == null
      then
        if content == null
          then ""
          else content
      else let
        attrs' = render-attrs attrs;
        content' = render-content content;
      in
        if content == null
          then "<${name}${attrs'}/>"
          else "<${name}${attrs'}>${content'}</${name}>";
}