Writing Nix ExpressionsThis chapter shows you how to write Nix expressions, which are
the things that tell Nix how to build components. It starts with a
simple example (a Nix expression for GNU Hello), and then moves
on to a more in-depth look at the Nix expression language.A simple Nix expressionThis section shows how to add and test the GNU Hello
package to the Nix Packages collection. Hello is a program
that prints out the text Hello, world!.To add a component to the Nix Packages collection, you generally
need to do three things:
Write a Nix expression for the component. This is a
file that describes all the inputs involved in building the
component, such as dependencies (other components required by the
component), sources, and so on.Write a builder. This is a
shell scriptIn fact, it can be written in any
language, but typically it's a bash shell
script. that actually builds the component from
the inputs.Add the component to the file
pkgs/system/all-packages-generic.nix. The Nix
expression written in the first step is a
function; it requires other components in order
to build it. In this step you put it all together, i.e., you call
the function with the right arguments to build the actual
component.The Nix expressionNix expression for GNU Hello
(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;
} shows a Nix expression for GNU
Hello. It's actually already in the Nix Packages collection in
pkgs/applications/misc/hello/ex-1/default.nix.
It is customary to place each package in a separate directory and call
the single Nix expression in that directory
default.nix. The file has the following elements
(referenced from the figure by number):
This states that the expression is a
function that expects to be called with three
arguments: stdenv, fetchurl,
and perl. They are needed to build Hello, but
we don't know how to build them here; that's why they are function
arguments. stdenv is a component that is used
by almost all Nix Packages components; it provides a
standard environment consisting of the things you
would expect in a basic Unix environment: a C/C++ compiler (GCC,
to be precise), the Bash shell, fundamental Unix tools such as
cp, grep,
tar, etc. (See
pkgs/stdenv/nix/path.nix to see what's in
stdenv.) fetchurl is a
function that downloads files. perl is the
Perl interpreter.Nix functions generally have the form {x, y, ...,
z}: e where x, y,
etc. are the names of the expected arguments, and where
e is the body of the function. So
here, the entire remainder of the file is the body of the
function; when given the required arguments, the body should
describe how to build an instance of the Hello component.So we have to build a component. Building something from
other stuff is called a derivation in Nix (as
opposed to sources, which are built by humans instead of
computers). We perform a derivation by calling
stdenv.mkDerivation.
mkDerivation is a function provided by
stdenv that builds a component from a set of
attributes. An attribute set is just a list
of key/value pairs where the value is an arbitrary Nix expression.
They take the general form
{name1 =
expr1; ...name1 =
expr1;.The attribute name specifies the symbolic
name and version of the component. Nix doesn't really care about
these things, but they are used by for instance nix-env
-q to show a human-readable name for
components. This attribute is required by
mkDerivation.The attribute builder specifies the
builder. This attribute can sometimes be omitted, in which case
mkDerivation will fill in a default builder
(which does a configure; make; make install, in
essence). Hello is sufficiently simple that the default builder
would suffice, but in this case, we will show an actual builder
for educational purposes. The value
./builder.sh refers to the shell script shown
in , discussed below.The builder has to know what the sources of the component
are. Here, the attribute src is bound to the
result of a call to the fetchurl function.
Given a URL and a MD5 hash of the expected contents of the file at
that URL, this function actually builds a derivation that
downloads the file and checks its hash. So the sources are a
dependency that like all other dependencies is built before Hello
itself is built.Instead of src any other name could have
been used, and in fact there can be any number of sources (bound
to different attributes). However, src is
customary, and it's also expected by the default builder (which we
don't use in this example).Since the derivation requires Perl, we have to pass the
value of the perl function argument to the
builder. All attributes in the set are actually passed as
environment variables to the builder, so declaring an attribute
perl = perl;
will do the trink: it binds an attribute perl
to the function argument which also happens to be called
perl. However, it looks a bit silly, so there
is a shorter syntax. The inherit keyword
causes the specified attributes to be bound to whatever variables
with the same name happen to be in scope.The builderBuild script for GNU Hello
(builder.sh)
. $stdenv/setup
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install shows the builder referenced
from Hello's Nix expression (stored in
pkgs/applications/misc/hello/ex-1/builder.sh).
The builder can actually be made a lot shorter by using the
generic builder functions provided by
stdenv, but here we write out the build steps to
elucidate what a builder does. It performs the following
steps:When Nix runs a builder, it initially completely clears the
environment. For instance, the PATH variable is
emptyActually, it's initialised to
/path-not-set to prevent Bash from setting it
to a default value.. This is done to prevent
undeclared inputs from being used in the build process. If for
example the PATH contained
/usr/bin, then you might accidentally use
/usr/bin/gcc.So the first step is to set up the environment. This is
done by calling the setup script of the
standard environment. The environment variable
stdenv points to the location of the standard
environment being used. (It wasn't specified explicitly as an
attribute in , but
mkDerivation adds it automatically.)Since Hello needs Perl, we have to make sure that Perl is in
the PATH. The perl environment
variable points to the location of the Perl component (since it
was passed in as an attribute to the derivation), so
$perl/bin is the
directory containing the Perl interpreter.Now we have to unpack the sources. The
src attribute was bound to the result of
fetching the Hello source tarball from the network, so the
src environment variable points to the location in
the Nix store to which the tarball was downloaded. After
unpacking, we cd to the resulting source
directory.The whole build is performed in a temporary directory
created in /tmp, by the way. This directory is
removed after the builder finishes, so there is no need to clean
up the sources afterwards. Also, the temporary directory is
always newly created, so you don't have to worry about files from
previous builds interfering with the current build.GNU Hello is a typical Autoconf-based package, so we first
have to run its configure script. In Nix
every component is stored in a separate location in the Nix store,
for instance
/nix/store/9a54ba97fb71b65fda531012d0443ce2-hello-2.1.1.
Nix computes this path by cryptographically hashing all attributes
of the derivation. The path is passed to the builder through the
out environment variable. So here we give
configure the parameter
--prefix=$out to cause Hello to be installed in
the expected location.Finally we build Hello (make) and install
it into the location specified by out
(make install).If you are wondering about the absence of error checking on the
result of various commands called in the builder: this is because the
shell script is evaluated with Bash's option,
which causes the script to be aborted if any command fails without an
error check.CompositionComposing GNU Hello
(all-packages-generic.nix)
...
rec {
hello = (import ../applications/misc/hello/ex-1 ) {
inherit fetchurl stdenv perl;
};
perl = (import ../development/interpreters/perl) {
inherit fetchurl stdenv;
};
fetchurl = (import ../build-support/fetchurl) {
inherit stdenv; ...
};
stdenv = ...;
}
The Nix expression in is a
function; it is missing some arguments that have to be filled in
somewhere. In the Nix Packages collection this is done in the file
pkgs/system/all-packages-generic.nix, where all
Nix expressions for components are imported and called with the
appropriate arguments. shows
some fragments of
all-packages-generic.nix.This file defines a set of attributes, all of which are
concrete derivations (i.e., not functions). In fact, we define a
mutually recursive set of attributes. That
is, the attributes can refer to each other. This is precisely
what we want since we want to plug the
various components into each other.Here we import the Nix expression for
GNU Hello. The import operation just loads and returns the
specified Nix expression. In fact, we could just have put the
contents of in
all-packages-generic.nix at this point. That
would be completely equivalent, but it would make the file rather
bulky.Note that we refer to
../applications/misc/hello/ex-1, not
../applications/misc/hello/ex-1/default.nix.
When you try to import a directory, Nix automatically appends
/default.nix to the file name.This is where the actual composition takes place. Here we
call the function imported from
../applications/misc/hello/ex-1 with an
attribute set containing the things that the function expects,
namely fetchurl, stdenv, and
perl. We use inherit again to use the
attributes defined in the surrounding scope (we could also have
written fetchurl = fetchurl;, etc.).The result of this function call is an actual derivation
that can be built by Nix (since when we fill in the arguments of
the function, what we get is its body, which is the call to
stdenv.mkDerivation in ).Likewise, we have to instantiate Perl,
fetchurl, and the standard environment.TestingYou can now try to build Hello. The simplest way to do that is
by using nix-env:
$ nix-env -f pkgs/system/i686-linux.nix -i hello
installing `hello-2.1.1'
building path `/nix/store/632d2b22514dcebe704887c3da15448d-hello-2.1.1'
hello-2.1.1/
hello-2.1.1/intl/
hello-2.1.1/intl/ChangeLog
...
This will build Hello and install it into your profile. The file
i686-linux is just a simple Nix expression that
imports all-packages-generic.nix and instantiates
it for Linux on the x86 platform.Note that the hello argument here refers to
the symbolic name given to the Hello derivation (the
name attribute in ),
not the hello attribute in
all-packages-generic.nix.
nix-env simply walks through all derivations
defined in the latter file, looking for one with a
name attribute matching the command-line
argument.You can test whether it works:
$ hello
Hello, world!Generally, however, using nix-env is not the
best way to test components, since you may not want to install them
into your profile right away (they might not work properly, after
all). A better way is to write a short file containging the
following:
(import pkgs/system/i686-linux.nix).hello
Call it test.nix. You can then build it without
installing it using the command nix-build:
$ nix-build ./test.nix
...
/nix/store/632d2b22514dcebe704887c3da15448d-hello-2.1.1nix-build will build the derivation and print the
output path. It also creates a symlink to the output path called
result in the current directory. This is
convenient for testing the component:
$ ./result/bin/hello
Hello, world!Nix has a transactional semantics. Once a build finishes
succesfully, Nix makes a note of this in its database: it registers
that the path denoted by out is now
valid. If you try to build the derivation again, Nix
will see that the path is already valid and finish immediately. If a
build fails, either because it returns a non-zero exit code, because
Nix or the builder are killed, or because the machine crashes, then
the output path will not be registered as valid. If you try to build
the derivation again, Nix will remove the output path if it exists
(e.g., because the builder died half-way through make
install) and try again. Note that there is no
negative caching: Nix doesn't remember that a build
failed, and so a failed build can always be repeated. This is because
Nix cannot distinguish between permanent failures (e.g., a compiler
error due to a syntax error in the source) and transient failures
(e.g., a disk full condition).Nix also performs locking. If you run multiple Nix builds
simultaneously, and they try to build the same derivation, the first
Nix instance that gets there will perform the build, while the others
block (or perform other derivations if available) until the build
finishes. So it is always safe to run multiple instances of Nix in
parallel (contrary to, say, make).If you have a system with multiple CPUs, you may want to have
Nix build different derivations in parallel (insofar as possible).
Just pass the option ,
where N is the maximum number of jobs to be
run in parallel. Typically this should be the number of CPUs.The generic builderRecall from that the builder
looked something like this:
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
The builders for almost all Unix packages look like this — set up some
environment variables, unpack the sources, configure, build, and
install. For this reason the standard environment provides some Bash
functions that automate the build process. A builder using the
generic build facilities in shown in .Build script using the generic
build functions
buildInputs="$perl"
. $stdenv/setup
genericBuild The buildInputs variable tells
setup to use the indicated components as
inputs. This means that if a component provides a
bin subdirectory, it's added to
PATH; if it has a include
subdirectory, it's added to GCC's header search path; and so
on.The function genericBuild is defined in
the file $stdenv/setup.The final step calls the shell function
genericBuild, which performs the steps that
were done explicitly in . The
generic builder is smart enough to figure out whether to unpack
the sources using gzip,
bzip2, etc. It can be customised in many ways;
see .Discerning readers will note that the
buildInputs could just as well have been set in the Nix
expression, like this:
buildInputs = [perl];
The perl attribute can then be removed, and the
builder becomes even shorter:
. $stdenv/setup
genericBuilder>
In fact, mkDerivation provides a default builder
that looks exactly like that, so it is actually possible to omit the
builder for Hello entirely.The Nix expression languageThe Nix expression language is a pure, lazy, functional
language. Purity means that operations in the language don't have
side-effects (for instance, there is no variable assignment).
Laziness means that arguments to functions are evaluated only when
they are needed. Functional means that functions are
normal values that can be passed around and
manipulated in interesting ways.The language is not a full-featured, general purpose language.
It's main job is to describe components, compositions of components,
and the variability within components. For this a functional language
is perfectly suited.This section presents the various features of the
language.Simple valuesNix has the following basic datatypes:
Strings, enclosed between
double quotes, e.g., "foo bar".Integers, e.g.,
123.URIs as defined in appendix B
of RFC
2396, e.g.,
https://svn.cs.uu.nl:12443/dist/trace/trace-nix-trunk.tar.bz2.Paths, e.g.,
/bin/sh or ./builder.sh.
A path must contain at least one slash to be recognised as such; for
instance, builder.sh is not a
pathIt's parsed as an expression that selects the
attribute sh from the variable
builder.. If the filename is
relative, i.e., if it does not begin with a slash, it is made
absolute at parse time relative to the directory of the Nix
expression that contained it. For instance, if a Nix expression in
/foo/bar/bla.nix refers to
../xyzzy/fnord.nix, the absolutised path is
/foo/xyzzy/fnord.nix.ListsLists are formed by enclosing a whitespace-separated list of
values between square bracktes. For example,
[ 123 ./foo.nix "abc" (f {x=y;}) ]
defines a list of four elements, the last being the result of a call
to the function f. Note that function calls have
to be enclosed in parentheses. If they had been omitted, e.g.,
[ 123 ./foo.nix "abc" f {x=y;} ]
the result would be a list of five elements, the fourth one being a
function and the fifth being an attribute set.Attribute setsAttribute sets are really the core of the language, since
ultimately it's all about creating derivations, which are really just
sets of attributes to be passed to build scripts.Attribute sets are just a list of name/value pairs enclosed in
curly brackets, where each value is an arbitrary expression terminated
by a semicolon. For example:
{ x = 123;
text = "Hello";
y = f { bla = 456; };
}
This defines an attribute set with attributes named
x, test, y.
The order of the attributes is irrelevant. An attribute name may only
occur once.Attributes can be selected from an attribute set using the
. operator. For instance,
{ a = "Foo"; b = "Bar"; }.a
evaluates to "Foo".Recursive attribute setsRecursive attribute sets are just normal attribute sets, but the
attributes can refer to each other. For example,
rec {
x = y;
y = 123;
}.x
evaluates to 123. Note that without
rec the binding x = y; would
refer to the variable y in the surrounding scope,
if one exists, and would be invalid if no such variable exists. That
is, in a normal (non-recursive) attribute set, attributes are not
added to the lexical scope; in a recursive set, they are.Recursive attribute sets of course introduce the danger of
infinite recursion. For example,
rec {
x = y;
y = x;
}.x
does not terminateActually, Nix detects infinite
recursion in this case and aborts (infinite recursion
encountered)..Let expressionsTODOInheriting attributesTODOFunctionsTODOHigher-order functions; mapConditionalsTODOWith expressionsTODOOperatorsTODODerivationsTODOMiscelleneous built-in functionsTODOThe standard environmentTODO