From 1e7ccb7acf70805693d6e8f4a4ef01d191804544 Mon Sep 17 00:00:00 2001 From: Kiana Sheibani Date: Wed, 26 Nov 2025 16:53:32 -0500 Subject: [PATCH] refactor: improve `flake.nix` code --- flake.nix | 52 ++++++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/flake.nix b/flake.nix index 51cee52..2ec1f3f 100644 --- a/flake.nix +++ b/flake.nix @@ -2,41 +2,45 @@ description = "Hello World flake templates for various languages and build systems"; outputs = { self, ... }: - let + with builtins; let + concatMapAttrs = func: attr: + foldl' (x: y: x // y) {} (map func attr); + + # Template Aliases + # Used to pick default template for each language aliases = { bash = "bash_script_nixpkgs"; fish = "fish_script_nixpkgs"; python = "python_pyproject_nixpkgs_basic"; }; - # Get all project directories + # Get all subdirectories of the given path + # Returns [str] subdirs = dir: - let sub = __readDir dir; - in builtins.filter - (d: sub.${d} == "directory") - (builtins.attrNames sub); - - concatMapAttrs = func: attr: - builtins.foldl' (x: y: x // y) {} - (builtins.map func attr); + let subd = readDir dir; + in filter (d: subd.${d} == "directory") (attrNames subd); + # Get all proper recursive subdirectories with flakes in them + # Returns [[str]] (list of subdirectory sequences, for processing) flakeSubdirs = dir: - builtins.concatMap (sub: - if builtins.pathExists /${dir}/${sub}/flake.nix then [ [ sub ] ] else - builtins.map (l: [ sub ] ++ l) (flakeSubdirs /${dir}/${sub})) + concatMap (subd: + if pathExists /${dir}/${subd}/flake.nix then [ [ subd ] ] else + map (l: [ subd ] ++ l) (flakeSubdirs /${dir}/${subd})) (subdirs dir); + + generateDesc = subds: + "${head subds} template - ${concatStringsSep ", " (tail subds)}"; in { - templates = concatMapAttrs (path: { - ${builtins.concatStringsSep "_" path} = { - description = "${builtins.head path} template - ${builtins.concatStringsSep - ", " (builtins.tail path)}"; - path = builtins.filterSource - (path: type: builtins.baseNameOf path != "flake.lock") - (builtins.foldl' (dir: sub: /${dir}/${sub}) ./. path); + templates = concatMapAttrs (subds: { + ${concatStringsSep "_" subds} = { + description = generateDesc subds; + path = filterSource + (p: _: baseNameOf p != "flake.lock") + (foldl' (dir: subd: /${dir}/${subd}) ./. subds); }; - }) (flakeSubdirs ./.) // builtins.mapAttrs (lang: def: - self.templates.${def} // { - description = "${lang} template"; - }) aliases; + }) (flakeSubdirs ./.) // mapAttrs (from: to: + self.templates.${to} // { + description = generateDesc (filter (p: p != []) (split "_" to)); + }) aliases; }; }