How to garbage collect nix store without removing currently used packages?

I’m using nix for a number of projects, but I’m not running NixOS. My nix store is getting quite bloated, I presume there’s a lot of old cruft in there I’ll never use again. I want to remove all old builds, but I don’t want to remove anything I’m currently using.

I was thinking a way to do this was to:

  1. Enter a nix develop shell with all my current projects in separate terminals (with master checked out, for example).
  2. Run nix-store --gc.

Would the active nix develop shells prevent any packages used by the current master branch of my projects being eaten up by the garbage collector?

But then I have the issue that I’d probably like to save any packages that are produced by a nix build of my respective projects also. I’m not sure how to force the garbage collector to respect any packages required by a nix build?

I basically don’t want to rebuild anything I’m “currently” using, but don’t care if packages built years ago get GCed.

Anyway to do this?

It all comes down to having garbage collector roots somewhere.

Yes. You might want to have a look at nix-direnv to make it so you don’t even need to enter those shells in the future.

As long as the result symlink of such builds is still there those packages won’t be cleaned up.

You can also manually place roots for any store paths you want to keep - note that you’ll also have to delete them manually once you do want to get rid of them: Garbage Collector Roots - Nix Reference Manual