From fe22f3f45f431de636c887d0e114eca3a7fc63c2 Mon Sep 17 00:00:00 2001 From: Daniel Olsen Date: Sun, 26 Nov 2023 08:23:03 +0100 Subject: [PATCH 1/2] lib/tests: Add test for genAttrs --- lib/tests/misc.nix | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 06cb5e763e2c2..137f06c4e7d31 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -785,6 +785,10 @@ runTests { }; }; + testGenAttrs = { + expr = attrsets.genAttrs [ "foo" "bar" ] (name: "${name}123"); + expected = { foo = "foo123"; bar = "bar123"; }; + }; testMergeAttrsListExample1 = { expr = attrsets.mergeAttrsList [ { a = 0; b = 1; } { c = 2; d = 3; } ]; From 7bbba3ffda2c9dc5f674e01ce169b1b56d6fce5d Mon Sep 17 00:00:00 2001 From: Daniel Olsen Date: Sun, 26 Nov 2023 13:22:09 +0100 Subject: [PATCH 2/2] lib/attrsets: add genAttrs' --- lib/attrsets.nix | 14 ++++++++++++++ lib/tests/misc.nix | 7 +++++++ 2 files changed, 21 insertions(+) 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 137f06c4e7d31..033ac44091976 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -789,6 +789,13 @@ runTests { 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; } ];