How to get "name" field out of nix expression?

907 Views Asked by At

Given following default.nix,

{ stdenv, fetchurl, perl }:

stdenv.mkDerivation {
  name = "hello-2.1.1";
  builder = ./builder.sh;
  src = fetchurl {
    url = ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz;
    md5 = "70c9ccf9fac07f762c24f2df2290784d";
  };
  inherit perl;
}

How can I get the value hello-2.1.1 from name field using nix-instantiate ?

$ nix-instantiate --eval -E 'name' default.nix 
error: undefined variable ‘name’ at (string):1:1
1

There are 1 best solutions below

2
On BEST ANSWER

What your nix-instantiate invocation is doing, is trying to retrieve name from a mostly empty scope. What's missing here is a piece of functionality that is implemented in NixPkgs provides the arguments to your function in default.nix.

Let's get the callPackage function from your current <nixpkgs>:

(import <nixpkgs> {}).callPackage

callPackage requires two arguments, a function that defines the package and an attribute set of overrides. Instead of providing the function directly, you can provide a file reference instead.

(import <nixpkgs> {}).callPackage ./. {}

Now let's get the name

((import <nixpkgs> {}).callPackage ./. {}).name

And run it

$ nix-instantiate --eval -E '((import <nixpkgs> {}).callPackage ./. {}).name'
"hello-2.1.1"

To experiment with Nix, I prefer to use nix-repl though. It is easier to use and has tab completion.

$ nix-env -iA nixpkgs.nix-repl
$ nix-repl
nix-repl> ((import <nixpkgs> {}).callPackage ./. {}).name
"hello-2.1.1"