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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/chikamim/nilsimsa"
)
// Parent detection time threshold: ignore merge-bases older than this
const parentDetectionMaxAge = 180 * 24 * time.Hour // 6 months
// buildBranchTipsIndex builds a map from commit hash to branch name
func buildBranchTipsIndex(ctx context.Context, branches []BranchInfo) map[string]string {
ctx, done := StartSpan(ctx, "buildBranchTipsIndex")
defer done()
branchTips := make(map[string]string)
for _, branch := range branches {
branchTips[branch.CurrentCommit] = branch.Name
}
return branchTips
}
// calculateBranchPatchIds calculates patch-ids for a branch (limited to 10)
// If divergenceCommit is provided, calculates from divergenceCommit..branch (first 10)
// If not provided (orphan branch), calculates for last 10 commits on branch
func calculateBranchPatchIds(ctx context.Context, branchName string, divergenceCommit string) ([]string, error) {
ctx, done := StartSpan(ctx, "calculateBranchPatchIds")
defer done()
if divergenceCommit != "" {
// Branch has parent: get first 10 patch-ids from divergence point
return getFirstNPatchIds(ctx, divergenceCommit, branchName, 10)
} else {
// Orphan branch: get patch-ids for last 10 commits
return getPatchIdsForLastNCommits(ctx, branchName, 10)
}
}
// detectParents finds parent candidates for a given branch using merge-base with trunk
// Returns parent candidate with divergence commit (if found)
// allBranches is needed to find the trunk branch
func detectParents(ctx context.Context, targetBranch BranchInfo, allBranches []BranchInfo, branchTips map[string]string) (*ParentCandidate, error) {
ctx, done := StartSpan(ctx, "detectParents")
defer done()
// STRATEGY 1: Use merge-base with trunk branch (most reliable for typical workflows)
trunkBranch := findTrunkBranch(allBranches)
if trunkBranch != "" && trunkBranch != targetBranch.Name {
mergeBase, err := getMergeBase(ctx, targetBranch.Name, trunkBranch)
if err == nil && mergeBase != "" {
// Get commit date to check if it's recent enough
commitDate, err := getCommitDate(ctx, mergeBase)
if err == nil {
age := time.Since(commitDate)
if age <= parentDetectionMaxAge {
// Recent merge-base found - this is the parent
parent := &ParentCandidate{
BranchName: trunkBranch,
Method: "merge-base-trunk",
CommonAncestor: mergeBase,
}
return parent, nil
}
// Merge-base too old - branch is stale/ancient
fmt.Fprintf(os.Stderr, "Note: branch %s has ancient merge-base with %s (%.0f days old), skipping\n",
targetBranch.Name, trunkBranch, age.Hours()/24)
}
}
}
// STRATEGY 2: Fallback to ancestor-walk (for branches not based on trunk)
ancestors, err := getAncestorCommits(ctx, targetBranch.Name, 100)
if err == nil {
// Walk through ancestors, looking for a branch tip
for i, ancestorCommit := range ancestors {
if i == 0 {
// Skip first commit (it's the branch's own HEAD)
continue
}
if parentBranch, exists := branchTips[ancestorCommit]; exists {
// Found parent via ancestor-walk
parent := &ParentCandidate{
BranchName: parentBranch,
Method: "ancestor-walk",
CommonAncestor: ancestorCommit,
}
return parent, nil
}
}
}
// STRATEGY 3: Use upstream tracking if configured (last resort)
if targetBranch.UpstreamBranch != "" {
// Calculate merge-base with upstream to get CommonAncestor
mergeBase, err := getMergeBase(ctx, targetBranch.Name, targetBranch.UpstreamBranch)
if err == nil && mergeBase != "" {
// Extract branch name from upstream (e.g., "origin/main" -> full upstream path)
parent := &ParentCandidate{
BranchName: targetBranch.UpstreamBranch,
Method: "upstream-tracking",
CommonAncestor: mergeBase,
}
return parent, nil
}
}
// No parent found
return nil, nil
}
// buildPatchIdIndexFromBranches builds an index of patch-ids to branch names
// Takes a map of branchName -> []patchIds and inverts it to patchId -> []branchNames
// Returns a map where key=patchId (string), value=[]string (branch names)
func buildPatchIdIndexFromBranches(ctx context.Context, branchPatchIds map[string][]string) map[string][]string {
ctx, done := StartSpan(ctx, "buildPatchIdIndexFromBranches")
defer done()
patchIdIndex := make(map[string][]string)
for branchName, patchIds := range branchPatchIds {
for _, patchId := range patchIds {
patchIdIndex[patchId] = append(patchIdIndex[patchId], branchName)
}
}
return patchIdIndex
}
// detectRelatedBranches uses patch-id matching to find related branches
// Takes the target branch's patch-ids and finds other branches with shared patch-ids
// Also requires allBranches to look up commit IDs for related branches
func detectRelatedBranches(ctx context.Context, targetBranchName string, targetPatchIds []string, patchIdIndex map[string][]string, allBranchPatchIds map[string][]string, allBranches []BranchInfo) []PrefixSharedBranch {
ctx, done := StartSpan(ctx, "detectRelatedBranches")
defer done()
var results []PrefixSharedBranch
if len(targetPatchIds) == 0 {
return results
}
// Build a map from branch name to commit ID for quick lookup
branchCommits := make(map[string]string)
for _, branch := range allBranches {
branchCommits[branch.Name] = branch.CurrentCommit
}
// Find candidate branches that share at least one patch-id
candidateSet := make(map[string]bool)
for _, patchId := range targetPatchIds {
if branchList, ok := patchIdIndex[patchId]; ok {
for _, branchName := range branchList {
if branchName != targetBranchName {
candidateSet[branchName] = true
}
}
}
}
// If no candidates found, return early
if len(candidateSet) == 0 {
return results
}
// Compare with candidate branches
for candidateName := range candidateSet {
candidatePatchIds, ok := allBranchPatchIds[candidateName]
if !ok || len(candidatePatchIds) == 0 {
continue
}
// Check if candidate's patch-ids form a prefix of target's patch-ids
prefixMatch := checkPatchIdPrefix(candidatePatchIds, targetPatchIds)
if prefixMatch >= 2 {
// Shared prefix (diverged siblings or rebased versions)
// Look up commit ID for this branch
commitID := branchCommits[candidateName]
results = append(results, PrefixSharedBranch{
BranchName: candidateName,
CurrentCommit: commitID,
SharedPrefixLength: prefixMatch,
TotalInBranch: len(candidatePatchIds),
TotalInCurrent: len(targetPatchIds),
Diverged: prefixMatch < len(candidatePatchIds) || prefixMatch < len(targetPatchIds),
})
}
}
return results
}
// checkPatchIdPrefix checks how many patch-ids from start match between two lists
// Returns the number of matching patch-ids from the start
func checkPatchIdPrefix(prefix, full []string) int {
matchCount := 0
minLen := min(len(full), len(prefix))
for i := 0; i < minLen; i++ {
if prefix[i] == full[i] {
matchCount++
} else {
// Stop at first mismatch (prefix must be continuous from start)
break
}
}
return matchCount
}
// findBaseBranch attempts to find the main/base branch for patch-id comparisons
func findBaseBranch(branches []BranchInfo) string {
// Check common base branch names in order of preference
baseNames := []string{"canon", "main", "master", "develop"}
for _, baseName := range baseNames {
for _, branch := range branches {
if branch.Name == baseName {
return baseName
}
}
}
// If no common base found, return first branch (not ideal but better than nothing)
if len(branches) > 0 {
return branches[0].Name
}
return "main" // fallback
}
// findRemoteCounterpart finds the remote branch that corresponds to a local branch
// Looks for origin/<branchName> or any remote with the same branch name
func findRemoteCounterpart(branchName string, allBranches []BranchInfo) *BranchInfo {
// Try origin/<branchName> first (most common)
remoteName := "origin/" + branchName
for i := range allBranches {
if allBranches[i].Name == remoteName && allBranches[i].IsRemote {
return &allBranches[i]
}
}
// Try any remote with the same branch name
for i := range allBranches {
if allBranches[i].IsRemote && strings.HasSuffix(allBranches[i].Name, "/"+branchName) {
return &allBranches[i]
}
}
return nil
}
// detectAmendedCommits finds commits that appear to be the same logical change
// but with different hashes (due to rebase/amend) using nilsimsa similarity hashing
func detectAmendedCommits(ctx context.Context, localCommits, remoteCommits []string, threshold float64) ([]AmendedCommit, error) {
ctx, done := StartSpan(ctx, "detectAmendedCommits")
defer done()
var results []AmendedCommit
// Get commit messages for local commits in one batch
localMessages, err := getCommitMessagesBatch(ctx, localCommits)
if err != nil {
return nil, fmt.Errorf("fetching local commit messages: %w", err)
}
// Get commit messages for remote commits in one batch
remoteMessages, err := getCommitMessagesBatch(ctx, remoteCommits)
if err != nil {
return nil, fmt.Errorf("fetching remote commit messages: %w", err)
}
// Compute nilsimsa hashes for all messages
localHashes := make(map[string][32]byte)
for commit, msg := range localMessages {
localHashes[commit] = nilsimsa.Sum([]byte(msg))
}
remoteHashes := make(map[string][32]byte)
for commit, msg := range remoteMessages {
remoteHashes[commit] = nilsimsa.Sum([]byte(msg))
}
// Compare all pairs
for localCommit, localHash := range localHashes {
for remoteCommit, remoteHash := range remoteHashes {
// Calculate similarity score
similarity := nilsimsa.DiffScore(&localHash, &remoteHash)
// If similarity exceeds threshold, consider them the same commit
if similarity >= threshold {
// Get patch-ids to determine if this is a pure rebase or actual amendment
localPatchId, err := getSingleCommitPatchIdCached(ctx, localCommit)
if err != nil {
// Log warning but continue - patch-id is supplementary info
fmt.Fprintf(os.Stderr, "Warning: could not get patch-id for local commit %s: %v\n",
localCommit[:8], err)
localPatchId = ""
}
remotePatchId, err := getSingleCommitPatchIdCached(ctx, remoteCommit)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not get patch-id for remote commit %s: %v\n",
remoteCommit[:8], err)
remotePatchId = ""
}
results = append(results, AmendedCommit{
LocalCommit: localCommit,
RemoteCommit: remoteCommit,
LocalMessage: localMessages[localCommit],
RemoteMessage: remoteMessages[remoteCommit],
Similarity: similarity,
LocalPatchId: localPatchId,
RemotePatchId: remotePatchId,
})
}
}
}
return results, nil
}
|