1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
package main
import (
"context"
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
)
// enrichLocalBranchesWithParentInfo performs the core 4-phase enrichment algorithm
// on local branches using all branches (local + remote) for context.
// This is the shared logic used by both TUI and JSON output modes.
// If skipPatchIds is true, PHASE 2 & 3 (expensive patch-id calculation) are skipped for faster startup.
func enrichLocalBranchesWithParentInfo(ctx context.Context, localBranches []BranchInfo, allBranches []BranchInfo, skipPatchIds bool) []BranchInfo {
if len(localBranches) == 0 {
return localBranches
}
// Build branch tips index from ALL branches (local + remote)
// This allows detecting parents that point to remote branches
branchTips := buildBranchTipsIndex(ctx, allBranches)
// Find base branch (skip it from parent detection)
baseBranch := findBaseBranch(localBranches)
enrichedBranches := make([]BranchInfo, len(localBranches))
copy(enrichedBranches, localBranches)
// PHASE 1: Find natural parents for local branches (using merge-base with trunk)
for i := range enrichedBranches {
if enrichedBranches[i].Name == baseBranch {
continue // Skip base branch
}
parent, err := detectParents(ctx, enrichedBranches[i], allBranches, branchTips)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error detecting parent for %s: %v\n", enrichedBranches[i].Name, err)
continue
}
if parent != nil {
enrichedBranches[i].ParentCandidates = []ParentCandidate{*parent}
// Calculate ahead/behind
if parent.CommonAncestor != "" {
commits, _ := getMissingCommits(ctx, parent.CommonAncestor, enrichedBranches[i].CurrentCommit)
enrichedBranches[i].CommitsAhead = len(commits)
enrichedBranches[i].CommitsBehind = 0 // Found parent's tip in our ancestry
}
}
}
// PHASE 2 & 3: Calculate patch-ids and find related branches (can be skipped for faster startup)
if !skipPatchIds {
// PHASE 2: Calculate patch-ids for all branches using divergence points
branchPatchIds := make(map[string][]string)
for i := range enrichedBranches {
if enrichedBranches[i].Name == baseBranch {
continue // Skip base branch
}
// Get divergence commit from parent (if any)
divergenceCommit := ""
branchType := "orphan"
if len(enrichedBranches[i].ParentCandidates) > 0 {
divergenceCommit = enrichedBranches[i].ParentCandidates[0].CommonAncestor
branchType = "with parent"
}
// Calculate patch-ids (10 max, from divergence or last 10)
patchIds, err := calculateBranchPatchIds(ctx, enrichedBranches[i].Name, divergenceCommit)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: skipping patch-id calculation for '%s' (%s): %v\n",
enrichedBranches[i].Name, branchType, err)
continue
}
if len(patchIds) > 0 {
branchPatchIds[enrichedBranches[i].Name] = patchIds
}
}
// PHASE 3: Build patch-id index and find related branches
if len(branchPatchIds) > 0 {
patchIdIndex := buildPatchIdIndexFromBranches(ctx, branchPatchIds)
for i := range enrichedBranches {
if enrichedBranches[i].Name == baseBranch {
continue
}
targetPatchIds, ok := branchPatchIds[enrichedBranches[i].Name]
if !ok {
continue
}
relatedBranches := detectRelatedBranches(
ctx,
enrichedBranches[i].Name,
targetPatchIds,
patchIdIndex,
branchPatchIds,
allBranches,
)
enrichedBranches[i].PrefixShared = relatedBranches
}
}
}
// PHASE 4: Detect remote counterparts and commit differences
enrichRemoteTrackingInfo(ctx, enrichedBranches, allBranches)
return enrichedBranches
}
// enrichBranchesWithParents adds parent detection to all branches
// Uses the shared enrichLocalBranchesWithParentInfo function
// Skips expensive patch-id calculation (PHASE 2 & 3) for faster startup
func enrichBranchesWithParents(ctx context.Context, branches []BranchInfo) tea.Cmd {
return func() tea.Msg {
if len(branches) == 0 {
return branchesEnrichedMsg{branches: branches}
}
// Separate local and remote branches
// We only enrich local branches, but use remote branches for parent detection
var localBranches []BranchInfo
for _, branch := range branches {
if !branch.IsRemote {
localBranches = append(localBranches, branch)
}
}
// Perform the core enrichment, skipping expensive patch-id phases
enrichedBranches := enrichLocalBranchesWithParentInfo(ctx, localBranches, branches, true)
// Fetch stashes once for all branches
stashMap, err := getStashes(ctx)
if err != nil {
// Log error but continue without stash info
fmt.Fprintf(os.Stderr, "Warning: error getting stashes: %v\n", err)
} else {
// Count stashes for each branch based on last 10 commits
for i := range enrichedBranches {
recentCommits, err := getRecentCommits(ctx, enrichedBranches[i].Name, 10)
if err != nil {
continue
}
stashCount := 0
for _, commit := range recentCommits {
if stashes, ok := stashMap[commit.Hash]; ok {
stashCount += len(stashes)
}
}
enrichedBranches[i].StashCount = stashCount
}
}
return branchesEnrichedMsg{branches: enrichedBranches}
}
}
// enrichRemoteTrackingInfo detects remote counterparts and calculates ahead/behind statistics
// for local branches by comparing them against their remote counterparts in the branches list
func enrichRemoteTrackingInfo(ctx context.Context, localBranches []BranchInfo, allBranches []BranchInfo) {
for i := range localBranches {
// Find remote counterpart (e.g., origin/feature-branch)
remoteBranch := findRemoteCounterpart(localBranches[i].Name, allBranches)
if remoteBranch == nil {
continue // No remote counterpart found
}
localBranches[i].RemoteCounterpart = remoteBranch.Name
// Get commits missing from remote (local commits not in remote)
missingFromRemote, err := getMissingCommits(ctx, localBranches[i].CurrentCommit, remoteBranch.CurrentCommit)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error getting missing commits for %s: %v\n", localBranches[i].Name, err)
continue
}
localBranches[i].CommitsMissingFromRemote = missingFromRemote
// Get commits missing from local (remote commits not in local)
missingFromLocal, err := getMissingCommits(ctx, remoteBranch.CurrentCommit, localBranches[i].CurrentCommit)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error getting missing commits from remote for %s: %v\n", localBranches[i].Name, err)
continue
}
localBranches[i].CommitsMissingFromLocal = missingFromLocal
// Update ahead/behind counts based on remote tracking
localBranches[i].CommitsAhead = len(missingFromRemote)
localBranches[i].CommitsBehind = len(missingFromLocal)
// Detect amended commits (using nilsimsa similarity with threshold 0.8)
if len(missingFromRemote) > 0 && len(missingFromLocal) > 0 {
amendedCommits, err := detectAmendedCommits(ctx, missingFromRemote, missingFromLocal, 0.8)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error detecting amended commits for %s: %v\n", localBranches[i].Name, err)
continue
}
localBranches[i].AmendedCommits = amendedCommits
}
}
}
// enrichSingleBranchWithRelated enriches a single branch with related branches (patch-id based)
// Uses the provided patchIdCache to avoid recalculating patch-ids for branches
// Returns the enriched branch and the updated cache
func enrichSingleBranchWithRelated(ctx context.Context, targetBranch BranchInfo, allBranches []BranchInfo, patchIdCache map[string][]string) (BranchInfo, map[string][]string, error) {
enriched := targetBranch
// Initialize cache if nil
if patchIdCache == nil {
patchIdCache = make(map[string][]string)
}
// Find base branch for skipping
baseBranch := findBaseBranch(allBranches)
if targetBranch.Name == baseBranch {
return enriched, patchIdCache, nil // Don't enrich base branch
}
// Calculate patch-ids for target branch if not in cache
targetPatchIds, ok := patchIdCache[targetBranch.Name]
if !ok {
// Get divergence commit from parent (if any)
divergenceCommit := ""
if len(targetBranch.ParentCandidates) > 0 {
divergenceCommit = targetBranch.ParentCandidates[0].CommonAncestor
}
// Calculate patch-ids (10 max, from divergence or last 10)
patchIds, err := calculateBranchPatchIds(ctx, targetBranch.Name, divergenceCommit)
if err != nil {
return enriched, patchIdCache, fmt.Errorf("calculating patch-ids for %s: %w", targetBranch.Name, err)
}
targetPatchIds = patchIds
patchIdCache[targetBranch.Name] = patchIds
}
// Build patch-id index from all local branches
branchPatchIds := make(map[string][]string)
branchPatchIds[targetBranch.Name] = targetPatchIds
// Calculate patch-ids for other local branches (using cache where possible)
for _, branch := range allBranches {
if branch.IsRemote || branch.Name == baseBranch || branch.Name == targetBranch.Name {
continue
}
// Check cache first
if cached, ok := patchIdCache[branch.Name]; ok {
branchPatchIds[branch.Name] = cached
continue
}
// Calculate and cache
divergenceCommit := ""
if len(branch.ParentCandidates) > 0 {
divergenceCommit = branch.ParentCandidates[0].CommonAncestor
}
patchIds, err := calculateBranchPatchIds(ctx, branch.Name, divergenceCommit)
if err != nil {
// Skip branches with errors, don't fail the whole operation
fmt.Fprintf(os.Stderr, "Warning: skipping patch-id calculation for '%s': %v\n", branch.Name, err)
continue
}
if len(patchIds) > 0 {
branchPatchIds[branch.Name] = patchIds
patchIdCache[branch.Name] = patchIds
}
}
// Build patch-id index and find related branches
if len(branchPatchIds) > 1 { // Need at least 2 branches (target + 1 other)
patchIdIndex := buildPatchIdIndexFromBranches(ctx, branchPatchIds)
relatedBranches := detectRelatedBranches(
ctx,
targetBranch.Name,
targetPatchIds,
patchIdIndex,
branchPatchIds,
allBranches,
)
enriched.PrefixShared = relatedBranches
}
return enriched, patchIdCache, nil
}
// branchesEnrichedMsg is sent when branches have been enriched with parent information
type branchesEnrichedMsg struct {
branches []BranchInfo
}
|