package roots import ( "context" "errors" "fmt" "io/fs" "os" "os/exec" "regexp" "strconv" "strings" ) type Result struct { Link string `json:"link"` Target string `json:"target,omitempty"` Action string `json:"action"` Err string `json:"error,omitempty"` } func (r Result) OK() bool { return r.Err == "" } type DeleteOpts struct { DryRun bool // Force allows deleting protected roots (current generations, // current-system/booted-system). Force bool } // Delete removes the given roots. It only ever removes symlinks (or calls // nix-env for profile generations); nothing inside the store is touched. func Delete(ctx context.Context, cfg Config, rs []Root, opts DeleteOpts) []Result { res := make([]Result, 0, len(rs)) for _, r := range rs { res = append(res, deleteOne(ctx, cfg, r, opts)) } return res } func deleteOne(ctx context.Context, cfg Config, r Root, opts DeleteOpts) Result { res := Result{Link: r.Link, Target: r.Target} fail := func(err error) Result { res.Err = err.Error() if errors.Is(err, fs.ErrPermission) { res.Err += " (root-owned? rerun with sudo)" } return res } if !r.Deletable() { res.Action = "skip" return fail(errors.New("runtime roots are held by running processes and cannot be deleted")) } if r.Protected && !opts.Force { res.Action = "skip" return fail(fmt.Errorf("protected: %s", r.Reason)) } switch r.Kind { case KindProfile: gen := strconv.Itoa(r.Generation) res.Action = fmt.Sprintf("nix-env --profile %s --delete-generations %s", r.Profile, gen) if r.Current { // nix-env refuses to delete the current generation; with --force // fall back to removing the link itself. res.Action = "rm " + r.Link if opts.DryRun { return res } return orFail(res, removeSymlink(cfg, r.Link, true), fail) } if opts.DryRun { return res } out, err := exec.CommandContext(ctx, cfg.NixEnvBin, "--profile", r.Profile, "--delete-generations", gen).CombinedOutput() if err != nil { msg := strings.TrimSpace(string(out)) if msg == "" { msg = err.Error() } if strings.Contains(msg, "Permission denied") { msg += " (rerun with sudo)" } res.Err = msg } return res case KindDangling: res.Action = "rm " + r.Via if opts.DryRun { return res } return orFail(res, removeSymlink(cfg, r.Via, false), fail) case KindIndirect: if r.Target == "" { res.Action = "skip" return fail(fmt.Errorf("cannot inspect %s: %s", r.Link, r.Reason)) } res.Action = "rm " + r.Link if opts.DryRun { return res } if err := removeSymlink(cfg, r.Link, true); err != nil { return fail(err) } // The auto/ entry is now stale; nix-store --gc prunes it, but tidy it // up right away if we are allowed to. if r.Via != "" { _ = removeSymlink(cfg, r.Via, false) } return res default: // KindDirect res.Action = "rm " + r.Link if opts.DryRun { return res } return orFail(res, removeSymlink(cfg, r.Link, false), fail) } } func orFail(res Result, err error, fail func(error) Result) Result { if err != nil { return fail(err) } return res } // removeSymlink removes p after checking it is a symlink and, if // mustPointToStore, that it points into the store. func removeSymlink(cfg Config, p string, mustPointToStore bool) error { if cfg.inStore(p) || p == cfg.StoreDir { return fmt.Errorf("refusing to remove %s: inside the store", p) } st, err := os.Lstat(p) if err != nil { return err } if st.Mode()&fs.ModeSymlink == 0 { return fmt.Errorf("refusing to remove %s: not a symlink", p) } if mustPointToStore { t, err := os.Readlink(p) if err != nil { return err } if !cfg.inStore(t) { return fmt.Errorf("refusing to remove %s: points to %s, not the store", p, t) } } return os.Remove(p) } var freedRe = regexp.MustCompile(`(\d+) store paths deleted, ([0-9.]+ \w+) freed`) // GC runs nix-store --gc and returns its summary line. func GC(ctx context.Context, cfg Config) (string, error) { out, err := exec.CommandContext(ctx, cfg.NixStoreBin, "--gc").CombinedOutput() if m := freedRe.FindString(string(out)); m != "" { return m, err } lines := strings.Split(strings.TrimSpace(string(out)), "\n") last := lines[len(lines)-1] if err != nil { return "", fmt.Errorf("nix-store --gc: %v: %s", err, last) } return last, nil }