numtide / flake-utils

Pure Nix flake utility functions [maintainer=@zimbatm]
MIT License
1.14k stars 78 forks source link

Prefer `import nixpkgs` #71

Closed WhyNotHugo closed 2 years ago

WhyNotHugo commented 2 years ago

Avoid using legacyPackages and use import nixpkgs instead. The latter has the advantage of being easier to extend. For example, with overlays:

pkgs = import nixpkgs {
  overlays = [ self.overlays.default ];
  inherit system;
};
WhyNotHugo commented 2 years ago

In case you're interested in a full example using overlays with this syntax:

{
  description = "Hugo's neovim setup";

  inputs.flake-utils.url = "github:numtide/flake-utils";

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem
      (system:
        let
          pkgs = import nixpkgs {
            overlays = [ self.overlays.default ];
            inherit system;
          };
          paths = pkgs.lib.makeBinPath [
            pkgs.neovim
            pkgs.gopls
            # TODO: more LSPs here
          ];
        in
        {
          defaultPackage = pkgs.writeShellScriptBin "v" ''
            export PATH=${paths}:$PATH
            nvim "$@"
          '';
        }
      ) // {
      # Wrap LSPs to run them containerised.
      overlays.default = final: prev: {

        gopls = prev.writeShellScriptBin "gopls" ''
          export PATH=${prev.lib.makeBinPath [ prev.go ]}:$PATH
          bwrap \
            --share-net \
            --ro-bind "$(pwd)" "$(pwd)" \
            --ro-bind /nix /nix \
            --proc /proc \
            --dev /dev \
            --tmpfs /tmp
            ${prev.gopls}/bin/gopls
        '';

      };

    };
}
zimbatm commented 2 years ago

It's fine in isolation but it's problematic (in terms of CPU and RAM usage) if every flake dependency creates its own instance of nixpkgs. The best is if each flake can use the same instance of nixpkgs.legacyPackages and then compose.

I wrote a longer blog post that explains the idea a bit further: https://zimbatm.com/notes/1000-instances-of-nixpkgs