Temporary Writable Directory for Builds

Some package builds need a temporary writable directory, be it because $HOME must be accessible, it relies on some caching or any other reason.

I went looking around on the nixpkgs repo and found at least three different solutions:

  1. mktempe. g., r2modman
  2. $TMPDIRe. g., build-support/go/module.nix
  3. $NIX_BUILD_TOPe. g., hare

Would there be a correct solution?

Regarding the ones above, I’ve managed to found at least an issue in regards to $NIX_BUILD_TOP:

However, its stated harmfulness is related to the use of nix-shell, not the build process.

mktemp -d is definitely the way to go! Most notably mktemp -d ensures that it’s a fresh directory. So you don’t have to worry about the path potentially being polluted already.

Does Nix do anything to ensure that mktemp -d directories are cleaned up after a build? Or are package authors responsible for putting a trap 'rm -rf $whatever' EXIT in the relevant phase script?

Only the build directory ($NIX_BUILD_TOP, also the same as $TMPDIR) is writable by the build, and it’s definitely being cleaned up after the build :slight_smile:

1 Like

nix-shell doesn’t have any clean-up phase like nix-build, so I think it’s best if temporary directories are created inside the build directory/current working directory and/or using trap 'rm -rf...' EXIT.

Thanks for the clarification!, @Infinisil.

Do nix-shell and nix-build have the same value for TMPDIR? Because if nix-shell sets it to a tmpfs partition — e. g., /run —, the created directory would be cleaned up after a reboot and, thus, there would be no need for the trap call.