Hacker symbol

September 21, 2023 ~ 2 min read

Explainer of nixpkgs/nixos/default.nix


This file https://github.com/NixOS/nixpkgs/blob/master/nixos/default.nix

{ configuration ? import ./lib/from-env.nix "NIXOS_CONFIG" <nixos-config>
, system ? builtins.currentSystem
}:

let

  eval = import ./lib/eval-config.nix {
    inherit system;
    modules = [ configuration ];
  };

in

{
  inherit (eval) pkgs config options;

  system = eval.config.system.build.toplevel;

  inherit (eval.config.system.build) vm vmWithBootLoader;
}

This week I was working with https://github.com/astro/microvm.nix and I was trying to understand how it was creating the NixOS configurations. This lead me to the above file that pretty much receives a NixOS configuration.nix (usually located at /etc/nixos/configuration.nix) and generates and attribute set that the nix cli will be used to build a system derivation. Lets go line by line and see what it does.

Inputs

{
    configuration ? import ./lib/from-env.nix "NIXOS_CONFIG" <nixos-config>,
    system ? builtins.currentSystem
}:

The above two inputs of a nix function are: - configuration which has the default value of the environment variable NIXOS_CONFIG or <nixos-config> which is usually passed in as a cli argument in the form of: -I nixos-config=./configuration.nix. I know that the value <nixpkgs> is usually a path defined in a file ~/.config or /etc/nix. Using the bracket notation used be much more common before nix Flakes got introduced. - system which is the host machine architecture ("aarch64-linux", "x86_64-linux")

let closure

eval = import ./lib/eval-config.nix {
    inherit system;
    modules = [ configuration ];
};

These lines imports a nix file, which is a function that needs the arguments system and modules. In the end it returns the evaluated value and calls it eval.

Returned attribute set

{
  inherit (eval) pkgs config options;
  system = eval.config.system.build.toplevel;
  inherit (eval.config.system.build) vm vmWithBootLoader;
}

The above is an attribute set that is returned by nixpkgs/nixos/default.nix. The attribute names are as follows:

{
    pkgs = ...; # All of the packages for the determined system
    config = ...; # The config of nixos
    options = ...; # The options enabled of the above config
    system = <originally builtins.currentSystem>;
    # The following two options are used by the `nixos-rebuild build-vm` command
    vm = {...};  
    vmWithBootLoader =  {...} ;
}

Sebastian BolaƱos

Hi, I'm Sebastian. I'm a software developer from Costa Rica. You can follow me on Twitter. I enjoy working on distributed systems.