Isolated temporary files in Nix derivation

Viewed 565

I haven't found any info about handling temporary files in Nix derivations.

I found $TMP and $TMPDIR env vars, but they both point just to /tmp, which is system global.

{
  pkgs ? import <nixpkgs> {}
}:
  pkgs.stdenv.mkDerivation {
    pname = "show-tmp"
    version = "0.1.0";
    src = ./.;
    configurePhase = ''
      echo "tmp = $tmp; TMP =  $TMP; TMPDIR = $TMPDIR"
    '';
    buildPhase = '':'';
    installPhase = '':'';        
  }

Variable $tmp is not defined inside mkDerivation. I would expect such thing, because other derivation scope vars follow low case style such as $out.

The problem with /tmp is obvious - it is global directory. I need to worry about collisions and cleaning.

My derivation-hook archives a big folder tree.

1 Answers

If you're on Linux, don't worry. The Nix sandbox will give your build its own empty /tmp. It is removed when your derivation is done.

On macOS, $TMP and $TMPDIR are taken care of but /tmp is a potential problem.

Linux: https://github.com/NixOS/nix/blob/340f831ebe9d74659b84667b96251b7ab0edd09d/src/libstore/build/local-derivation-goal.cc#L609-L614

Darwin:

nix-build --expr 'with import <nixpkgs> {}; runCommand "hi" {} "echo a > /tmp/a; ls -al /tmp; sleep 1;"'
ls -al /private/tmp/
...
-rw-r--r--  1 nixbld1  wheel    2 May 19 12:49 a
...

This was on a macOS machine where I installed Nix in early 2020.

Related