NixOS modules: Difference between revisions

Qyriad (talk | contribs)
With Flakes: fix? typo and typesetting; idk what {{|c|nixos-rebuild}} was intended to be
Dafitt (talk | contribs)
Added examples to Declarations
Line 174: Line 174:
Declarations specify a module's external interfaces.
Declarations specify a module's external interfaces.


<syntaxhighlight lang=nix>
<syntaxhighlight lang="nix">
optionName = mkOption {
options = {
  # ...
  optionName = mkOption {
    # ...
  };
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 207: Line 209:
</dl>
</dl>


==== Examples ====
[[File:NixOS Search - Options.png|alt=A search query `programs.bat.` on the official NixOS Search - Options.|thumb|268x268px|For more examples you can browse [https://github.com/NixOS/nixpkgs NixOS/nixpkgs]: Search a similar option on [https://search.nixos.org/options NixOS Search - Options] and click on the link beside "Declared in".]]
Some useful option examples.<syntaxhighlight lang="nixos">
{ lib, pkgs, ... }: {
  options.examples = {
    enable = lib.options.mkEnableOption "showcasing of options";
    # type = lib.types.bool;
    package = lib.options.mkPackageOption pkgs "bash" { };
    # type = lib.types.package;
    groceries = lib.options.mkOption {
      type = lib.types.listOf lib.types.strMatching "^[a-z]*$";
      default = [];
      description = "Showcase `listOf` and `strMatching`".
      example = [
        "bananas"
        "cherrys"
        "Throws an error at evaluation beause of regex not matching."
      ];
    };
    settings = lib.options.mkOption {
      type = lib.types.json;
      default = {};
      description = ''
        Showcase the possible option for settings of a configuration file.
        Always document, where you can find possible options e.g.:
          Refer <https://example.com/> for possible options.
      '';
      example = {
        global = {
          log_format = "-";
          log_filter = "^$";
        };
      };
    };
 
    units = lib.options.mkOption {
      type = lib.types.attrsOf (lib.types.submodule (
        { name, ... }:
        {
          options = {
            name = lib.options.mkOption {
              type = lib.types.str;
              default = name;
              defaultText = "<name>";
              description = "Name of the unit";
            };
            unit = lib.options.mkOption {
              type = lib.types.str;
              defaultText = ''
                Default will be set in the `config` block
                of the `submodule` (see down below)
              '';
              description = "A unit of measurement";
            };
          };
          config = {
            unit = lib.mkDefault "kg";
          };
        }
      ));
      default = {};
      description = "Showcase the combination `attrsOf` and `submodule`";
      example = {
        "unit1" = { unit = "m" };
        "unit2".unit = "cm";
      };
    };
  };
}
</syntaxhighlight>
== Rationale ==
== Rationale ==