Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/conch/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/Amitgb14/conch/internal/client"
"github.com/Amitgb14/conch/internal/config"
"github.com/Amitgb14/conch/internal/gitx"
"github.com/Amitgb14/conch/internal/proto"
)

Expand Down Expand Up @@ -470,6 +471,8 @@ func worktreeLabel(w proto.StaleWorktree) string {
// why it looks finished.
func worktreeState(w proto.StaleWorktree) string {
switch {
case w.Operation != "":
return gitx.OperationWord(w.Operation)
case w.Panes:
return "panes running"
case w.Locked:
Expand Down
26 changes: 26 additions & 0 deletions cmd/conch/worktreestate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"testing"

"github.com/Amitgb14/conch/internal/proto"
)

// conch worktree ls says a worktree mid-rebase is rebasing, before
// anything else about it, and names the branch the rebase is rewriting.
func TestWorktreeStateSaysRebasing(t *testing.T) {
w := proto.StaleWorktree{Path: "/r/feat", Branch: "feat", Operation: "rebase", Panes: true}
if got := worktreeState(w); got != "rebasing" {
t.Fatalf("state: %q", got)
}
if got := worktreeLabel(w); got != "feat" {
t.Fatalf("label: %q", got)
}
w.Operation = ""
if got := worktreeState(w); got != "panes running" {
t.Fatalf("no operation: %q", got)
}
if got := worktreeLabel(proto.StaleWorktree{Path: "/r/x"}); got != "(detached)" {
t.Fatalf("detached: %q", got)
}
}
66 changes: 48 additions & 18 deletions internal/gitx/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,45 +105,75 @@ func gitDir(ctx context.Context, dir string) (string, bool) {
// rewriting, or "". git detaches HEAD while it works, so the worktree list
// shows no branch there until the rebase ends.
func RebasingBranch(ctx context.Context, dir string) string {
gd, ok := gitDir(ctx, dir)
if !ok {
return ""
}
for _, d := range []string{"rebase-merge", "rebase-apply"} {
if b, err := os.ReadFile(filepath.Join(gd, d, "head-name")); err == nil {
return strings.TrimPrefix(strings.TrimSpace(string(b)), "refs/heads/")
}
}
return ""
_, branch := Operation(ctx, dir)
return branch
}

// InProgress names the operation left unfinished in the checkout at dir —
// "rebase", "merge", "cherry-pick", "revert" or "am" — or "" when there is
// none. Each worktree has its own, so a conflict in one doesn't show in
// the others.
func InProgress(ctx context.Context, dir string) string {
op, _ := Operation(ctx, dir)
return op
}

// OperationWord says what Operation found as a person reads it beside a
// branch: "rebasing" for "rebase".
func OperationWord(op string) string {
switch op {
case "rebase":
return "rebasing"
case "merge":
return "merging"
case "cherry-pick":
return "cherry-picking"
case "revert":
return "reverting"
case "am":
return "applying patches"
}
return op
}

// Operation is InProgress and, for a rebase, the branch it is rewriting,
// read with one call to git. The branch is "" for anything but a rebase of
// a branch: an am also keeps rebase-apply, and a rebase of a detached HEAD
// writes "detached HEAD" where a branch's name would be.
func Operation(ctx context.Context, dir string) (op, branch string) {
gd, ok := gitDir(ctx, dir)
if !ok {
return ""
return "", ""
}
has := func(name string) bool {
_, err := os.Stat(filepath.Join(gd, name))
return err == nil
}
headName := func(d string) string {
b, err := os.ReadFile(filepath.Join(gd, d, "head-name"))
if err != nil {
return ""
}
name, ok := strings.CutPrefix(strings.TrimSpace(string(b)), "refs/heads/")
if !ok {
return ""
}
return name
}
switch {
case has("rebase-merge"):
return "rebase"
return "rebase", headName("rebase-merge")
case has("rebase-apply"):
if has("rebase-apply/applying") {
return "am"
return "am", ""
}
return "rebase"
return "rebase", headName("rebase-apply")
case has("MERGE_HEAD"):
return "merge"
return "merge", ""
case has("CHERRY_PICK_HEAD"):
return "cherry-pick"
return "cherry-pick", ""
case has("REVERT_HEAD"):
return "revert"
return "revert", ""
}
return ""
return "", ""
}
113 changes: 113 additions & 0 deletions internal/gitx/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package gitx
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -182,3 +184,114 @@ func TestInProgress(t *testing.T) {
t.Fatalf("missing dir: %q", got)
}
}

// stuckRebase leaves the checkout at dir mid-rebase onto onto, stopped on
// a conflict, with the extra arguments given to git rebase.
func stuckRebase(t *testing.T, dir, onto string, args ...string) {
t.Helper()
argv := append(append([]string{"rebase"}, args...), onto)
if _, code, _, _ := RunUser(ctx, dir, argv, 1<<16); code == 0 {
t.Fatalf("git %v didn't conflict", argv)
}
}

func TestOperation(t *testing.T) {
t.Run("linked worktree, each backend", func(t *testing.T) {
for _, args := range [][]string{nil, {"-i"}, {"--apply"}} {
root, wt := taskRepo(t)
commit(t, root, "README.md", "hello\nfrom main\n", "main edit")
commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit")
if len(args) > 0 && args[0] == "-i" {
t.Setenv("GIT_SEQUENCE_EDITOR", "true") // take the todo list as it is
}
stuckRebase(t, wt, "main", args...)
if op, b := Operation(ctx, wt); op != "rebase" || b != "feat" {
t.Fatalf("rebase %v: %q %q", args, op, b)
}
// The main checkout is not the one rebasing.
if op, b := Operation(ctx, root); op != "" || b != "" {
t.Fatalf("main checkout during rebase %v: %q %q", args, op, b)
}
git(t, wt, "rebase", "--abort")
if op, b := Operation(ctx, wt); op != "" || b != "" {
t.Fatalf("after aborting %v: %q %q", args, op, b)
}
}
})

t.Run("main checkout", func(t *testing.T) {
root := newRepo(t)
git(t, root, "checkout", "-q", "-b", "side")
commit(t, root, "README.md", "hello\nfrom side\n", "side edit")
git(t, root, "checkout", "-q", "main")
commit(t, root, "README.md", "hello\nfrom main\n", "main edit")
stuckRebase(t, root, "side")
if op, b := Operation(ctx, root); op != "rebase" || b != "main" {
t.Fatalf("main checkout rebasing: %q %q", op, b)
}
})

t.Run("detached HEAD rebased", func(t *testing.T) {
root, wt := taskRepo(t)
commit(t, root, "README.md", "hello\nfrom main\n", "main edit")
commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit")
git(t, wt, "checkout", "-q", "--detach")
stuckRebase(t, wt, "main")
// git writes "detached HEAD" where a branch would be: no branch.
if op, b := Operation(ctx, wt); op != "rebase" || b != "" {
t.Fatalf("detached rebase: %q %q", op, b)
}
})

t.Run("head-name missing or empty", func(t *testing.T) {
root, wt := taskRepo(t)
commit(t, root, "README.md", "hello\nfrom main\n", "main edit")
commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit")
stuckRebase(t, wt, "main")
gd := git(t, wt, "rev-parse", "--absolute-git-dir")
name := filepath.Join(gd, "rebase-merge", "head-name")
if err := os.WriteFile(name, nil, 0o644); err != nil {
t.Fatal(err)
}
if op, b := Operation(ctx, wt); op != "rebase" || b != "" {
t.Fatalf("empty head-name: %q %q", op, b)
}
if err := os.Remove(name); err != nil {
t.Fatal(err)
}
if op, b := Operation(ctx, wt); op != "rebase" || b != "" {
t.Fatalf("no head-name: %q %q", op, b)
}
})

t.Run("am is not a rebase", func(t *testing.T) {
root, wt := taskRepo(t)
commit(t, root, "README.md", "hello\nfrom main\n", "main edit")
patch := filepath.Join(t.TempDir(), "p.patch")
write(t, filepath.Dir(patch), "p.patch", git(t, root, "format-patch", "-1", "--stdout")+"\n")
commit(t, wt, "README.md", "hello\nfrom feat\n", "feat edit")
if _, code, _, _ := RunUser(ctx, wt, []string{"am", patch}, 1<<16); code == 0 {
t.Fatal("am didn't conflict")
}
if op, b := Operation(ctx, wt); op != "am" || b != "" {
t.Fatalf("am: %q %q", op, b)
}
})

t.Run("not a repository", func(t *testing.T) {
if op, b := Operation(ctx, t.TempDir()); op != "" || b != "" {
t.Fatalf("plain folder: %q %q", op, b)
}
})
}

func TestOperationWord(t *testing.T) {
for op, want := range map[string]string{
"rebase": "rebasing", "merge": "merging", "cherry-pick": "cherry-picking",
"revert": "reverting", "am": "applying patches", "bisect": "bisect", "": "",
} {
if got := OperationWord(op); got != want {
t.Errorf("%q: %q, want %q", op, got, want)
}
}
}
17 changes: 16 additions & 1 deletion internal/proto/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const ProtocolVersion = 1
var Capabilities = []string{
"pane.v1", "pane.frame.v1", "events.v1", "agent.v1",
"project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1",
"agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged,
"agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged, CapWorktreeOperation,
}

// The tiers an agent can be in, as agent.list reports them. They are in
Expand Down Expand Up @@ -258,6 +258,11 @@ const CapAgentAttach = "agent.attach.v1"
// or too-big, with a comment saying why.
const CapAutopilotTriage = "autopilot.triage.v1"

// CapWorktreeOperation is WorktreeInfo.Operation, and a worktree mid-rebase
// carrying the branch being rebased as its Branch: git detaches HEAD until
// the rebase ends, and the agents in it showed under no branch.
const CapWorktreeOperation = "worktree.operation.v1"

// CapBranchPrune is branch.stale and branch.prune: local branches nobody
// has committed to for a while, and deleting them.
const CapBranchPrune = "branch.prune.v1"
Expand Down Expand Up @@ -978,6 +983,12 @@ type WorktreeInfo struct {
// servers, and Conflicts where git is older than 2.38.
Overlaps []Overlap `json:"overlaps,omitempty"`
Conflicts []string `json:"conflicts,omitempty"`
// Operation is what git left unfinished here: "rebase", "merge",
// "cherry-pick", "revert" or "am". Mid-rebase, Branch is the branch
// being rebased while Detached stays true, since HEAD is: a client
// shows the checkout under that branch. Absent from older servers
// (CapWorktreeOperation).
Operation string `json:"operation,omitempty"`
}

// Overlap is another branch's checkout touching the same files.
Expand Down Expand Up @@ -1906,6 +1917,10 @@ type StaleWorktree struct {
// Suggested means it can go without losing anything.
Reasons []string `json:"reasons,omitempty"`
Suggested bool `json:"suggested,omitempty"`
// Operation is what git left unfinished in it ("rebase", "merge"…), as
// in WorktreeInfo: such a worktree is never suggested, and mid-rebase
// Branch is the branch being rebased (CapWorktreeOperation).
Operation string `json:"operation,omitempty"`
}

// WorktreeCleanupParams removes linked worktrees, deleting their branches
Expand Down
21 changes: 20 additions & 1 deletion internal/server/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto
if b, known := branches[wt.Branch]; known {
sw.Gone, sw.Committed, sw.PR = b.Gone, b.Committed, b.PR
}
if !sw.Missing {
// Mid-rebase, git has detached HEAD; the rebase still names
// the branch, and the worktree is anything but finished.
op, rebasing := gitx.Operation(ctx, wt.Path)
sw.Operation = op
if wt.Branch == "" && rebasing != "" {
sw.Branch = rebasing
}
}
readable := true
if !sw.Missing {
sw.Panes = pm.s.panesIn(wt.Path)
Expand All @@ -66,6 +75,7 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto
note("folder gone")
}
switch {
case sw.Operation != "":
case wt.Branch == "":
note("detached")
case sw.Base:
Expand All @@ -82,7 +92,7 @@ func (pm *projectManager) staleWorktrees(id string) (proto.WorktreeStale, *proto
if sw.Gone {
note("upstream deleted")
}
sw.Suggested = finished && readable && !sw.Base && !sw.Locked && !sw.Panes && sw.Uncommitted == 0 && sw.Unmerged == 0
sw.Suggested = finished && readable && sw.Operation == "" && !sw.Base && !sw.Locked && !sw.Panes && sw.Uncommitted == 0 && sw.Unmerged == 0
out.Worktrees = append(out.Worktrees, sw)
}
return out, nil
Expand Down Expand Up @@ -136,6 +146,10 @@ func (pm *projectManager) cleanupWorktrees(cp proto.WorktreeCleanupParams) (prot
fail(item.Path, "panes are still running in it")
continue
}
if op := gitx.InProgress(ctx, wt.Path); op != "" && !item.Force {
fail(item.Path, "a %s is in progress in it; finish or abort it first", op)
continue
}
branch := wt.Branch
if branch == base {
branch = "" // the base branch stays
Expand Down Expand Up @@ -274,6 +288,11 @@ func checkedOutBranches(ctx context.Context, root string) (map[string]string, *p
for _, wt := range wts {
if wt.Branch != "" {
at[wt.Branch] = wt.Path
} else if wt.Detached && !wt.Prunable {
// A branch being rebased is as checked out as any other.
if b := gitx.RebasingBranch(ctx, wt.Path); b != "" {
at[b] = wt.Path
}
}
}
return at, nil
Expand Down
Loading
Loading