Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

treewide: improve usage of lib.optional and lib.optionals #304726

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions nixos/modules/config/xdg/portal.nix
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ in
packages = [ pkgs.xdg-desktop-portal ] ++ cfg.extraPortals;
in
mkIf cfg.enable {
warnings = lib.optional (cfg.configPackages == [ ] && cfg.config == { }) ''
warnings = lib.optionals (cfg.configPackages == [ ] && cfg.config == { }) [
''
xdg-desktop-portal 1.17 reworked how portal implementations are loaded, you
should either set `xdg.portal.config` or `xdg.portal.configPackages`
to specify which portal backend to use for the requested interface.
Expand All @@ -132,7 +133,8 @@ in
portal implementation found in lexicographical order, use the following:

xdg.portal.config.common.default = "*";
'';
''
];

assertions = [
{
Expand Down
8 changes: 4 additions & 4 deletions nixos/modules/services/monitoring/certspotter.nix
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ let
name = "watchlist";
path = pkgs.writeText "certspotter-watchlist" (builtins.concatStringsSep "\n" cfg.watchlist);
}
++ lib.optional (cfg.emailRecipients != [ ]) {
++ lib.optionals (cfg.emailRecipients != [ ]) [{
name = "email_recipients";
path = pkgs.writeText "certspotter-email_recipients" (builtins.concatStringsSep "\n" cfg.emailRecipients);
}
}]
# always generate hooks dir when no emails are provided to allow running cert spotter with no hooks/emails
++ lib.optional (cfg.emailRecipients == [ ] || cfg.hooks != [ ]) {
++ lib.optionals (cfg.emailRecipients == [ ] || cfg.hooks != [ ]) [{
name = "hooks.d";
path = pkgs.linkFarm "certspotter-hooks" (lib.imap1 (i: path: {
inherit path;
name = "hook${toString i}";
}) cfg.hooks);
});
}]);
in
{
options.services.certspotter = {
Expand Down
5 changes: 3 additions & 2 deletions nixos/modules/services/monitoring/telegraf.nix
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,12 @@ in {
path = lib.optional (config.services.telegraf.extraConfig.inputs ? procstat) pkgs.procps;
serviceConfig = {
EnvironmentFile = config.services.telegraf.environmentFiles;
ExecStartPre = lib.optional (config.services.telegraf.environmentFiles != [])
ExecStartPre = lib.optionals (config.services.telegraf.environmentFiles != []) [
(pkgs.writeShellScript "pre-start" ''
umask 077
${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /var/run/telegraf/config.toml
'');
'')
];
ExecStart="${cfg.package}/bin/telegraf -config ${finalConfigFile}";
ExecReload="${pkgs.coreutils}/bin/kill -HUP $MAINPID";
RuntimeDirectory = "telegraf";
Expand Down
6 changes: 3 additions & 3 deletions nixos/modules/services/networking/mycelium.nix
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ in
"--tun-name"
"mycelium"
"${utils.escapeSystemdExecArgs cfg.extraArgs}"
] ++
(lib.optional (cfg.addHostedPublicNodes || cfg.peers != [ ]) "--peers")
++ cfg.peers ++ (lib.optionals cfg.addHostedPublicNodes [
] ++ lib.optionals (cfg.addHostedPublicNodes || cfg.peers != [ ]) [
"--peers"
] ++ cfg.peers ++ (lib.optionals cfg.addHostedPublicNodes [
"tcp://188.40.132.242:9651" # DE 01
"tcp://[2a01:4f8:221:1e0b::2]:9651"
"quic://188.40.132.242:9651"
Expand Down
4 changes: 2 additions & 2 deletions nixos/modules/services/networking/quicktun.nix
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,13 @@ in
(lib.mapAttrsToList (name: value: if value.privateKey != null then name else null))
(builtins.filter (n: n != null))
(map (n: " - services.quicktun.${n}.privateKey"))
(services: lib.optional (services != [ ]) ''
(services: lib.optionals (services != [ ]) [''
`services.quicktun.<name>.privateKey` is deprecated.
Please use `services.quicktun.<name>.privateKeyFile` instead.

Offending options:
${lib.concatStringsSep "\n" services}
'')
''])
];

systemd.services = lib.mkMerge (
Expand Down
22 changes: 18 additions & 4 deletions nixos/modules/services/system/cachix-watch-store.nix
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,24 @@ in
};
script =
let
command = [ "${cfg.package}/bin/cachix" ]
++ (lib.optional cfg.verbose "--verbose") ++ (lib.optionals (cfg.host != null) [ "--host" cfg.host ])
++ [ "watch-store" ] ++ (lib.optionals (cfg.compressionLevel != null) [ "--compression-level" (toString cfg.compressionLevel) ])
++ (lib.optionals (cfg.jobs != null) [ "--jobs" (toString cfg.jobs) ]) ++ [ cfg.cacheName ];
command = [
"${cfg.package}/bin/cachix"
] ++ lib.optionals cfg.verbose [
"--verbose"
] ++ lib.optionals (cfg.host != null) [
"--host"
cfg.host
] ++ [
"watch-store"
] ++ lib.optionals (cfg.compressionLevel != null) [
"--compression-level"
(toString cfg.compressionLevel)
] ++ lib.optionals (cfg.jobs != null) [
"--jobs"
(toString cfg.jobs)
] ++ [
cfg.cacheName
];
in
''
export CACHIX_AUTH_TOKEN="$(<"$CREDENTIALS_DIRECTORY/cachix-token")"
Expand Down
4 changes: 2 additions & 2 deletions nixos/modules/services/web-servers/nginx/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ in
defaultListenAddresses = mkOption {
type = types.listOf types.str;
default = [ "0.0.0.0" ] ++ optional enableIPv6 "[::0]";
defaultText = literalExpression ''[ "0.0.0.0" ] ++ lib.optional config.networking.enableIPv6 "[::0]"'';
defaultText = literalExpression ''[ "0.0.0.0" ] ++ lib.optionals config.networking.enableIPv6 [ "[::0]" ]'';
example = literalExpression ''[ "10.0.0.12" "[2002:a00:1::]" ]'';
description = ''
If vhosts do not specify listenAddresses, use these addresses by default.
Expand Down Expand Up @@ -1207,7 +1207,7 @@ in
services.nginx.virtualHosts.localhost = mkIf cfg.statusPage {
listenAddresses = lib.mkDefault ([
"0.0.0.0"
] ++ lib.optional enableIPv6 "[::]");
] ++ lib.optionals enableIPv6 [ "[::]" ]);
locations."/nginx_status" = {
extraConfig = ''
stub_status on;
Expand Down
4 changes: 2 additions & 2 deletions nixos/modules/services/web-servers/stargazer.nix
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ in

listen = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ "0.0.0.0" ] ++ lib.optional config.networking.enableIPv6 "[::0]";
defaultText = lib.literalExpression ''[ "0.0.0.0" ] ++ lib.optional config.networking.enableIPv6 "[::0]"'';
default = [ "0.0.0.0" ] ++ lib.optionals config.networking.enableIPv6 [ "[::0]" ];
defaultText = lib.literalExpression ''[ "0.0.0.0" ] ++ lib.optionals config.networking.enableIPv6 [ "[::0]" ]'';
example = lib.literalExpression ''[ "10.0.0.12" "[2002:a00:1::]" ]'';
description = ''
Address and port to listen on.
Expand Down
5 changes: 3 additions & 2 deletions nixos/modules/services/web-servers/traefik.nix
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,12 @@ in {
startLimitBurst = 5;
serviceConfig = {
EnvironmentFile = cfg.environmentFiles;
ExecStartPre = lib.optional (cfg.environmentFiles != [])
ExecStartPre = lib.optionals (cfg.environmentFiles != []) [
(pkgs.writeShellScript "pre-start" ''
umask 077
${pkgs.envsubst}/bin/envsubst -i "${staticConfigFile}" > "${finalStaticConfigFile}"
'');
'')
];
ExecStart = "${cfg.package}/bin/traefik --configfile=${finalStaticConfigFile}";
Type = "simple";
User = "traefik";
Expand Down
45 changes: 24 additions & 21 deletions nixos/modules/system/boot/systemd.nix
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ let
"systemd-udevd-kernel.socket"
"systemd-udevd.service"
"systemd-udev-settle.service"
] ++ (optional (!config.boot.isContainer) "systemd-udev-trigger.service") ++ [
] ++ lib.optionals (!config.boot.isContainer) [
"systemd-udev-trigger.service"
] ++ [
# hwdb.bin is managed by NixOS
# "systemd-hwdb-update.service"

Expand Down Expand Up @@ -95,12 +97,16 @@ let
"dev-hugepages.mount"
"dev-mqueue.mount"
"sys-fs-fuse-connections.mount"
] ++ (optional (!config.boot.isContainer) "sys-kernel-config.mount") ++ [
] ++ lib.optionals (!config.boot.isContainer) [
"sys-kernel-config.mount"
] ++ [
"sys-kernel-debug.mount"

# Maintaining state across reboots.
"systemd-random-seed.service"
] ++ (optional cfg.package.withBootloader "systemd-boot-random-seed.service") ++ [
] ++ lib.optionals cfg.package.withBootloader [
"systemd-boot-random-seed.service"
] ++ [
"systemd-backlight@.service"
"systemd-rfkill.service"
"systemd-rfkill.socket"
Expand Down Expand Up @@ -128,8 +134,9 @@ let
"final.target"
"kexec.target"
"systemd-kexec.service"
] ++ lib.optional cfg.package.withUtmp "systemd-update-utmp.service" ++ [

] ++ lib.optionals cfg.package.withUtmp [
"systemd-update-utmp.service"
] ++ [
# Password entry.
"systemd-ask-password-console.path"
"systemd-ask-password-console.service"
Expand Down Expand Up @@ -166,13 +173,13 @@ let
"systemd-update-done.service"
] ++ cfg.additionalUpstreamSystemUnits;

upstreamSystemWants =
[ "sysinit.target.wants"
"sockets.target.wants"
"local-fs.target.wants"
"multi-user.target.wants"
"timers.target.wants"
];
upstreamSystemWants = [
"sysinit.target.wants"
"sockets.target.wants"
"local-fs.target.wants"
"multi-user.target.wants"
"timers.target.wants"
];

proxy_env = config.networking.proxy.envVars;

Expand Down Expand Up @@ -446,16 +453,12 @@ in
restart = service.serviceConfig.Restart or "no";
hasDeprecated = builtins.hasAttr "StartLimitInterval" service.serviceConfig;
in
concatLists [
(optional (type == "oneshot" && (restart == "always" || restart == "on-success"))
"Service '${name}.service' with 'Type=oneshot' cannot have 'Restart=always' or 'Restart=on-success'"
)
(optional hasDeprecated
"Service '${name}.service' uses the attribute 'StartLimitInterval' in the Service section, which is deprecated. See https://github.com/NixOS/nixpkgs/issues/45786."
)
(optional (service.reloadIfChanged && service.reloadTriggers != [])
[] ++ lib.optionals (type == "oneshot" && (restart == "always" || restart == "on-success")) [
"Service '${name}.service' with 'Type=oneshot' cannot have 'Restart=always' or 'Restart=on-success'"
] ++ lib.optionals hasDeprecated [
"Service '${name}.service' uses the attribute 'StartLimitInterval' in the Service section, which is deprecated. See https://github.com/NixOS/nixpkgs/issues/45786."
] ++ lib.optionals (service.reloadIfChanged && service.reloadTriggers != []) [
"Service '${name}.service' has both 'reloadIfChanged' and 'reloadTriggers' set. This is probably not what you want, because 'reloadTriggers' behave the same whay as 'restartTriggers' if 'reloadIfChanged' is set."
)
]
)
cfg.services
Expand Down
2 changes: 1 addition & 1 deletion nixos/modules/virtualisation/digital-ocean-init.nix
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ let
defaultConfigFile = pkgs.writeText "digitalocean-configuration.nix" ''
{ modulesPath, lib, ... }:
{
imports = lib.optional (builtins.pathExists ./do-userdata.nix) ./do-userdata.nix ++ [
imports = lib.optionals (builtins.pathExists ./do-userdata.nix) [ ./do-userdata.nix ] ++ [
(modulesPath + "/virtualisation/digital-ocean-config.nix")
];
}
Expand Down
9 changes: 6 additions & 3 deletions pkgs/applications/editors/textadept/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ stdenv.mkDerivation rec {
lib.optionals withQt [ qtbase ]
++ lib.optionals withCurses ncurses;

cmakeFlags =
lib.optional withQt [ "-DQT=ON" ]
++ lib.optional withCurses [ "-DCURSES=ON" "-DQT=OFF"];
cmakeFlags = lib.optionals withQt [
"-DQT=ON"
] ++ lib.optionals withCurses [
"-DCURSES=ON"
"-DQT=OFF"
];

preConfigure = ''
mkdir -p $PWD/build/_deps
Expand Down
18 changes: 11 additions & 7 deletions pkgs/applications/editors/vim/plugins/vim-utils.nix
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ let
ln -s ${python3Env}/${python3Env.sitePackages} $out/pack/${packageName}/start/__python3_dependencies/python3
'';
in
[ packdirStart packdirOpt ] ++ lib.optional (allPython3Dependencies python3.pkgs != []) python3link;
[ packdirStart packdirOpt ] ++ lib.optionals (allPython3Dependencies python3.pkgs != []) [ python3link ];
in
buildEnv {
name = "vim-pack-dir";
Expand Down Expand Up @@ -266,12 +266,16 @@ let

entries = [
beforePlugins
]
++ lib.optional (vam != null) (lib.warn "'vam' attribute is deprecated. Use 'packages' instead in your vim configuration" vamImpl)
++ lib.optional (packages != null && packages != []) (nativeImpl packages)
++ lib.optional (pathogen != null) (throw "pathogen is now unsupported, replace `pathogen = {}` with `packages.home = { start = []; }`")
++ lib.optional (plug != null) plugImpl
++ [ customRC ];
customRC
] ++ lib.optionals (vam != null) [
(lib.warn "'vam' attribute is deprecated. Use 'packages' instead in your vim configuration" vamImpl)
] ++ lib.optionals (packages != null && packages != []) [
(nativeImpl packages)
] ++ lib.optionals (pathogen != null) [
(throw "pathogen is now unsupported, replace `pathogen = {}` with `packages.home = { start = []; }`")
] ++ lib.optionals (plug != null) [
plugImpl
];

in
lib.concatStringsSep "\n" (lib.filter (x: x != null && x != "") entries);
Expand Down
11 changes: 8 additions & 3 deletions pkgs/applications/emulators/retroarch/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@ stdenv.mkDerivation rec {
rev = "v${version}";
};

nativeBuildInputs = [ pkg-config wrapQtAppsHook ] ++
lib.optional withWayland wayland ++
lib.optional (runtimeLibs != [ ]) makeWrapper;
nativeBuildInputs = [
pkg-config
wrapQtAppsHook
] ++ lib.optionals withWayland [
wayland
] ++ lib.optionals (runtimeLibs != [ ]) [
makeWrapper
];

buildInputs = [
ffmpeg_4
Expand Down
2 changes: 1 addition & 1 deletion pkgs/applications/networking/libcoap/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ stdenv.mkDerivation rec {
which
libtool
pkg-config
] ++ lib.optional withTLS gnutls ++ lib.optionals withDocs [ doxygen asciidoc ] ;
] ++ lib.optionals withTLS [ gnutls ] ++ lib.optionals withDocs [ doxygen asciidoc ] ;
preConfigure = "./autogen.sh";
configureFlags = [ "--disable-shared" ]
++ lib.optional (!withDocs) "--disable-documentation"
Expand Down
4 changes: 3 additions & 1 deletion pkgs/applications/radio/pat/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ buildGoModule rec {
installShellFiles
];

buildInputs = lib.optional stdenv.isLinux [ libax25 ];
buildInputs = lib.optionals stdenv.isLinux [
libax25
];

# Needed by wl2k-go go module for libax25 to include support for Linux' AX.25 stack by linking against libax25.
# ref: https://github.com/la5nta/wl2k-go/blob/abe3ae5bf6a2eec670a21672d461d1c3e1d4c2f3/transport/ax25/ax25.go#L11-L17
Expand Down
4 changes: 3 additions & 1 deletion pkgs/applications/science/biology/bowtie2/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ stdenv.mkDerivation (finalAttrs: {

buildInputs = [ tbb zlib python3 perl ];

cmakeFlags = lib.optional (!stdenv.hostPlatform.isx86) ["-DCMAKE_CXX_FLAGS=-I${finalAttrs.src}/third_party"];
cmakeFlags = lib.optionals (!stdenv.hostPlatform.isx86) [
"-DCMAKE_CXX_FLAGS=-I${finalAttrs.src}/third_party"
];

# ctest fails because of missing dependencies between tests
doCheck = false;
Expand Down
2 changes: 1 addition & 1 deletion pkgs/build-support/fetchgitlab/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ lib.makeOverridable (
} @ args:

let
slug = lib.concatStringsSep "/" ((lib.optional (group != null) group) ++ [ owner repo ]);
slug = lib.concatStringsSep "/" ([ owner repo ] ++ lib.optionals (group != null) [ group ]);
escapedSlug = lib.replaceStrings [ "." "/" ] [ "%2E" "%2F" ] slug;
escapedRev = lib.replaceStrings [ "+" "%" "/" ] [ "%2B" "%25" "%2F" ] rev;
passthruAttrs = removeAttrs args [ "protocol" "domain" "owner" "group" "repo" "rev" "fetchSubmodules" "forceFetchGit" "leaveDotGit" "deepClone" ];
Expand Down
2 changes: 1 addition & 1 deletion pkgs/by-name/c2/c2patool/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ rustPlatform.buildRustPackage rec {
];
buildInputs = [
openssl
] ++ lib.optional stdenv.isDarwin [
] ++ lib.optionals stdenv.isDarwin [
libiconv
darwin.apple_sdk.frameworks.CoreServices
darwin.apple_sdk.frameworks.Carbon
Expand Down
4 changes: 3 additions & 1 deletion pkgs/by-name/fr/frankenphp/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ in buildGoModule rec {
"-w"
"-X 'github.com/caddyserver/caddy/v2.CustomVersion=FrankenPHP ${version} PHP ${phpUnwrapped.version} Caddy'"
# pie mode is only available with pkgsMusl, it also automaticaly add -buildmode=pie to $GOFLAGS
] ++ (lib.optional pieBuild [ "-static-pie" ]);
] ++ lib.optionals pieBuild [
"-static-pie"
];

preBuild = ''
export CGO_CFLAGS="$(${phpConfig} --includes)"
Expand Down
4 changes: 2 additions & 2 deletions pkgs/by-name/kt/ktls-utils/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ stdenv.mkDerivation rec {

outputs = [ "out" "man" ];

configureFlags = lib.optional withSystemd [ "--with-systemd" ];
configureFlags = lib.optionals withSystemd [ "--with-systemd" ];

makeFlags = lib.optional withSystemd [ "unitdir=$(out)/lib/systemd/system" ];
makeFlags = lib.optionals withSystemd [ "unitdir=$(out)/lib/systemd/system" ];

doCheck = true;

Expand Down