How to fetch Nixpkgs with an empty NIX PATH

From NixOS Wiki
Revision as of 16:49, 3 November 2017 by imported>Gabriel439 (Created page with " <syntaxhighlight lang="nix"> # This file provides a way to fetch `nixpkgs` with an empty `NIX_PATH`. This # comes in handy if you want to remove impure references to the `NI...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
# This file 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
#
# To use this code, save this to a `fetchNixpkgs.nix` file within your project
# and then referencing this file like so:
#
# ```nix
# let
#   fetchNixpkgs = import ./fetchNixpkgs.nix;
#
#   nixpkgs = fetchNixpkgs {
#      rev = "76d649b59484607901f0c1b8f737d8376a904019";
#
#      sha256 = "01c2f4mj4ahir0sxk9kxbymg2pki1pc9a3y6r9x6ridry75fzb8h";
#   };
#
#   pkgs = import nixpkgs { config = {}; };
#
# in
#   ...
# ```

{ rev, sha256 }:

if 0 <= builtins.compareVersions builtins.nixVersion "1.12"
then

builtins.fetchTarball {
  url = "https://github.com/NixOS/nixpkgs/archive/${rev}.tar.gz";

  inherit sha256;
}

else

# `builtins.fetchTarball` only accepts a `sha256` argument in Nix version 1.12 or later
with rec {
  system = builtins.currentSystem;

  tarball = import <nix/fetchurl.nix> {
    url = "https://github.com/NixOS/nixpkgs/archive/${rev}.tar.gz";

    inherit sha256;
  };

  builtin-paths = import <nix/config.nix>;

  script = builtins.toFile "nixpkgs-unpacker" ''
    "$coreutils/mkdir" "$out"
    cd "$out"
    "$gzip" --decompress < "$tarball" | "$tar" --extract --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;
  };
};

nixpkgs