Merge pull request #154196 from romildo/add.checkListOfEnum

lib.checkListOfEnum: init
This commit is contained in:
José Romildo Malaquias 2022-01-10 08:11:51 -03:00 committed by GitHub
commit 54bf8b2d70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View file

@ -66,7 +66,7 @@ let
stringLength sub substring tail trace;
inherit (self.trivial) id const pipe concat or and bitAnd bitOr bitXor
bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max
importJSON importTOML warn warnIf throwIfNot
importJSON importTOML warn warnIf throwIfNot checkListOfEnum
info showWarnings nixpkgsVersion version
mod compare splitByAndCompare functionArgs setFunctionArgs isFunction
toHexString toBaseDigits;

View file

@ -347,6 +347,23 @@ rec {
*/
throwIfNot = cond: msg: if cond then x: x else throw msg;
/* Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise.
Example:
let colorVariants = ["bright" "dark" "black"]
in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
=>
error: color variants: bright, black unexpected; valid ones: standard, light, dark
Type: String -> List ComparableVal -> List ComparableVal -> a -> a
*/
checkListOfEnum = msg: valid: given:
let
unexpected = lib.subtractLists valid given;
in
lib.throwIfNot (unexpected == [])
"${msg}: ${builtins.concatStringsSep ", " (builtins.map builtins.toString unexpected)} unexpected; valid ones: ${builtins.concatStringsSep ", " (builtins.map builtins.toString valid)}";
info = msg: builtins.trace "INFO: ${msg}";
showWarnings = warnings: res: lib.foldr (w: x: warn w x) res warnings;