From 320cdecd1697020cb367adc1f8408dbf689ca254 Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Mon, 6 Aug 2018 01:35:48 +0200 Subject: [PATCH] lib/trivial: add assertOneOf --- lib/default.nix | 2 +- lib/trivial.nix | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/default.nix b/lib/default.nix index fd3be3c6f4bc..358c8ca0b8f9 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -60,7 +60,7 @@ let boolToString mergeAttrs flip mapNullable inNixShell min max importJSON warn info nixpkgsVersion version mod compare splitByAndCompare functionArgs setFunctionArgs isFunction - assertMsg; + assertMsg assertOneOf; inherit (fixedPoints) fix fix' extends composeExtensions makeExtensible makeExtensibleWithCustomName; diff --git a/lib/trivial.nix b/lib/trivial.nix index bba284548d98..f1001ee10ca3 100644 --- a/lib/trivial.nix +++ b/lib/trivial.nix @@ -203,11 +203,29 @@ rec { Type: assertMsg :: Bool -> String -> Bool */ + # TODO(Profpatsch): add tests that check stderr assertMsg = pred: msg: if pred then true else builtins.trace msg false; + /* Specialized `assertMsg` for checking if val is one of the elements + of a list. Useful for checking enums. + + Example: + let sslLibrary = "libressl" + in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ] + => false + stderr> trace: sslLibrary must be one of "openssl", "bearssl", but is: "libressl" + + Type: + assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool + */ + assertOneOf = name: val: xs: assertMsg + (lib.elem val xs) + "${name} must be one of ${ + lib.generators.toPretty {} xs}, but is: ${ + lib.generators.toPretty {} val}"; ## Function annotations