Skip to content

Commit

Permalink
lib: add option parameter to make default additive
Browse files Browse the repository at this point in the history
It's sometimes the case that your option's default value should be additive such
that setting it results in the default value being merged with whatever was set.

Previously, you had to add the default value in the implementation which might
be many lines away from the option declaration and is generally an odd pattern.

This is a lot clearer, simpler and doesn't add much complexity.

If this becomes used more widely, it should be rendered in the generated options'
manual and nixos-search.
  • Loading branch information
Atemu committed Mar 18, 2024
1 parent 0ad13a6 commit 2a6744e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/modules.nix
Original file line number Diff line number Diff line change
Expand Up @@ -780,9 +780,11 @@ let
evalOptionValue = loc: opt: defs:
let
# Add in the default value for this option, if any.
defs' =
(optional (opt ? default)
{ file = head opt.declarations; value = mkOptionDefault opt.default; }) ++ defs;
defs' = (optional (opt ? default) {
file = head opt.declarations;
value = (if opt.additive or false then id else mkOptionDefault) opt.default;
})
++ defs;

# Handle properties, check types, and merge everything together.
res =
Expand Down
2 changes: 2 additions & 0 deletions lib/options.nix
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ rec {
visible ? null,
# Whether the option can be set only once
readOnly ? null,
# Whether the option default will be merged or overridden when the option is set
additive ? false
} @ attrs:
attrs // { _type = "option"; };

Expand Down

0 comments on commit 2a6744e

Please sign in to comment.