diff --git a/lib/attrsets.nix b/lib/attrsets.nix index bf6c90bf1be60..afb8362f0de19 100644 --- a/lib/attrsets.nix +++ b/lib/attrsets.nix @@ -651,6 +651,20 @@ rec { f: listToAttrs (map (n: nameValuePair n (f n)) names); + /* Generate an attribute set by mapping over a list of items + Taking two functions, one to apply for the name and one to + apply for the value of the attribute set. + + Example: + genAttrs' [ {a = 2; b.c = "a" } {a = 1; b.c = "b"} ] + (i: i.b.c) (i: i.a) + => { a = 2; b = 1; } + + Type: + genAttrs' :: [ a ] -> (a -> String) -> (a -> Any) -> AttrSet + */ + genAttrs' = items: f: g: + listToAttrs (map (i: nameValuePair (f i) (g i)) items); /* Check whether the argument is a derivation. Any set with `{ type = "derivation"; }` counts as a derivation. diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 06cb5e763e2c2..033ac44091976 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -785,6 +785,17 @@ runTests { }; }; + testGenAttrs = { + expr = attrsets.genAttrs [ "foo" "bar" ] (name: "${name}123"); + expected = { foo = "foo123"; bar = "bar123"; }; + }; + testGenAttrsPrime = { + expr = attrsets.genAttrs' [ { foo = "a"; bar = "b"; } { foo = "c"; bar = "d"; } ] (x: x.foo) (x: "${toString x.foo}${toString x.bar}"); + expected = { + a = "ab"; + c = "cd"; + }; + }; testMergeAttrsListExample1 = { expr = attrsets.mergeAttrsList [ { a = 0; b = 1; } { c = 2; d = 3; } ];