From 5d24a1199053cea2a759f7e64eef735a135873ca Mon Sep 17 00:00:00 2001 From: Mohammad Rafiq Date: Mon, 7 Jul 2025 15:18:33 +0800 Subject: [PATCH] feat(lib): add admin user using custom lib function --- nix/flake-parts/meta.nix | 18 +++++++++++++- nix/lib/attrsets.nix | 54 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 nix/lib/attrsets.nix diff --git a/nix/flake-parts/meta.nix b/nix/flake-parts/meta.nix index e7659e6..4398cfb 100644 --- a/nix/flake-parts/meta.nix +++ b/nix/flake-parts/meta.nix @@ -1,8 +1,16 @@ -{ lib, inputs, ... }: +{ + lib, + config, + inputs, + ... +}: let inherit (lib.options) mkOption; inherit (lib.types) path lazyAttrsOf raw; inherit (inputs.flake-parts.lib) mkSubmoduleOptions; + inherit (cfg.lib.attrsets) firstAttrNameMatching; + cfg = config.flake; + username = firstAttrNameMatching (_: v: v.primary or false) cfg.manifest.users; in { options.flake = mkSubmoduleOptions { @@ -14,5 +22,13 @@ in type = path; default = ""; }; + admin = mkOption { + type = lazyAttrsOf raw; + default = { }; + }; + }; + + config.flake.admin = cfg.manifest.users.${username} // { + inherit username; }; } diff --git a/nix/lib/attrsets.nix b/nix/lib/attrsets.nix new file mode 100644 index 0000000..1361c2a --- /dev/null +++ b/nix/lib/attrsets.nix @@ -0,0 +1,54 @@ +{ lib, ... }: +let + inherit (builtins) attrNames head; + inherit (lib.trivial) pipe; + inherit (lib.attrsets) filterAttrs; +in +{ + flake.lib.attrsets = { + /** + `firstAttrNameMatching pred set` filters an attribute set `set` based on a predicate `pred` + and returns the *first* attribute name that satisfies the predicate. + + # Example + + ```nix + let + mySet = { + a = { value = 1; }; + b = { value = 2; }; + c = { value = 3; }; + }; + + isGreaterThanOne = name: value: value.value > 1; + + result = firstAttrNameMatching isGreaterThanOne mySet; + + in + result + # Output: "b" + ``` + + # Type + + ``` + firstAttrNameMatching :: (String -> Any -> Bool) -> AttrSet -> String + ``` + + # Arguments + + pred + : A function that takes an attribute name and its value and returns a boolean. + + set + : The attribute set to filter. + */ + firstAttrNameMatching = + pred: set: + pipe set [ + (filterAttrs pred) + attrNames + head + ]; + }; +}