query
On this page

hasAttrByPath

lib.hasAttrByPath

Docs pulled from | This Revision | about 1 hour ago


Return if an attribute from nested attribute set exists.

Nix has a has attribute operator ?, which is sufficient for such queries, as long as the number of attributes is static. For example:

(x?a.b) == hasAttrByPath ["a" "b"] x
# and
(x?${f p}."example.com") == hasAttrByPath [ (f p) "example.com" ] x

Laws:

  1. hasAttrByPath [] x == true
    

Inputs

attrPath

A list of strings representing the attribute path to check from set

e

The nested attribute set to check

Type

hasAttrByPath :: [String] -> AttrSet -> Bool

Examples

lib.attrsets.hasAttrByPath usage example

x = { a = { b = 3; }; }
hasAttrByPath ["a" "b"] x
=> true
hasAttrByPath ["z" "z"] x
=> false
hasAttrByPath [] (throw "no need")
=> true
(lib.attrsets.hasAttrByPath)

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

hasAttrByPath =
    attrPath: e:
    let
      lenAttrPath = length attrPath;
      hasAttrByPath' =
        n: s:
        (
          n == lenAttrPath
          || (
            let
              attr = elemAt attrPath n;
            in
            if s ? ${attr} then hasAttrByPath' (n + 1) s.${attr} else false
          )
        );
    in
    hasAttrByPath' 0 e;