Nix tricks: path: flakes [nix/trick-path-flake]

Nix flakes must be copied into the store before being evaluated. And for a git repository, even if the flake is referred to with a path (.# and alike), all (and only) the indexed files (files that are git added and committed) are copied.

This is quite annoying while working on other people’s project. I use dev flakes to provide personal dev environments, I don’t want to copy the whole project into my nix store frequently, and nor do I want to add the files to be accidentally committed.

There’s a solution for this: it’s possible to force a flake to work in “plain directory mode” that only copies the directory containing it, by prefixing path: before the flake path when referring to it.

For example, if I want to set up a dev shell with nix-direnv, I can use this as my .envrc:

use flake path:./.flake

or with an absolute path:

use flake path:$(pwd)/.flake

Then, with a file structure like

- <project root>/
  - .envrc
  - .flake/
    - flake.nix
    - flake.lock

I can now have a flake that doesn’t copy extra files to the store and doesn’t need to be added to git index.

Note that you may need to manually call nix lock to create a lock file for this kind of flake, because nix refuses to do that with a relative path, and has problem dealing with unicode in absolute paths.