Flake - Read file from another derivation is impure

In order to build a nixos configuration like this with flake I need to use --impure because I am reading a file from this overlay built: pkgs.lab.blackhole.

{ config, pkgs, lib, modulesPath, ... }: with lib; {
  imports = [
    (modulesPath + "/installer/scan/not-detected.nix")
  ];

  services.pixiecore.cmdLine = lib.readFile "${pkgs.lab.blackhole}/init";;

  system.stateVersion = "22.05";
}

I am wondering how I can make it pure.

Whatever operation you are performing there will need to be done before you build, and provided as an argument. So in this case a path to init in your git tree.

If it must be dynamic you can implement whatever operation you’re performing in that derivation using pure Nix expressions. E.g. builtins + lib functions. This is less painful than it sounds in many cases, particularly if you have JSON input or files that are easily parsed such as CSV.

What does your derivation do?
If the file is available in the original source then builtins.readFile "${builtins.fetchTree { type = "tarball"; url = ...; narHash = <SHA-256-SRI>; }}/init" is pure.
You might even be able to yank the url and hash from pkg.foo.src.* fields.

IFD is good to avoid, but it shouldn’t require --impure, regardless… there must be another reason you need it.

How is the overlay defined?

I managed to create an easy to reproduce example

I hope it will help

1 Like

Looks like a bug in nix. It’s not tracking the available paths properly. It works with --impure because it just treats it as an absolute filesystem path rather than the result of a derivation.

By contrast, this works fine, despite being basically the same thing:

nix eval --expr 'let pkgs = import (builtins.getFlake "github:nixos/nixpkgs/34c5293a71ffdb2fe054eb5288adc1882c1eb0b1") {}; in builtins.readFile "${pkgs.writeScriptBin "foo" "bar"}/bin/foo"'

Not sure precisely where the bug comes in.

1 Like

Great! I have to admit that I was not fully understanding why impure was a requirement.

I will open an issue!

Thanks

Could you add the link here once it is done?

@tobiasBora

1 Like