Profpatsch/third_party/overlays/sam/pkgs/pkgs-lib/formats/preserves.nix
 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
# Format Preserves data into files using text or binary syntax.
# https://preserves.dev/

{ lib
, preserves-tools
, writeTextFile
}:

{ ... }@args:
let
  toPreserves = lib.generators.toPreserves args;
  literal =
    with lib.types;
    nullOr
      (oneOf [
        bool
        int
        float
        str
        (attrsOf literal)
        (listOf literal)
      ])
    // {
      description = "Preserves value";
    };
  convert =
    syntax: name: value:
    writeTextFile {
      name =
        let
          ext =
            {
              binary = ".prb";
              text = ".pr";
            }.${syntax};
        in
        if lib.hasSuffix ext name then name else "${name}${ext}";
      text = toString (map toPreserves value);
      checkPhase = ''
        ${lib.getExe preserves-tools} convert \
          --output-format ${syntax} \
          <$target >tmp.pr && mv tmp.pr $target
      '';
      passthru = {
        inherit value;
      }
      // {
        # For each syntax the alternative
        # is available in passthru.
        binary.text = convert "text" name value;
        text.binary = convert "binary" name value;
      }.${syntax};
    };
in
{
  inherit literal;
  type = lib.types.listOf literal;

  generate = convert "text";

  # Hack to make Preserves records with < >.
  __findFile =
    _: _record: fields:
    fields ++ [{ inherit _record; }];
}