From 7cc1b04f796ff2ff95fc0a8403dd3343f0cede99 Mon Sep 17 00:00:00 2001 From: Ryan Burns Date: Tue, 12 Oct 2021 14:19:36 -0700 Subject: [PATCH] lib/attrsets: add filterAttrsRecursiveCond function based on the mapAttrsRecursive{,Cond} functions --- lib/attrsets.nix | 31 ++++++++++++++++++++++++++++--- lib/default.nix | 1 + 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/attrsets.nix b/lib/attrsets.nix index c68806912321f..ed71618417917 100644 --- a/lib/attrsets.nix +++ b/lib/attrsets.nix @@ -697,8 +697,33 @@ rec { ::: */ - filterAttrsRecursive = - pred: set: + filterAttrsRecursive = filterAttrsRecursiveCond (_: true); + + /** + Like `filterAttrsRecursive', but it takes an additional predicate that tells it whether to recurse into an attribute set. + If the predicate returns false, `filterAttrsRecursiveCond' does not recurse, but instead applies the filtering function. + If the predicate returns true, it does recurse, and does not apply the filtering function. + + :::{#filter-attrs-recursive-cond-example .example} + # Filter over an leaf attributes defined by a condition + + Filter derivations according to their `name` attribute. + Derivations are identified as attribute sets that contain `{ type = "derivation"; }`. + ```nix + filterAttrsRecursiveCond + (as: !(as ? "type" && as.type == "derivation")) + (x: x.name != "foo") + attrs + ``` + ::: + + # Type: + ``` + filterAttrsRecursiveCond :: (AttrSet -> Bool) -> (String -> a -> Bool) -> AttrSet -> AttrSet + ``` + */ + filterAttrsRecursiveCond = + cond: pred: set: listToAttrs ( concatMap ( name: @@ -707,7 +732,7 @@ rec { in if pred name v then [ - (nameValuePair name (if isAttrs v then filterAttrsRecursive pred v else v)) + (nameValuePair name (if isAttrs v && cond v then filterAttrsRecursiveCond cond pred v else v)) ] else [ ] diff --git a/lib/default.nix b/lib/default.nix index 875a1b9bb3efd..023f022e739ce 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -195,6 +195,7 @@ let catAttrs filterAttrs filterAttrsRecursive + filterAttrsRecursiveCond foldlAttrs foldAttrs collect