This comes up a lot. For example, consider alacritty’s colorscheme configuration.
It has a colors
entry that matches the yaml config 1:1.
It would be nice if we can have config.colors = fromYaml ./colors.yaml
inside alacritty.nix
.
Currently I have to copy the yaml file, then manually change it to nix syntax when I want to experiment with stuff like this.
Probably the best you can do is turn your YAML file into a JSON with:
$ echo -e 'a:\n b: 1\n c: 2' | nix run nixpkgs#yj
{"a":{"b":1,"c":2}}
And then use builtins.readFile and builtins.fromJSON
You could also use a derivation that does the yj
step automatically (only if import-from-derivation is ok to your use case)
These days i tend to customize applications this way: nixfiles/default.nix at 2b2abcd07ede0df56360a8cda50a919a65864f8c · gytis-ivaskevicius/nixfiles · GitHub (For more examples refer to /overlays/g-*)
I just find it easier due to less clutter in module files. Also, you can nix run
it
Nix can only natively “import” TOML, JSON and Nix. As Nix lacks YAML support for this, you have three options:
- Use JSON. Since YAML is a superset of JSON, you could limit yourself to using JSON in this use case. Other applications should still be able to interpret the YAML file correctly as well.
- Use import-from-derivation to import the YAML file by converting it to JSON first. We could use
yj
for this as proposed above:let importYaml = file: builtins.fromJSON (builtins.readFile (pkgs.runCommandNoCC "converted-yaml.json" ''${pkgs.yj}/bin/yj < "${file}" > "$out"'')); in importYaml ./colors.yaml
. This has some drawbacks, mainly thatyj
needs to be available at evaluation time (so if it’s not cached you are looking at building it) and evaluation will block on the build of the converted JSON (and yj…) as evaluation is single-threaded. -
Write a YAML implementation in pure Nix.This is probably an extreme measure; Despite theoretically useful, certainly a lot of nontrivial work.
Looking at GitHub search for fromYaml
, IFD is the most common approach. I only noticed a single repo attempting to parse (a subset of) YAML using Nix.