From a7aa95db53ad43533805bf0971b6c77fa7e87c01 Mon Sep 17 00:00:00 2001 From: Robert Hensing Date: Wed, 13 Dec 2023 18:38:41 +0100 Subject: [PATCH] lib/attrsets: Document and link Nix language operators --- lib/attrsets.nix | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/attrsets.nix b/lib/attrsets.nix index 9b4a8684f9b7..99b686918453 100644 --- a/lib/attrsets.nix +++ b/lib/attrsets.nix @@ -14,6 +14,14 @@ rec { /* Return an attribute from nested attribute sets. + Nix has an [attribute selection operator `. or`](https://nixos.org/manual/nix/stable/language/operators#attribute-selection) which is sufficient for such queries, as long as the number of attributes is static. For example: + + ```nix + (x.a.b or 6) == attrByPath ["a" "b"] 6 x + # and + (x.${f p}."example.com" or 6) == attrByPath [ (f p) "example.com" ] 6 x + ``` + Example: x = { a = { b = 3; }; } # ["a" "b"] is equivalent to x.a.b @@ -51,6 +59,14 @@ rec { /* Return if an attribute from nested attribute set exists. + Nix has a [has attribute operator `?`](https://nixos.org/manual/nix/stable/language/operators#has-attribute), which is sufficient for such queries, as long as the number of attributes is static. For example: + + ```nix + (x?a.b) == hasAttryByPath ["a" "b"] x + # and + (x?${f p}."example.com") == hasAttryByPath [ (f p) "example.com" ] x + ``` + **Laws**: 1. ```nix hasAttrByPath [] x == true @@ -177,6 +193,14 @@ rec { /* Like `attrByPath`, but without a default value. If it doesn't find the path it will throw an error. + Nix has an [attribute selection operator](https://nixos.org/manual/nix/stable/language/operators#attribute-selection) which is sufficient for such queries, as long as the number of attributes is static. For example: + + ```nix + x.a.b == getAttrByPath ["a" "b"] x + # and + x.${f p}."example.com" == getAttrByPath [ (f p) "example.com" ] x + ``` + Example: x = { a = { b = 3; }; } getAttrFromPath ["a" "b"] x