Skip to content

Options argument

There is another attribute that is automatically provided by the module system, options. options provides information about all of the option declarations in the module. It has much more information than config which only gives you the final value. It can tell you what the type is, what the default value is, whether or not it is defined, and many more things.

Note

This is the options function argument attribute which is not to be confused by the options attribute where we declare options.

Let us take a look at using the information provided by options to create conditional logic. In our options.nix file, we have the same option declarations that we have seen in previous lessons. However, we have change how greeting is defined. Now the definition is conditionally generated depending on which options we define. If we set a value for name, then we will get an additional line in our output. If we do not, then that line is completely omitted.

options.nix
{
  lib,
  options,
  config,
  ...
}: let
  cfg = config;
  opts = options;
in {
  options = {
    name = lib.mkOption {
      type = lib.types.str;
    };
    title = lib.mkOption {
      type = lib.types.str;
    };
    origin = lib.mkOption {
      type = lib.types.str;
    };
    greeting = lib.mkOption {
      type = lib.types.str;
    };
  };

  config = {
    greeting =
      lib.concatStringsSep
      "\n"
      (
        [
          "Hello"
        ]
        ++ (lib.optional opts.name.isDefined "My name is ${cfg.name}.")
        ++ (lib.optional opts.title.isDefined "I am a ${cfg.title}.")
        ++ (lib.optional opts.origin.isDefined "I am from ${cfg.origin}.")
      );
  };
}

In our config.nix, we define values for name and origin, but not title. This is fine because use of the title definition is contingent on whether or not it is defined—remember nix is lazy!

config.nix
{...}: {
  config = {
    name = "Boaty McBoatface";
    origin = "England";
  };
}

Setup an eval.nix to evaluate our modules and return the config.greeting attribute.

eval.nix
{pkgs}:
(
  pkgs.lib.evalModules {
    modules = [
      ./options.nix
      ./config.nix
    ];
  }
)
.config
.greeting

Create a run.sh run script to evaluate the eval.nix file.

run.sh
nix eval -f eval.nix \
    --apply 'x: x {pkgs = import <nixpkgs> {};}' \
    --json | nix run nixpkgs#jq -- -r

And if we run the script (./run.sh), we have our configuration.

Hello
My name is Boaty McBoatface.
I am from England.