add agentws prune
Agents leave their managed worktrees behind, and `agentws rm` takes one path at a time with no idea whether a branch's work is safely upstream, so clearing an accumulation by hand risks destroying unmerged commits. - classify every managed worktree: dirty, PR open, upstream, or unproven - remove only what is safe; delete the local branch only when work is upstream - prove "upstream" with merge-base and git cherry, so squash merges count - match a PR by head.label, which survives the branch deletion a merge does - dry run by default; --yes applies, --keep-branches spares every branch - read the Gitea path from origin's URL rather than assuming the owner
This commit is contained in:
@@ -13,6 +13,7 @@
|
||||
// agentws new <repo> [--branch benvin/<name>] [--from <base-branch>]
|
||||
// agentws list
|
||||
// agentws rm <path-or-branch> [--delete-branch]
|
||||
// agentws prune [--yes] [--keep-branches]
|
||||
// agentws clean
|
||||
// agentws token
|
||||
// agentws credential get # git credential-helper protocol on stdin
|
||||
@@ -54,6 +55,7 @@ func newRootCmd() *cobra.Command {
|
||||
newNewCmd(),
|
||||
newListCmd(),
|
||||
newRmCmd(),
|
||||
newPruneCmd(),
|
||||
newCleanCmd(),
|
||||
newTokenCmd(),
|
||||
newCredentialCmd(),
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"git.unkin.net/unkin/agent-tools/internal/agent"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Verdicts a worktree can be classified into.
|
||||
const (
|
||||
verdictKeep = "keep"
|
||||
verdictRemove = "remove"
|
||||
verdictRemoveBranch = "remove+branch"
|
||||
)
|
||||
|
||||
// prLister is the slice of the Gitea client prune needs, so tests can drive
|
||||
// classification without a live server.
|
||||
type prLister interface {
|
||||
ListPRs(repoPath, state string) ([]agent.PullRequest, error)
|
||||
}
|
||||
|
||||
type pruneResult struct {
|
||||
wt managedWt
|
||||
verdict string
|
||||
reason string
|
||||
}
|
||||
|
||||
// repoCtx is the per-repo state classification is decided against.
|
||||
type repoCtx struct {
|
||||
srcDir string
|
||||
defBranch string
|
||||
prs map[string]agent.PullRequest
|
||||
prsKnown bool
|
||||
}
|
||||
|
||||
func newPruneCmd() *cobra.Command {
|
||||
var apply, keepBranches bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "prune",
|
||||
Short: "Classify managed worktrees and remove the ones whose work is safely upstream",
|
||||
Long: "prune inspects every managed worktree, classifies it against git and its Gitea\npull request, and removes the ones whose work is provably upstream. It is a dry\nrun unless --yes is given.",
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runPrune(cmd.OutOrStdout(), pruneClient(), apply, keepBranches)
|
||||
},
|
||||
}
|
||||
f := cmd.Flags()
|
||||
f.BoolVar(&apply, "yes", false, "Actually remove worktrees (default is a dry run)")
|
||||
f.BoolVar(&keepBranches, "keep-branches", false, "Never delete a local branch, whatever the classification")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// pruneClient builds a Gitea client, falling back to anonymous access when no
|
||||
// token can be minted; prune degrades to git-only signals if that fails too.
|
||||
func pruneClient() prLister {
|
||||
tok, err := agent.GiteaToken()
|
||||
if err != nil {
|
||||
tok = ""
|
||||
}
|
||||
return agent.NewGiteaClient(tok)
|
||||
}
|
||||
|
||||
func runPrune(out io.Writer, prs prLister, apply, keepBranches bool) error {
|
||||
managed, err := managedWorktrees()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(managed) == 0 {
|
||||
_, _ = fmt.Fprintln(out, "no managed worktrees")
|
||||
return nil
|
||||
}
|
||||
|
||||
byRepo := map[string][]managedWt{}
|
||||
for _, w := range managed {
|
||||
byRepo[w.srcDir] = append(byRepo[w.srcDir], w)
|
||||
}
|
||||
srcDirs := make([]string, 0, len(byRepo))
|
||||
for dir := range byRepo {
|
||||
srcDirs = append(srcDirs, dir)
|
||||
}
|
||||
sort.Strings(srcDirs)
|
||||
|
||||
var results []pruneResult
|
||||
for _, srcDir := range srcDirs {
|
||||
ctx, err := newRepoCtx(out, prs, srcDir)
|
||||
if err != nil {
|
||||
for _, w := range byRepo[srcDir] {
|
||||
results = append(results, pruneResult{wt: w, verdict: verdictKeep, reason: "repo state unknown: " + err.Error()})
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, w := range byRepo[srcDir] {
|
||||
res, err := classify(w, ctx)
|
||||
if err != nil {
|
||||
res = pruneResult{wt: w, verdict: verdictKeep, reason: "inspection failed: " + err.Error()}
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range results {
|
||||
_, _ = fmt.Fprintf(out, "%-44s %-34s %-14s %s\n", filepath.Base(r.wt.path), r.wt.branch, r.verdict, r.reason)
|
||||
}
|
||||
if !apply {
|
||||
_, _ = fmt.Fprintln(out, "dry run: nothing removed (pass --yes to apply)")
|
||||
return nil
|
||||
}
|
||||
|
||||
var errs []error
|
||||
for _, r := range results {
|
||||
if r.verdict == verdictKeep {
|
||||
continue
|
||||
}
|
||||
deleteBranch := r.verdict == verdictRemoveBranch && !keepBranches
|
||||
if err := removeWorktree(out, r.wt, deleteBranch); err != nil {
|
||||
errs = append(errs, fmt.Errorf("%s: %w", r.wt.path, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// newRepoCtx refreshes a source repo and collects the signals prune classifies
|
||||
// against. A failed fetch or an unreachable Gitea is reported and tolerated:
|
||||
// the git-only signals still work offline.
|
||||
func newRepoCtx(out io.Writer, prs prLister, srcDir string) (repoCtx, error) {
|
||||
ctx := repoCtx{srcDir: srcDir, prs: map[string]agent.PullRequest{}}
|
||||
repo := filepath.Base(srcDir)
|
||||
if err := agent.GitFetchPrune(srcDir, "origin", credentialHelperArgs()...); err != nil {
|
||||
_, _ = fmt.Fprintf(out, "warn: fetch %s: %v (using local refs)\n", repo, err)
|
||||
}
|
||||
def, err := agent.GitRemoteDefaultBranch(srcDir, "origin")
|
||||
if err != nil {
|
||||
return repoCtx{}, err
|
||||
}
|
||||
ctx.defBranch = def
|
||||
|
||||
if prs == nil {
|
||||
return ctx, nil
|
||||
}
|
||||
list, err := prs.ListPRs(repoPath(srcDir, repo), "all")
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(out, "warn: list PRs for %s: %v (git signals only)\n", repo, err)
|
||||
return ctx, nil
|
||||
}
|
||||
ctx.prs = prsByBranch(list)
|
||||
ctx.prsKnown = true
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// repoPath is the Gitea "owner/repo" for a checkout, read from origin's URL
|
||||
// because not every managed repo lives under AGENTWS_OWNER.
|
||||
func repoPath(srcDir, repo string) string {
|
||||
url, err := agent.GitRemoteURL(srcDir, "origin")
|
||||
if err == nil && agent.RemoteHost(url) == giteaHost() {
|
||||
if path, err := agent.RepoPathFromRemoteURL(url); err == nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
return owner() + "/" + repo
|
||||
}
|
||||
|
||||
// prsByBranch indexes PRs by head branch, preferring an open PR and otherwise
|
||||
// the most recent one when a branch has been used more than once.
|
||||
func prsByBranch(list []agent.PullRequest) map[string]agent.PullRequest {
|
||||
out := map[string]agent.PullRequest{}
|
||||
for _, pr := range list {
|
||||
branch := agent.PRHeadBranch(pr)
|
||||
if branch == "" {
|
||||
continue
|
||||
}
|
||||
if cur, ok := out[branch]; ok && !supersedes(pr, cur) {
|
||||
continue
|
||||
}
|
||||
out[branch] = pr
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func supersedes(a, b agent.PullRequest) bool {
|
||||
if a.IsOpen() != b.IsOpen() {
|
||||
return a.IsOpen()
|
||||
}
|
||||
if a.Merged != b.Merged {
|
||||
return a.Merged
|
||||
}
|
||||
return a.Number > b.Number
|
||||
}
|
||||
|
||||
// classify applies the prune precedence: dirty and open-PR worktrees are kept,
|
||||
// provably-upstream work loses its branch too, and anything unproven keeps its
|
||||
// branch so no commits become unreachable.
|
||||
func classify(wt managedWt, ctx repoCtx) (pruneResult, error) {
|
||||
res := pruneResult{wt: wt}
|
||||
dirty, err := agent.GitIsDirty(wt.path)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if dirty {
|
||||
res.verdict, res.reason = verdictKeep, "dirty"
|
||||
return res, nil
|
||||
}
|
||||
|
||||
pr, hasPR := ctx.prs[wt.branch]
|
||||
if hasPR && pr.IsOpen() {
|
||||
res.verdict, res.reason = verdictKeep, fmt.Sprintf("PR open #%d", pr.Number)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
upstream := "origin/" + ctx.defBranch
|
||||
contained, err := agent.GitIsAncestor(wt.path, "HEAD", upstream)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if contained {
|
||||
res.verdict, res.reason = verdictRemoveBranch, "contained in "+upstream
|
||||
return res, nil
|
||||
}
|
||||
unmerged, err := agent.GitUnmergedCommits(wt.path, upstream, "HEAD")
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if unmerged == 0 {
|
||||
res.verdict, res.reason = verdictRemoveBranch, "cherry-clean against "+upstream
|
||||
return res, nil
|
||||
}
|
||||
if hasPR && pr.Merged {
|
||||
res.verdict, res.reason = verdictRemoveBranch, fmt.Sprintf("PR merged #%d", pr.Number)
|
||||
return res, nil
|
||||
}
|
||||
if hasPR {
|
||||
if agent.GitRemoteBranchExists(ctx.srcDir, "origin", wt.branch) {
|
||||
res.verdict, res.reason = verdictRemoveBranch, fmt.Sprintf("PR closed #%d, branch on origin", pr.Number)
|
||||
return res, nil
|
||||
}
|
||||
res.verdict, res.reason = verdictRemove, fmt.Sprintf("PR closed #%d, branch gone", pr.Number)
|
||||
return res, nil
|
||||
}
|
||||
res.verdict = verdictRemove
|
||||
res.reason = "no PR"
|
||||
if !ctx.prsKnown {
|
||||
res.reason = "PR state unknown"
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.unkin.net/unkin/agent-tools/internal/agent"
|
||||
)
|
||||
|
||||
// fixture is a bare origin plus a source checkout named "repo" and a worktree
|
||||
// root, wired so managedWorktrees() finds the worktrees created here.
|
||||
type fixture struct {
|
||||
root string
|
||||
bare string
|
||||
srcDir string
|
||||
wtRoot string
|
||||
}
|
||||
|
||||
func git(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %s (in %s): %v: %s", strings.Join(args, " "), dir, err, out)
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
f := &fixture{
|
||||
root: root,
|
||||
bare: filepath.Join(root, "origin.git"),
|
||||
srcDir: filepath.Join(root, "src", "repo"),
|
||||
wtRoot: filepath.Join(root, "worktrees"),
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(root, "src"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(f.wtRoot, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git(t, root, "init", "--bare", "-b", "main", f.bare)
|
||||
|
||||
seed := filepath.Join(root, "seed")
|
||||
git(t, root, "init", "-b", "main", seed)
|
||||
identity(t, seed)
|
||||
writeCommit(t, seed, "README.md", "hi\n", "init")
|
||||
git(t, seed, "remote", "add", "origin", f.bare)
|
||||
git(t, seed, "push", "-u", "origin", "main")
|
||||
|
||||
git(t, filepath.Join(root, "src"), "clone", f.bare, f.srcDir)
|
||||
identity(t, f.srcDir)
|
||||
|
||||
t.Setenv("AGENTWS_ROOT", f.wtRoot)
|
||||
t.Setenv("AGENTWS_SRC_ROOT", filepath.Join(root, "src"))
|
||||
t.Setenv("AGENTWS_OWNER", "unkin")
|
||||
return f
|
||||
}
|
||||
|
||||
func identity(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
git(t, dir, "config", "user.email", "test@example.com")
|
||||
git(t, dir, "config", "user.name", "Test")
|
||||
}
|
||||
|
||||
func writeCommit(t *testing.T, dir, name, content, msg string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git(t, dir, "add", ".")
|
||||
git(t, dir, "commit", "-m", msg)
|
||||
}
|
||||
|
||||
// addWorktree creates a managed worktree for branch and returns its path.
|
||||
func (f *fixture) addWorktree(t *testing.T, branch string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(f.wtRoot, agent.WorktreeDirName("repo", branch))
|
||||
git(t, f.srcDir, "worktree", "add", path, "-b", branch, "origin/main")
|
||||
identity(t, path)
|
||||
return path
|
||||
}
|
||||
|
||||
// landUpstream commits content on origin's main, mimicking a squash merge: the
|
||||
// same patch arrives upstream under a different SHA.
|
||||
func (f *fixture) landUpstream(t *testing.T, name, content, msg string) {
|
||||
t.Helper()
|
||||
seed := filepath.Join(f.root, "seed")
|
||||
git(t, seed, "pull", "--ff-only", "origin", "main")
|
||||
writeCommit(t, seed, name, content, msg)
|
||||
git(t, seed, "push", "origin", "main")
|
||||
}
|
||||
|
||||
// fakeGitea serves the pulls listing for unkin/repo with the given PR bodies.
|
||||
func fakeGitea(t *testing.T, prs ...map[string]any) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("page") != "1" {
|
||||
_, _ = w.Write([]byte("[]"))
|
||||
return
|
||||
}
|
||||
body, err := json.Marshal(prs)
|
||||
if err != nil {
|
||||
t.Errorf("marshal PRs: %v", err)
|
||||
}
|
||||
_, _ = w.Write(body)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func client(srv *httptest.Server) prLister {
|
||||
return &agent.GiteaClient{BaseURL: srv.URL, HTTP: srv.Client()}
|
||||
}
|
||||
|
||||
// mergedPR mimics Gitea after a merge: the branch is deleted, so head.ref
|
||||
// becomes refs/pull/<n>/head and only head.label still names the branch.
|
||||
func mergedPR(number int, branch string) map[string]any {
|
||||
return map[string]any{
|
||||
"number": number,
|
||||
"state": "closed",
|
||||
"merged": true,
|
||||
"head": map[string]any{
|
||||
"ref": "refs/pull/" + strconv.Itoa(number) + "/head",
|
||||
"label": branch,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func openPR(number int, branch string) map[string]any {
|
||||
return map[string]any{
|
||||
"number": number,
|
||||
"state": "open",
|
||||
"merged": false,
|
||||
"head": map[string]any{"ref": branch, "label": branch},
|
||||
}
|
||||
}
|
||||
|
||||
func closedPR(number int, branch string) map[string]any {
|
||||
return map[string]any{
|
||||
"number": number,
|
||||
"state": "closed",
|
||||
"merged": false,
|
||||
"head": map[string]any{"ref": branch, "label": branch},
|
||||
}
|
||||
}
|
||||
|
||||
func run(t *testing.T, prs prLister, apply, keepBranches bool) string {
|
||||
t.Helper()
|
||||
var out bytes.Buffer
|
||||
if err := runPrune(&out, prs, apply, keepBranches); err != nil {
|
||||
t.Fatalf("runPrune: %v\n%s", err, out.String())
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func lineFor(t *testing.T, out, branch string) string {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if strings.Contains(line, " "+branch+" ") {
|
||||
return line
|
||||
}
|
||||
}
|
||||
t.Fatalf("no line for branch %q in:\n%s", branch, out)
|
||||
return ""
|
||||
}
|
||||
|
||||
func assertVerdict(t *testing.T, out, branch, verdict, reason string) {
|
||||
t.Helper()
|
||||
line := lineFor(t, out, branch)
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 3 || fields[2] != verdict {
|
||||
t.Errorf("branch %s: verdict line %q, want verdict %q", branch, line, verdict)
|
||||
}
|
||||
if reason != "" && !strings.Contains(line, reason) {
|
||||
t.Errorf("branch %s: line %q, want reason containing %q", branch, line, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// A merged PR's branch is deleted on merge, so its head.ref reads
|
||||
// refs/pull/<n>/head; classification must still see the merge (via head.label)
|
||||
// and remove the branch, not fall through to "no PR".
|
||||
func TestPruneMergedPRWithDeletedBranch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/merged")
|
||||
writeCommit(t, wt, "m.txt", "m\n", "work")
|
||||
|
||||
srv := fakeGitea(t, mergedPR(3, "benvin/merged"))
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/merged", verdictRemoveBranch, "PR merged #3")
|
||||
|
||||
if exists(wt) {
|
||||
t.Errorf("worktree %s should have been removed", wt)
|
||||
}
|
||||
if agent.GitBranchExists(f.srcDir, "benvin/merged") {
|
||||
t.Error("branch of a merged PR should be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// The same PR without head.label: matching falls back to head.ref, which no
|
||||
// longer names the branch, so prune must not guess it is merged — the worktree
|
||||
// goes but the branch stays.
|
||||
func TestPruneMergedPRWithoutLabelKeepsBranch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/merged")
|
||||
writeCommit(t, wt, "m.txt", "m\n", "work")
|
||||
|
||||
pr := mergedPR(3, "benvin/merged")
|
||||
pr["head"].(map[string]any)["label"] = ""
|
||||
srv := fakeGitea(t, pr)
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/merged", verdictRemove, "no PR")
|
||||
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/merged") {
|
||||
t.Error("branch must survive when the PR could not be matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPruneContainedBranch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/contained")
|
||||
|
||||
srv := fakeGitea(t)
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained in origin/main")
|
||||
|
||||
if exists(wt) {
|
||||
t.Error("contained worktree should have been removed")
|
||||
}
|
||||
if agent.GitBranchExists(f.srcDir, "benvin/contained") {
|
||||
t.Error("contained branch should be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// Squash-merged work keeps a local SHA that is not upstream, so only the
|
||||
// patch-equivalence check proves it landed.
|
||||
func TestPruneCherryCleanBranch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/squashed")
|
||||
writeCommit(t, wt, "s.txt", "same\n", "add s")
|
||||
f.landUpstream(t, "s.txt", "same\n", "squashed s")
|
||||
|
||||
srv := fakeGitea(t)
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/squashed", verdictRemoveBranch, "cherry-clean")
|
||||
|
||||
if agent.GitBranchExists(f.srcDir, "benvin/squashed") {
|
||||
t.Error("cherry-clean branch should be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// Uncommitted work outranks every other signal, including a branch that is
|
||||
// otherwise fully contained upstream.
|
||||
func TestPruneNeverTouchesDirtyWorktree(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/dirty")
|
||||
if err := os.WriteFile(filepath.Join(wt, "wip.txt"), []byte("wip\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := fakeGitea(t, mergedPR(4, "benvin/dirty"))
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/dirty", verdictKeep, "dirty")
|
||||
|
||||
if !exists(wt) {
|
||||
t.Error("dirty worktree must not be removed")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/dirty") {
|
||||
t.Error("dirty worktree's branch must survive")
|
||||
}
|
||||
}
|
||||
|
||||
// An open PR is kept even when its commits are already upstream.
|
||||
func TestPruneKeepsOpenPR(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/open")
|
||||
|
||||
srv := fakeGitea(t, openPR(5, "benvin/open"))
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/open", verdictKeep, "PR open #5")
|
||||
|
||||
if !exists(wt) {
|
||||
t.Error("worktree with an open PR must not be removed")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/open") {
|
||||
t.Error("branch with an open PR must not be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// Closed-unmerged with the branch still on origin: the work is not lost, so the
|
||||
// local branch goes too.
|
||||
func TestPruneClosedPRWithBranchOnOrigin(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/closed")
|
||||
writeCommit(t, wt, "c.txt", "c\n", "work")
|
||||
git(t, wt, "push", "origin", "benvin/closed")
|
||||
|
||||
srv := fakeGitea(t, closedPR(6, "benvin/closed"))
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/closed", verdictRemoveBranch, "PR closed #6, branch on origin")
|
||||
|
||||
if exists(wt) {
|
||||
t.Error("worktree should have been removed")
|
||||
}
|
||||
if agent.GitBranchExists(f.srcDir, "benvin/closed") {
|
||||
t.Error("branch should be deleted while origin still has it")
|
||||
}
|
||||
}
|
||||
|
||||
// Closed-unmerged with nothing on origin: the commits exist only here, so the
|
||||
// branch is kept and only the worktree goes.
|
||||
func TestPruneClosedPRWithBranchGone(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/orphan")
|
||||
writeCommit(t, wt, "o.txt", "o\n", "work")
|
||||
|
||||
srv := fakeGitea(t, closedPR(7, "benvin/orphan"))
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/orphan", verdictRemove, "PR closed #7, branch gone")
|
||||
|
||||
if exists(wt) {
|
||||
t.Error("worktree should have been removed")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/orphan") {
|
||||
t.Error("branch must survive when origin does not have the commits")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPruneNoPRKeepsBranch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/unpushed")
|
||||
writeCommit(t, wt, "u.txt", "u\n", "work")
|
||||
|
||||
srv := fakeGitea(t)
|
||||
out := run(t, client(srv), true, false)
|
||||
assertVerdict(t, out, "benvin/unpushed", verdictRemove, "no PR")
|
||||
|
||||
if exists(wt) {
|
||||
t.Error("worktree should have been removed")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/unpushed") {
|
||||
t.Error("branch with unproven work must survive")
|
||||
}
|
||||
}
|
||||
|
||||
// The default run reports and changes nothing.
|
||||
func TestPruneDryRunChangesNothing(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
contained := f.addWorktree(t, "benvin/contained")
|
||||
merged := f.addWorktree(t, "benvin/merged")
|
||||
writeCommit(t, merged, "m.txt", "m\n", "work")
|
||||
|
||||
srv := fakeGitea(t, mergedPR(8, "benvin/merged"))
|
||||
out := run(t, client(srv), false, false)
|
||||
|
||||
if !strings.Contains(out, "dry run") {
|
||||
t.Errorf("dry-run output should say so:\n%s", out)
|
||||
}
|
||||
assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained")
|
||||
assertVerdict(t, out, "benvin/merged", verdictRemoveBranch, "PR merged #8")
|
||||
if !exists(contained) || !exists(merged) {
|
||||
t.Error("dry run must not remove worktrees")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/contained") || !agent.GitBranchExists(f.srcDir, "benvin/merged") {
|
||||
t.Error("dry run must not delete branches")
|
||||
}
|
||||
}
|
||||
|
||||
// --keep-branches removes worktrees but leaves every branch alone.
|
||||
func TestPruneKeepBranches(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
wt := f.addWorktree(t, "benvin/contained")
|
||||
|
||||
srv := fakeGitea(t)
|
||||
out := run(t, client(srv), true, true)
|
||||
assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained")
|
||||
|
||||
if exists(wt) {
|
||||
t.Error("worktree should have been removed")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/contained") {
|
||||
t.Error("--keep-branches must not delete the branch")
|
||||
}
|
||||
}
|
||||
|
||||
// With Gitea unreachable prune falls back to the git signals: provably-upstream
|
||||
// work is still cleaned up, and anything unproven keeps its branch.
|
||||
func TestPruneDegradesWhenGiteaUnreachable(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
contained := f.addWorktree(t, "benvin/contained")
|
||||
unproven := f.addWorktree(t, "benvin/unproven")
|
||||
writeCommit(t, unproven, "u.txt", "u\n", "work")
|
||||
|
||||
dead := httptest.NewServer(http.NewServeMux())
|
||||
c := &agent.GiteaClient{BaseURL: dead.URL, HTTP: dead.Client()}
|
||||
dead.Close()
|
||||
|
||||
out := run(t, c, true, false)
|
||||
if !strings.Contains(out, "git signals only") {
|
||||
t.Errorf("output should note the Gitea failure:\n%s", out)
|
||||
}
|
||||
assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained")
|
||||
assertVerdict(t, out, "benvin/unproven", verdictRemove, "PR state unknown")
|
||||
|
||||
if exists(contained) || exists(unproven) {
|
||||
t.Error("both worktrees should have been removed")
|
||||
}
|
||||
if agent.GitBranchExists(f.srcDir, "benvin/contained") {
|
||||
t.Error("contained branch is safe to delete without Gitea")
|
||||
}
|
||||
if !agent.GitBranchExists(f.srcDir, "benvin/unproven") {
|
||||
t.Error("unproven branch must survive an unreachable Gitea")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPruneNoWorktrees(t *testing.T) {
|
||||
newFixture(t)
|
||||
srv := fakeGitea(t)
|
||||
if out := run(t, client(srv), true, false); !strings.Contains(out, "no managed worktrees") {
|
||||
t.Errorf("output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// Managed repos are not all under AGENTWS_OWNER, so the Gitea path comes from
|
||||
// origin's URL; a non-Gitea remote falls back to the configured owner.
|
||||
func TestRepoPathFollowsOrigin(t *testing.T) {
|
||||
t.Setenv("AGENTWS_OWNER", "unkin")
|
||||
dir := t.TempDir()
|
||||
git(t, dir, "init", "-b", "main", ".")
|
||||
git(t, dir, "remote", "add", "origin", "https://git.unkin.net/unkinben/dotfiles.git")
|
||||
if got := repoPath(dir, "dotfiles"); got != "unkinben/dotfiles" {
|
||||
t.Errorf("repoPath = %q, want unkinben/dotfiles", got)
|
||||
}
|
||||
git(t, dir, "remote", "set-url", "origin", filepath.Join(dir, "origin.git"))
|
||||
if got := repoPath(dir, "dotfiles"); got != "unkin/dotfiles" {
|
||||
t.Errorf("repoPath for a local remote = %q, want unkin/dotfiles", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user