lib/options: nullable mkPackageOption

It is sometimes useful to allow setting a package option to `null` to
skip installing the package. See
https://github.com/nix-community/home-manager/pull/3668#issuecomment-1554044171
for example.
This commit is contained in:
Naïm Favier 2023-05-19 12:22:21 +02:00
parent 8d25ab1fc6
commit 4a56b2655e
No known key found for this signature in database
GPG key ID: 95AFCE8211908325

View file

@ -155,6 +155,8 @@ rec {
# Name for the package, shown in option description # Name for the package, shown in option description
name: name:
{ {
# Whether the package can be null, for example to disable installing a package altogether.
nullable ? false,
# The attribute path where the default package is located (may be omitted) # The attribute path where the default package is located (may be omitted)
default ? name, default ? name,
# A string or an attribute path to use as an example (may be omitted) # A string or an attribute path to use as an example (may be omitted)
@ -164,19 +166,24 @@ rec {
}: }:
let let
name' = if isList name then last name else name; name' = if isList name then last name else name;
in mkOption ({
type = with lib.types; (if nullable then nullOr else lib.id) package;
description = "The ${name'} package to use."
+ (if extraDescription == "" then "" else " ") + extraDescription;
} // (if default != null then let
default' = if isList default then default else [ default ]; default' = if isList default then default else [ default ];
defaultPath = concatStringsSep "." default'; defaultPath = concatStringsSep "." default';
defaultValue = attrByPath default' defaultValue = attrByPath default'
(throw "${defaultPath} cannot be found in pkgs") pkgs; (throw "${defaultPath} cannot be found in pkgs") pkgs;
in mkOption { in {
default = defaultValue;
defaultText = literalExpression ("pkgs." + defaultPath); defaultText = literalExpression ("pkgs." + defaultPath);
type = lib.types.package; } else if nullable then {
description = "The ${name'} package to use." default = null;
+ (if extraDescription == "" then "" else " ") + extraDescription; } else { }) // lib.optionalAttrs (example != null) {
${if default != null then "default" else null} = defaultValue; example = literalExpression
${if example != null then "example" else null} = literalExpression
(if isList example then "pkgs." + concatStringsSep "." example else example); (if isList example then "pkgs." + concatStringsSep "." example else example);
}; });
/* Like mkPackageOption, but emit an mdDoc description instead of DocBook. */ /* Like mkPackageOption, but emit an mdDoc description instead of DocBook. */
mkPackageOptionMD = pkgs: name: extra: mkPackageOptionMD = pkgs: name: extra: