about summary refs log tree commit diff
path: root/pkgs/profpatsch/importDhall.nix
blob: 4334be3c7607b8aefccc010dfb3418c8ab71b37f (plain) (blame)
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
{ pkgs, exactSource }:
let

  # import the dhall file as nix expression via dhall-nix.
  # Converts the normalized dhall expression to a nix file,
  # puts it in the store and imports it.
  # Types are erased, functions are converted to nix functions,
  # unions values are nix functions that take a record of match
  # functions for their alternatives.
  importDhall = dhallType: file: importDhall2 {
    root = builtins.dirOf file;
    files = [];
    main = builtins.baseNameOf file;
    type = dhallType;
    deps = [];
  };

  # TODO: document
  importDhall2 = { root, files, main, deps, type }:
    let
      src =
        exactSource
          root
          # exactSource wants nix paths, but I think relative paths
          # as strings are more intuitive.
          (let abs = path: toString root + "/" + path;
           in ([ (abs main) ] ++ (map abs files)));

      cache = ".cache";
      cacheDhall = "${cache}/dhall";

      convert = pkgs.runCommandLocal "dhall-to-nix" { inherit deps; } ''
        mkdir -p ${cacheDhall}
        for dep in $deps; do
          ${pkgs.xorg.lndir}/bin/lndir -silent $dep/${cacheDhall} ${cacheDhall}
        done

        export XDG_CACHE_HOME=$(pwd)/${cache}
        # go into the source directory, so that the type can import files.
        # TODO: This is a bit of a hack hrm.
        cd "${src}"
        printf '%s' ${pkgs.lib.escapeShellArg "${src}/${main} : ${type}"} \
          | ${pkgs.dhall-nix}/bin/dhall-to-nix \
          > $out
      '';
    in import convert;


  # read dhall file in as JSON, then import as nix expression.
  # The dhall file must not try to import from non-local URLs!
  readDhallFileAsJson = dhallType: file:
    let
      convert = pkgs.runCommandLocal "dhall-to-json" {} ''
        printf '%s' ${pkgs.lib.escapeShellArg "${file} : ${dhallType}"} \
          | ${pkgs.dhall-json}/bin/dhall-to-json \
          > $out
      '';
    in builtins.fromJSON (builtins.readFile convert);

in {
  inherit
    importDhall
    importDhall2
    readDhallFileAsJson
    ;
}