Commit 44d97967 authored by Profpatsch's avatar Profpatsch

containers/helpers: add nix-json-trans

It’s a way to use the nix language capabilities to transform json. Essentially
like `jq`, but without introducing yet another DSL (the nixpkgs library is
reused).
One disadvantage it that it reads the json documents into memory, so no
streaming is performed. That shouldn’t matter for small-ish files, though.
parent f988fbd0
...@@ -25,6 +25,7 @@ let ...@@ -25,6 +25,7 @@ let
prependPrefix = ./helpers/prepend-prefix.nix; prependPrefix = ./helpers/prepend-prefix.nix;
debugDockerImage = ./helpers/debug-docker-image.nix; debugDockerImage = ./helpers/debug-docker-image.nix;
createStandaloneDockerImage = ./helpers/create-standalone-docker-image.nix; createStandaloneDockerImage = ./helpers/create-standalone-docker-image.nix;
nixJsonTrans = ./helpers/nix-json-trans.nix;
}; };
})]; })];
}; };
......
{ lib, pkgs, stdenv }:
{ libPath ? <nixpkgs/lib> }:
# TODO: Do we need all of lib?
let
trans = pkgs.writeScript "nix-json-trans" ''
#!${stdenv.shell}
DIR=$(mktemp -d)
cat >$DIR/script-input.nix <<EOF
with import ${libPath};
$(cat "$1")
EOF
JSON="$(realpath "$2")"
cat >$DIR/script.nix <<EOF
let
f = import $DIR/script-input.nix;
json = builtins.fromJSON (builtins.readFile $JSON);
in
assert builtins.typeOf $JSON == "path";
assert builtins.typeOf f == "lambda";
f json
EOF
source ${pkgs.setupLocalNixStore}
${pkgs.nix}/bin/nix-instantiate \
--eval --json --strict \
--show-trace \
$DIR/script.nix
'';
tests =
let
call = nixFile: jsonFile: "${trans} ${nixFile} ${jsonFile}";
eq = nixFile: jsonFile: resultFile: ''
${pkgs.diffutils}/bin/diff <(${call nixFile jsonFile}) ${resultFile}
'';
mkjson = json: pkgs.writeText "test.json" (builtins.toJSON json);
in {
idJson =
let
json = mkjson {
foo = [ 1 2 3 null "bar" ];
};
idScr = pkgs.writeText "id-converter" "id";
in eq idScr json json;
replaceAttrsJson =
eq (pkgs.writeText "maybe-its-neuer"
''mapAttrs (_: _: "manuel neuer")'')
(mkjson { foo = "richard stallman"; bar = "linus torvalds"; })
(mkjson { foo = "manuel neuer"; bar = "manuel neuer"; });
};
in pkgs.withTests tests trans
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment