hercules-ci / flake-parts

❄️ Simplify Nix Flakes with the module system
https://flake.parts
MIT License
721 stars 41 forks source link

flake-parts-lib: Add importApply #149

Closed roberth closed 1 year ago

roberth commented 1 year ago

See nixpkgs

roberth commented 1 year ago

Example use would be something like:

mkFlake argument or some imported flake module:

{ withSystem, ... }:
{
  flake.nixosModules.foo = importApply ./nixos-module.nix { inherit withSystem; };
}

nixos-module.nix

{ withSystem }:
{ lib, config, pkgs, ... }:
{
  options = ...;
  config.services.foo.package = mkDefault (
    withSystem pkgs.stdenv.hostPlatform.system ({config, ...}:
      config.packages.default
    )
  );
}
roberth commented 1 year ago

Perhaps another good example would be with flakeModules, passing { localInputs = inputs; } instead of inherit withSystem.

Atry commented 1 year ago

Would importApply work in diamond imports as discussed in https://github.com/NixOS/nixpkgs/issues/215496 ?

Would importApple address this comment?

roberth commented 1 year ago

Would importApply work in diamond imports as discussed in NixOS/nixpkgs#215496 ?

Yes, as long as follows is used. It doesn't guarantee that a missing follows is reported, hence the upstream issue. Most real-world modules define or declare at least something that isn't mergeable, so there will be some error at least.

Would importApple address this comment?

You can not use this option in defining the flake's own imports. Instead, you can put the module in question into its own file and reference it both in imports and export it with this option.

imports must not depend on config. That's a fundamental limitation of the config fixpoint, so no extra function will make that work. You can use a let binding instead.

That said, importApply doesn't really get in the way either. Just make sure your function is lazy enough. Note that { foo }: style functions are a bit strict, although the strictness is harmless if you pass e.g. an attrset literal such as { foo = b; }, or something similarly predictable.

roberth commented 1 year ago

Would importApple address this comment?

A solution is provided here https://flake.parts/dogfood-a-reusable-module.html