Skip to content

Commit d295708

Browse files
committed
devbox: clean up profile history after sync
After syncing the flake packages to the profile, remove all old generations of the Nix profile. This allows the Nix garbage collector to eventually remove any old packages. Opted for a Go implementation instead of calling `nix profile wipe-history` because deleting the history is pretty simple and this is faster.
1 parent 6d759b4 commit d295708

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

internal/devbox/nixprofile.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"errors"
66
"fmt"
77
"log/slog"
8+
"os"
9+
"path/filepath"
810
"strings"
911

1012
"github.com/samber/lo"
@@ -84,5 +86,42 @@ func (d *Devbox) syncNixProfileFromFlake(ctx context.Context) error {
8486
return fmt.Errorf("error installing packages in nix profile %s: %w", add, err)
8587
}
8688
}
89+
if len(add) > 0 || len(remove) > 0 {
90+
err := wipeProfileHistory(profilePath)
91+
if err != nil {
92+
// Log the error, but nothing terrible happens if this
93+
// fails.
94+
slog.DebugContext(ctx, "error cleaning up profile history", "err", err)
95+
}
96+
}
97+
return nil
98+
}
99+
100+
// wipeProfileHistory removes all old generations of a Nix profile, similar to
101+
// nix profile wipe-history. profile should be a path to the "default" symlink,
102+
// like .devbox/nix/profile/default.
103+
func wipeProfileHistory(profile string) error {
104+
link, err := os.Readlink(profile)
105+
if errors.Is(err, os.ErrNotExist) {
106+
return nil
107+
}
108+
if err != nil {
109+
return err
110+
}
111+
112+
dir := filepath.Dir(profile)
113+
entries, err := os.ReadDir(dir)
114+
if err != nil {
115+
return err
116+
}
117+
for _, dent := range entries {
118+
if dent.Name() == "default" || dent.Name() == link {
119+
continue
120+
}
121+
err := os.Remove(filepath.Join(dir, dent.Name()))
122+
if err != nil && !errors.Is(err, os.ErrNotExist) {
123+
return err
124+
}
125+
}
87126
return nil
88127
}

0 commit comments

Comments
 (0)