From 8ba40fdd4fae1edd4d725a53c04401d1f0d8b2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20=C5=BDlender?= Date: Wed, 20 Nov 2024 22:51:15 +0100 Subject: [PATCH] lib: add defaultTo --- lib/default.nix | 2 +- lib/trivial.nix | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/default.nix b/lib/default.nix index aff1df150f13b..48574ab3e4a25 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -71,7 +71,7 @@ let # these are the only ones that are currently not inherit (builtins) addErrorContext isPath trace typeOf unsafeGetAttrPos; inherit (self.trivial) id const pipe concat or and xor bitAnd bitOr bitXor - bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max + bitNot boolToString mergeAttrs flip defaultTo mapNullable inNixShell isFloat min max importJSON importTOML warn warnIf warnIfNot throwIf throwIfNot checkListOfEnum info showWarnings nixpkgsVersion version isInOldestRelease oldestSupportedReleaseIsAtLeast mod compare splitByAndCompare seq deepSeq lessThan add sub diff --git a/lib/trivial.nix b/lib/trivial.nix index 04fb9ffd46180..0e196018961c5 100644 --- a/lib/trivial.nix +++ b/lib/trivial.nix @@ -316,6 +316,40 @@ in { */ flip = f: a: b: f b a; + /** + Return `maybeValue` if not null, otherwise return `default`. + + + # Inputs + + `default` + + : 1\. Function argument + + `maybeValue` + + : 2\. Function argument + + + # Examples + :::{.example} + ## `lib.trivial.defaultTo` usage example + + ```nix + defaultTo "default" null + => "default" + defaultTo "default" "foo" + => "foo" + defaultTo "default" false + => false + ``` + + ::: + */ + defaultTo = default: maybeValue: + if maybeValue != null then maybeValue + else default; + /** Apply function if the supplied argument is non-null.