How to fetch Nixpkgs with an empty NIX PATH

From NixOS Wiki
Revision as of 16:34, 16 August 2018 by Gabriel439 (talk | contribs) (Remove `sha256` argument to `fetchNixpkgs` in favor of making `outputSha256` required. Reasons: (A) Nix 2.0 doesn't require `sha256`, (B) `outputSha256` subsumes `sha256`, (C) not required (<nix/fetchurl.nix> accepts `sha256 = null`))
Jump to: navigation, search

This recipe provides a way to fetch Nixpkgs with an empty NIX_PATH. This comes in handy if you want to remove impure references to the NIX_PATH from your code base

Save the following code to a fetchNixpkgs.nix file within your project:

{ rev                             # The Git revision of nixpkgs to fetch
, outputSha256                    # The SHA256 fixed-output hash
, system ? builtins.currentSystem # This is overridable if necessary
}:

if (0 <= builtins.compareVersions builtins.nixVersion "1.12")

# In Nix 1.12, we can just give a `sha256` to `builtins.fetchTarball`.
then (
  builtins.fetchTarball {
    url = "https://github.com/NixOS/nixpkgs/archive/${rev}.tar.gz";
    sha256 = outputSha256;
  })

# This hack should at least work for Nix 1.11
else (
  (rec {
    tarball = import <nix/fetchurl.nix> {
      url    = "https://github.com/NixOS/nixpkgs/archive/${rev}.tar.gz";
      sha256 = null;
    };

    builtin-paths = import <nix/config.nix>;
      
    script = builtins.toFile "nixpkgs-unpacker" ''
      "$coreutils/mkdir" "$out"
      cd "$out"
      "$gzip" --decompress < "$tarball" | "$tar" -x --strip-components=1
    '';

    nixpkgs = builtins.derivation ({
      name = "nixpkgs-${builtins.substring 0 6 rev}";

      builder = builtins.storePath builtin-paths.shell;

      args = [ script ];

      inherit tarball system;

      tar       = builtins.storePath builtin-paths.tar;
      gzip      = builtins.storePath builtin-paths.gzip;
      coreutils = builtins.storePath builtin-paths.coreutils;
    } // (if null == outputSha256 then { } else {
      outputHashMode = "recursive";
      outputHashAlgo = "sha256";
      outputHash = outputSha256;
    }));
  }).nixpkgs)

... and then you can use the saved file to fetch Nixpkgs like this:

let
  fetchNixpkgs = import ./fetchNixpkgs.nix;

  nixpkgs = fetchNixpkgs {
     rev          = "3389f23412877913b9d22a58dfb241684653d7e9";
     outputSha256 = "0wgm7sk9fca38a50hrsqwz6q79z35gqgb9nw80xz7pfdr4jy9pf8";
  };

  pkgs = import nixpkgs { config = {}; };
in
  ...