From 2272bc6049e04f98d93f82f22497dc805fbe00cd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Th=C3=A9ophane=20Hufschmitt?=
 <theophane.hufschmitt@tweag.io>
Date: Tue, 7 Mar 2023 10:33:21 +0100
Subject: [PATCH] Fix `nix-collect-garbage -d` with the new profile location

Low-hanging fix for https://github.com/NixOS/nix/pull/5226#issuecomment-1454669399
---
 src/nix-collect-garbage/nix-collect-garbage.cc |  3 +--
 tests/gc.sh                                    | 17 +++++++++++++++++
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/src/nix-collect-garbage/nix-collect-garbage.cc b/src/nix-collect-garbage/nix-collect-garbage.cc
index 8a4fdcb93..3cc57af4e 100644
--- a/src/nix-collect-garbage/nix-collect-garbage.cc
+++ b/src/nix-collect-garbage/nix-collect-garbage.cc
@@ -77,8 +77,7 @@ static int main_nix_collect_garbage(int argc, char * * argv)
             return true;
         });
 
-        auto profilesDir = settings.nixStateDir + "/profiles";
-        if (removeOld) removeOldGenerations(profilesDir);
+        if (removeOld) removeOldGenerations(profilesDir());
 
         // Run the actual garbage collector.
         if (!dryRun) {
diff --git a/tests/gc.sh b/tests/gc.sh
index ad09a8b39..98d6cb032 100644
--- a/tests/gc.sh
+++ b/tests/gc.sh
@@ -50,3 +50,20 @@ if test -e $outPath/foobar; then false; fi
 # Check that the store is empty.
 rmdir $NIX_STORE_DIR/.links
 rmdir $NIX_STORE_DIR
+
+## Test `nix-collect-garbage -d`
+# `nix-env` doesn't work with CA derivations, so let's ignore that bit if we're
+# using them
+if [[ -z "${NIX_TESTS_CA_BY_DEFAULT:-}" ]]; then
+    clearProfiles
+    # Run two `nix-env` commands, should create two generations of
+    # the profile
+    nix-env -f ./user-envs.nix -i foo-1.0
+    nix-env -f ./user-envs.nix -i foo-2.0pre1
+    [[ $(nix-env --list-generations | wc -l) -eq 2 ]]
+
+    # Clear the profile history. There should be only one generation
+    # left
+    nix-collect-garbage -d
+    [[ $(nix-env --list-generations | wc -l) -eq 1 ]]
+fi