Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: improve filterAttrs #345547

Merged
merged 3 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions lib/attrsets.nix
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ let
inherit (builtins) head length;
inherit (lib.trivial) isInOldestRelease mergeAttrs warn warnIf;
inherit (lib.strings) concatStringsSep concatMapStringsSep escapeNixIdentifier sanitizeDerivationName;
inherit (lib.lists) foldr foldl' concatMap elemAt all partition groupBy take foldl;
inherit (lib.lists) filter foldr foldl' concatMap elemAt all partition groupBy take foldl;
in

rec {
Expand Down Expand Up @@ -644,8 +644,7 @@ rec {
filterAttrs =
pred:
set:
listToAttrs (concatMap (name: let v = set.${name}; in if pred name v then [(nameValuePair name v)] else []) (attrNames set));

removeAttrs set (filter (name: ! pred name set.${name}) (attrNames set));

/**
Filter an attribute set recursively by removing all attributes for
Expand Down
20 changes: 20 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ let
evalModules
extends
filter
filterAttrs
fix
fold
foldAttrs
Expand Down Expand Up @@ -1102,6 +1103,25 @@ runTests {
};
};

testFilterAttrs = {
expr = filterAttrs (n: v: n != "a" && (v.hello or false) == true) {
a.hello = true;
b.hello = true;
c = {
hello = true;
world = false;
};
d.hello = false;
};
expected = {
b.hello = true;
c = {
hello = true;
world = false;
};
};
};

# code from example
testFoldlAttrs = {
expr = {
Expand Down