This is an automated archive made by the Lemmit Bot.

The original was posted on /r/nixos by /u/onmach on 2024-11-06 16:51:49+00:00.


I was writing some terranix for fun but wanting to stab myself a bit, I googled to see if there was any way to use pipes in nix and I was shocked to realize, yes there was. Some kind hearted individual merged an extension with pipes into nix just a few months ago, and I’ve heard zero chatter about it, since.

I decided to take the leap and upgrade to unstable to give this a try, and wow it works so well. Particularly for modules of a style like the nginx module in nixpkgs that iterates over free form virtualHosts, the code is so much more understandable and easy to maintain, it is like night and day.

Some befores and afters in my current code base.

# before
let digital_ocean_loadbalancer_regions = lib.lists.unique (lib.map (value: value.region) (builtins.attrValues (lib.filterAttrs (name: value: value.loadbalancer.enable) digital_ocean_clouds)));
# after
let digital_ocean_loadbalancer_regions = digital_ocean_clouds |> lib.filterAttrs (name: value: value.loadbalancer.enable) |> lib.mapAttrs (name: value: value.region) |> builtins.attrValues |> lib.lists.unique

# before
let
    # I hate this but I can't think of a better way to do this
    list_of_clouds = lib.map
        ({name, value}: {name = name; replicas = value.replicas; region = value.region; talos_image_version = value.talos_image_version;})
        (lib.attrsToList digital_ocean_clouds);
    f = {name, replicas, region, talos_image_version}:
        lib.map (replica: {name = name; replica = replica; region = region; talos_image_version = talos_image_version;})
        replicas;
    x = lib.lists.concatMap f list_of_clouds;

in lib.map createResource x;

# after
digital_ocean_clouds
|> lib.attrsToList
|> lib.map ({name, value}:
    { inherit name; inherit (value) replicas region talos_image_version; }
)
|> lib.map (x:
    x.replicas
    |> lib.map (replica: { inherit (x) name region talos_image_version; inherit replica; })
)
|> lib.concatLists
|> lib.map createDroplet;

As a bonus it feels like various llms deal with this code far more easily, giving much better refactors of code than before, especialy dealing with parenthesis better. Give it a try!