Skip to content

Commit

Permalink
lib/attrsets: add concatMapAttrs
Browse files Browse the repository at this point in the history
  • Loading branch information
figsoda committed Nov 17, 2022
1 parent 4536eba commit f993f8a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
21 changes: 20 additions & 1 deletion lib/attrsets.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

let
inherit (builtins) head tail length;
inherit (lib.trivial) id;
inherit (lib.trivial) flip id mergeAttrs pipe;
inherit (lib.strings) concatStringsSep concatMapStringsSep escapeNixIdentifier sanitizeDerivationName;
inherit (lib.lists) foldr foldl' concatMap concatLists elemAt all partition groupBy take foldl;
in
Expand Down Expand Up @@ -77,6 +77,25 @@ rec {
let errorMsg = "cannot find attribute `" + concatStringsSep "." attrPath + "'";
in attrByPath attrPath (abort errorMsg);

/* Map each attribute in the given set and merge them into a new attribute set.
Type:
concatMapAttrs ::
(String -> a -> AttrSet)
-> AttrSet
-> AttrSet
Example:
concatMapAttrs
(name: value: {
${name} = value;
${name + value} = value;
})
{ x = "a"; y = "b"; }
=> { x = "a"; xa = "a"; y = "b"; yb = "b"; }
*/
concatMapAttrs = f: flip pipe [ (mapAttrs f) attrValues (foldl' mergeAttrs { }) ];


/* Update or set specific paths of an attribute set.
Expand Down
2 changes: 1 addition & 1 deletion lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ let
inherit (self.attrsets) attrByPath hasAttrByPath setAttrByPath
getAttrFromPath attrVals attrValues getAttrs catAttrs filterAttrs
filterAttrsRecursive foldAttrs collect nameValuePair mapAttrs
mapAttrs' mapAttrsToList mapAttrsRecursive mapAttrsRecursiveCond
mapAttrs' mapAttrsToList concatMapAttrs mapAttrsRecursive mapAttrsRecursiveCond
genAttrs isDerivation toDerivation optionalAttrs
zipAttrsWithNames zipAttrsWith zipAttrs recursiveUpdateUntil
recursiveUpdate matchAttrs overrideExisting showAttrPath getOutput getBin
Expand Down
17 changes: 17 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,23 @@ runTests {

# ATTRSETS

testConcatMapAttrs = {
expr = concatMapAttrs
(name: value: {
${name} = value;
${name + value} = value;
})
{
foo = "bar";
foobar = "baz";
};
expected = {
foo = "bar";
foobar = "baz";
foobarbaz = "baz";
};
};

# code from the example
testRecursiveUpdateUntil = {
expr = recursiveUpdateUntil (path: l: r: path == ["foo"]) {
Expand Down

0 comments on commit f993f8a

Please sign in to comment.