From 61cfbf1578622980d96d5f7e9269a6ac092490d7 Mon Sep 17 00:00:00 2001 From: h7x4 Date: Mon, 30 Sep 2024 17:24:29 +0200 Subject: [PATCH 1/2] lib: let `getAttrs` ignore nonexistent keys Like its cousin `lib.removeAttrs`, `getAttrs` should now ignore keys that does not exist in the attrset. --- lib/attrsets.nix | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/attrsets.nix b/lib/attrsets.nix index 8bb4ef972fd8c..8668be1892794 100644 --- a/lib/attrsets.nix +++ b/lib/attrsets.nix @@ -541,7 +541,8 @@ rec { /** Given a set of attribute names, return the set of the corresponding - attributes from the given set. + attributes from the given set. If the attributes does not exist, + they will be ignored. # Inputs @@ -565,7 +566,7 @@ rec { ## `lib.attrsets.getAttrs` usage example ```nix - getAttrs [ "a" "b" ] { a = 1; b = 2; c = 3; } + getAttrs [ "a" "b" "d" ] { a = 1; b = 2; c = 3; } => { a = 1; b = 2; } ``` @@ -573,7 +574,7 @@ rec { */ getAttrs = names: - attrs: genAttrs names (name: attrs.${name}); + attrs: intersectAttrs (genAttrs names (_: null)) attrs; /** Collect each attribute named `attr` from a list of attribute From d243c48b1412e86bb1589b6064ba8d4638129ca7 Mon Sep 17 00:00:00 2001 From: h7x4 Date: Mon, 30 Sep 2024 17:26:30 +0200 Subject: [PATCH 2/2] lib/tests: test `getAttrs` --- lib/tests/misc.nix | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 116d86cdfb3fb..17617171bec1b 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -57,6 +57,7 @@ let functionArgs generators genList + getAttrs getExe getExe' getLicenseFromSpdxIdOr @@ -2094,6 +2095,18 @@ runTests { }; }; + testGetAttrs = { + expr = getAttrs [ "a" "b" "nonexistent" ] { + a = 1; + b = true; + c = "hello"; + }; + expected = { + a = 1; + b = true; + }; + }; + ## Levenshtein distance functions and co. testCommonPrefixLengthEmpty = { expr = strings.commonPrefixLength "" "hello";