forked from iOliverNguyen/git-pr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
680 lines (602 loc) · 19.2 KB
/
Copy pathgit.go
File metadata and controls
680 lines (602 loc) · 19.2 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
type gitCommand func(args ...string) (string, error)
// pushRemoteRef force-pushes one commit to one remote branch. A force push can
// lose a race after the remote advertises its current ref: another writer may
// install the same intended commit before receive-pack locks the ref. Git then
// exits unsuccessfully even though the requested state has been achieved.
// Verify that exact postcondition before propagating the push error.
func pushRemoteRef(run gitCommand, remote, sourceHash, expectedHash, remoteRef string) (string, error) {
fullRef := "refs/heads/" + remoteRef
refspec := fmt.Sprintf("%s:%s", sourceHash, fullRef)
out, pushErr := run("push", "-f", remote, refspec)
if pushErr == nil {
return out, nil
}
remoteRefs, verifyErr := run("ls-remote", "--refs", remote, fullRef)
if verifyErr != nil {
debugf("push failed and remote ref verification also failed: %v", verifyErr)
return "", pushErr
}
if remoteRefMatches(remoteRefs, fullRef, expectedHash) {
debugf("push reported an error, but %s already points to %s", fullRef, expectedHash)
return "", nil
}
return "", pushErr
}
func remoteRefMatches(output, expectedRef, expectedHash string) bool {
for _, line := range strings.Split(output, "\n") {
fields := strings.Fields(line)
if len(fields) == 2 && fields[0] == expectedHash && fields[1] == expectedRef {
return true
}
}
return false
}
var (
regexpCommitHash = regexp.MustCompile(`^commit ([0-9a-f]{40})$`)
regexpAuthor = regexp.MustCompile(`^Author: (.*) <(.*)>$`)
regexpDate = regexp.MustCompile(`^Date:\s+(.*)$`)
// "key: value" or "key = value"
// - must not start with space at the beginning of the line
regexpKeyVal = regexp.MustCompile(`^([a-zA-Z0-9-]+)\s*:\s*([^ ].+)$`)
dateLayouts = []string{"Mon Jan _2 15:04:05 2006 -0700", "2006-01-02 15:04:05 -0700"}
)
func gitLogs(size int, extra ...string) (string, error) {
args := []string{"log", fmt.Sprintf("-%v", size)}
args = append(args, extra...)
return git(args...)
}
// mustCommitCount returns the number of commits in (from, to], i.e., reachable
// from `to` but not from `from`. Used pre-rewrite to capture depth-from-HEAD
// markers that survive a rewrite pass (which changes hashes but not positions).
func mustCommitCount(from, to string) int {
out := must(git("rev-list", "--count", fmt.Sprintf("%v..%v", from, to)))
n, err := strconv.Atoi(strings.TrimSpace(out))
if err != nil {
exitf("ERROR: failed to parse commit count for %v..%v: %v", from, to, err)
}
return n
}
func parseLogs(logs string) (out CommitList, _ error) {
logs = strings.TrimSpace(logs)
if logs == "" {
return nil, nil
}
lines := strings.Split(logs, "\n")
part := []string{}
for _, line := range lines {
if m := regexpCommitHash.FindStringSubmatch(line); m != nil {
if len(part) > 0 {
item, err := parseLogsCommit(part)
if err != nil {
return nil, err
}
out = append(out, item)
}
part = part[:0]
}
part = append(part, line)
}
item, err := parseLogsCommit(part)
if err != nil {
return nil, err
}
out = append(out, item)
return out, err
}
func parseLogsCommit(lines []string) (*Commit, error) {
if len(lines) == 0 {
return nil, nil
}
backup := lines
out := &Commit{}
// parse header
bodyStart := len(lines) // default: no body
for i, line := range lines {
if line == "" {
bodyStart = i + 1
break
}
if m := regexpCommitHash.FindStringSubmatch(line); m != nil {
out.Hash = m[1]
}
if m := regexpAuthor.FindStringSubmatch(line); m != nil {
out.AuthorName = m[1]
out.AuthorEmail = m[2]
}
if m := regexpDate.FindStringSubmatch(line); m != nil {
var date time.Time
var err error
for _, layout := range dateLayouts {
date, err = time.Parse(layout, m[1])
if err == nil {
break
}
}
if err != nil {
return nil, errorf("failed to parse time from %q", m[1])
}
out.Date = date.UTC()
}
}
// parse title and body
bodyLines := lines[bodyStart:]
if len(bodyLines) > 0 {
out.Title = strings.TrimSpace(bodyLines[0])
bodyLines = bodyLines[1:]
// trim 4 spaces prefix from body lines before parsing trailers
for i := 0; i < len(bodyLines); i++ {
bodyLines[i] = strings.TrimPrefix(bodyLines[i], " ")
}
out.Message, out.Attrs = parseTrailers(bodyLines)
}
// validate (allow empty title for jujutsu commits like "jj new")
if out.Hash == "" || out.AuthorName == "" || out.AuthorEmail == "" {
return nil, errorf("failed to parse commit with log:\n%v", strings.Join(backup, "\n"))
}
return out, nil
}
func parseTrailers(lines []string) (message string, attrs []KeyVal) {
// skip empty lines
for i := 0; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) != "" {
lines = lines[i:]
break
}
}
for i := len(lines) - 1; i >= 0; i-- {
if strings.TrimSpace(lines[i]) != "" {
lines = lines[:i+1]
break
}
}
// parse trailer from bottom up
i, line := 0, ""
for i = len(lines) - 1; i >= 0; i-- {
if m := regexpKeyVal.FindStringSubmatch(lines[i]); m != nil {
key, val := strings.ToLower(m[1]), strings.TrimSpace(m[2])
attrs = append(attrs, KeyVal{key, val})
} else {
line = lines[i]
break
}
}
// require: trailers must be separated from body by a blank line
// stop at first non-trailer line, then validate the blank line above
if len(attrs) > 0 && line == "" {
if i >= 0 {
lines = lines[:i] // exclude the blank line
} else {
lines = nil
}
} else {
attrs = nil // no valid trailers
}
return strings.TrimSpace(strings.Join(lines, "\n")), attrs
}
// jjGetChangeID returns the jj change ID for a git commit hash
func jjGetChangeID(gitHash string) (string, error) {
if !config.jj.enabled {
return "", nil
}
output, err := jj("log", "-r", gitHash, "--no-graph", "-T", "change_id")
if err != nil {
return "", err
}
// jj output may include status messages before the actual change ID
// get the last non-empty line
lines := strings.Split(strings.TrimSpace(output), "\n")
for i := len(lines) - 1; i >= 0; i-- {
line := strings.TrimSpace(lines[i])
if line != "" {
return line, nil
}
}
return "", errorf("failed to parse change ID from jj output: %s", output)
}
// parseJJWorkingCopy parses jujutsu working copy output into a Commit.
// checkOutput format: "EMPTY|HAS-DESC" or "NONEMPTY|NO-DESC"
// infoOutput format: "changeID|commitID|description"
func parseJJWorkingCopy(checkOutput, infoOutput string) (*Commit, error) {
lines := strings.Split(strings.TrimSpace(checkOutput), "\n")
lastLine := lines[len(lines)-1]
parts := strings.Split(lastLine, "|")
if len(parts) != 2 {
return nil, nil
}
isEmpty := parts[0] == "EMPTY"
hasDesc := parts[1] == "HAS-DESC"
// skip if no description at all
if !hasDesc {
return nil, nil
}
// skip empty commits (no changes)
if isEmpty {
return nil, nil
}
// include only non-empty commits with description
// parse info output
lines = strings.Split(strings.TrimSpace(infoOutput), "\n")
firstLine := lines[0]
parts = strings.Split(firstLine, "|")
if len(parts) < 3 {
return nil, errorf("unexpected jj @ output: %s", firstLine)
}
changeID := parts[0]
commitID := parts[1]
// full description starts after "changeID|commitID|"
descriptionBody := strings.TrimPrefix(firstLine, changeID+"|"+commitID+"|")
if len(lines) > 1 {
// description spans multiple lines
descriptionBody = descriptionBody + "\n" + strings.Join(lines[1:], "\n")
}
// parse description like a commit body
descLines := strings.Split(descriptionBody, "\n")
title := ""
if len(descLines) > 0 {
title = strings.TrimSpace(descLines[0])
}
message, attrs := parseTrailers(descLines[1:])
// create commit struct
commit := &Commit{
Hash: commitID,
ChangeID: changeID,
Title: title,
Message: message,
Attrs: attrs,
AuthorEmail: config.git.email,
AuthorName: config.git.user,
}
return commit, nil
}
// jjGetWorkingCopy returns the working copy commit if it's non-empty with description
func jjGetWorkingCopy() (*Commit, error) {
if !config.jj.enabled {
return nil, nil
}
// check if @ is non-empty with description
checkOutput, err := jj("log", "-r", "@", "--no-graph", "-T",
"if(empty, \"EMPTY\", \"NONEMPTY\") ++ \"|\" ++ if(description, \"HAS-DESC\", \"NO-DESC\")")
if err != nil {
return nil, err
}
// get full info including description body
infoOutput, err := jj("log", "-r", "@", "--no-graph", "-T",
"change_id ++ \"|\" ++ commit_id ++ \"|\" ++ description")
if err != nil {
return nil, err
}
return parseJJWorkingCopy(checkOutput, infoOutput)
}
// resolveStackTip walks descendants of `target` (typically HEAD) along local
// branch refs and returns the topmost commit reachable through them. This lets
// git-pr operate on the full stack even when the user has checked out a middle
// commit of the stack. Returns `target` unchanged if there are no descendants
// on local branches, or if the descendants diverge into multiple unrelated
// chains — in which case we can't unambiguously pick a single tip.
func resolveStackTip(target string) string {
targetHash, err := git("rev-parse", target)
if err != nil {
return target
}
targetHash = strings.TrimSpace(targetHash)
output, err := git("for-each-ref", "--contains", target,
"--format=%(objectname)", "refs/heads/")
if err != nil {
return target
}
var tips []string
seen := map[string]bool{}
for _, line := range strings.Split(strings.TrimSpace(output), "\n") {
h := strings.TrimSpace(line)
if h == "" || h == targetHash || seen[h] {
continue
}
seen[h] = true
tips = append(tips, h)
}
leaf, ok := pickStackLeaf(tips, isAncestorCommit)
if !ok {
debugf("warning: %v has multiple unrelated descendant branches; operating on %v..HEAD only", target, target)
return target
}
if leaf == "" {
return target
}
return leaf
}
// pickStackLeaf returns the unique tip in `tips` that has every other tip as
// an ancestor (i.e. the leaf of a linear stack of descendants). Returns
// (leaf, true) on success. Returns ("", true) when `tips` is empty (no
// descendants — caller should keep their target). Returns ("", false) when
// descendants diverge into multiple unrelated chains. The `isAncestor`
// argument lets tests substitute a fake without invoking git.
func pickStackLeaf(tips []string, isAncestor func(ancestor, descendant string) bool) (string, bool) {
if len(tips) == 0 {
return "", true
}
for _, candidate := range tips {
isLeaf := true
for _, other := range tips {
if candidate == other {
continue
}
if !isAncestor(other, candidate) {
isLeaf = false
break
}
}
if isLeaf {
return candidate, true
}
}
return "", false
}
// isAncestorCommit reports whether `ancestor` is an ancestor of `descendant`.
// Uses `git merge-base --is-ancestor`, which exits 0 for true and 1 for false.
func isAncestorCommit(ancestor, descendant string) bool {
_, err := git("merge-base", "--is-ancestor", ancestor, descendant)
return err == nil
}
// getStackedCommits returns the commits in (base, target] ordered oldest→newest,
// with empty/invalid commits filtered out. When includeJJWorkingCopy is true and
// jj is enabled, jj's working copy (if non-empty with a description) is appended
// as the newest commit. Range-mode callers should pass false to avoid pulling
// in the working copy when the user has explicitly named a tip.
func getStackedCommits(base, target string, includeJJWorkingCopy bool) ([]*Commit, error) {
logs, err := gitLogs(100, fmt.Sprintf("%v..%v", base, target))
if err != nil {
return nil, wrapf(err, "failed to find common ancestor for %v and %v", base, target)
}
list, err := parseLogs(logs)
if err != nil {
return nil, err
}
// filter out empty commits (no title and no message)
filtered := make([]*Commit, 0, len(list))
for _, commit := range list {
if commit.Title != "" || commit.Message != "" {
filtered = append(filtered, commit)
}
}
list = filtered
// populate jj change IDs if in jj repo
if config.jj.enabled {
for _, commit := range list {
changeID, err := jjGetChangeID(commit.Hash)
if err != nil {
debugf("warning: failed to get change ID for %s: %v", commit.ShortHash(), err)
} else {
commit.ChangeID = changeID
}
}
}
// sort from oldest to newest
result := revert(list)
// append jj working copy at the end (newest) if applicable
if includeJJWorkingCopy && config.jj.enabled {
workingCopy, err := jjGetWorkingCopy()
if err != nil {
debugf("warning: failed to get jj working copy: %v", err)
} else if workingCopy != nil {
debugf("including jj working copy in stack: %s", workingCopy.Title)
result = append(result, workingCopy)
}
}
// validate commits and collect warnings/errors
var warnings []string
var errors []string
filtered = result[:0] // reuse filtered slice for non-skipped commits
for _, commit := range result {
isEmpty := isEmptyCommit(commit)
hasEmptyTitle := commit.Title == ""
if hasEmptyTitle && isEmpty {
// warn: empty title + no file changes
warnings = append(warnings, fmt.Sprintf("⚠️ commit %s has empty title and no file changes, skipping", commit.ShortHash()))
commit.Skip = true
continue
} else if hasEmptyTitle {
// error: empty title + has file changes
errors = append(errors, fmt.Sprintf("❌ commit %s has empty title but contains file changes (fix required)", commit.ShortHash()))
commit.Skip = true
continue
} else if isEmpty {
// warn: no file changes
warnings = append(warnings, fmt.Sprintf("⚠️ commit %s %q has no file changes, skipping", commit.ShortHash(), shortenTitle(commit.Title)))
commit.Skip = true
continue
}
filtered = append(filtered, commit)
}
result = filtered
// print warnings and errors
for _, msg := range warnings {
printf("%s\n", msg)
}
for _, msg := range errors {
printf("%s\n", msg)
}
// return error if any validation errors
if len(errors) > 0 {
return nil, errorf("validation failed, please fix the commits above")
}
return result, nil
}
// isEmptyCommit checks if a commit has no file changes
func isEmptyCommit(commit *Commit) bool {
// use git to check if commit has file changes
output, err := git("diff-tree", "--no-commit-id", "--name-only", "-r", commit.Hash)
if err != nil {
debugf("warning: failed to check if commit is empty: %v", err)
return false // assume not empty on error
}
return strings.TrimSpace(output) == ""
}
func shortenTitle(title string) string {
const Max = 36
if len(title) <= Max {
return title
}
title = title[:Max]
idx := strings.LastIndexByte(title, ' ')
if idx == -1 {
return title + "..."
} else {
return title[:idx] + " ..."
}
}
func deleteBranch(branch string) error {
branches, err := git("branch")
if err != nil {
return err
}
if strings.Contains(branches, branch+"\n") {
_, err = git("branch", "-D", branch) // delete branch
}
return err
}
// findBranchForCommit finds existing local or remote branch that POINTS TO the given commit
// (not just contains it in history)
func findBranchForCommit(commit *Commit) (string, error) {
// Get all branches with their HEAD commit
output, err := git("branch", "-a", "--format=%(refname)|%(objectname)")
if err != nil {
return "", nil // error listing branches, not a fatal error
}
lines := strings.Split(strings.TrimSpace(output), "\n")
if len(lines) == 0 || lines[0] == "" {
return "", nil
}
var localBranch string
var remoteBranch string
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Split(line, "|")
if len(parts) != 2 {
continue
}
refName := parts[0]
commitHash := parts[1]
// Only match if branch points EXACTLY to this commit
if commitHash != commit.Hash {
continue
}
// Skip HEAD and main/master branches
if isDetachedHeadBranchPlaceholder(refName) || strings.Contains(refName, "HEAD") {
continue
}
if strings.HasSuffix(refName, "/main") || strings.HasSuffix(refName, "/master") {
continue
}
if refName == "refs/heads/main" || refName == "refs/heads/master" {
continue
}
// Prefer local branches
if strings.HasPrefix(refName, "refs/heads/") {
localBranch = strings.TrimPrefix(refName, "refs/heads/")
break // found local branch, use it
}
// Track remote branches as fallback
if strings.HasPrefix(refName, "refs/remotes/"+config.git.remote+"/") {
remoteBranch = strings.TrimPrefix(refName, "refs/remotes/"+config.git.remote+"/")
}
}
// Prefer local branch, fallback to remote
if localBranch != "" {
return localBranch, nil
}
return remoteBranch, nil
}
func isDetachedHeadBranchPlaceholder(branchName string) bool {
return strings.HasPrefix(branchName, "(HEAD detached ")
}
func isIgnoredLocalBranchName(branchName string) bool {
return branchName == "main" || branchName == "master" || isDetachedHeadBranchPlaceholder(branchName)
}
func parseFormattedBranchLine(line string) (branchName string, commitHash string, ok bool) {
line = strings.TrimSpace(line)
if line == "" {
return "", "", false
}
parts := strings.Split(line, "|")
if len(parts) != 2 {
return "", "", false
}
return parts[0], parts[1], true
}
func selectLocalBranchForCommit(lines []string, commit *Commit) string {
for _, line := range lines {
branchName, commitHash, ok := parseFormattedBranchLine(line)
if !ok {
continue
}
// Skip main/master and Git's synthetic detached-HEAD row. In detached
// checkouts, `git branch --format` emits a first row such as
// "(HEAD detached at abc1234)|<hash>", which is display text, not a ref.
if isIgnoredLocalBranchName(branchName) {
continue
}
shortHash := commitHash
if len(shortHash) > 8 {
shortHash = shortHash[:8]
}
debugf(" checking %v -> %v (match: %v)", branchName, shortHash, commitHash == commit.Hash)
// Check for exact match
if commitHash == commit.Hash {
debugf(" FOUND: %v", branchName)
return branchName
}
}
return ""
}
func validateRemoteRef(remoteRef string) error {
if strings.TrimSpace(remoteRef) != remoteRef {
return errorf("remote ref has leading or trailing whitespace")
}
if isDetachedHeadBranchPlaceholder(remoteRef) {
return errorf("remote ref is Git's detached-HEAD display placeholder, not a branch")
}
if _, err := git("check-ref-format", "--branch", remoteRef); err != nil {
return wrapf(err, "invalid branch name %q", remoteRef)
}
return nil
}
// getLocalBranchForCommit returns the local branch that points to this commit
// Used when branches are pre-created (e.g., by git-branchless)
func getLocalBranchForCommit(commit *Commit) (string, error) {
// Get all local branches with their HEAD commit
output, err := git("branch", "--format=%(refname:short)|%(objectname)")
if err != nil {
return "", err
}
lines := strings.Split(strings.TrimSpace(output), "\n")
debugf("[getLocalBranchForCommit] looking for commit %v", commit.Hash)
if branchName := selectLocalBranchForCommit(lines, commit); branchName != "" {
return branchName, nil
}
// No branch found - log debug info
printf("[BRANCH-NOT-FOUND] commit %v not on any local branch\n", commit.Hash[:8])
printf(" Commit title: %v\n", commit.Title)
printf(" Available local branches:\n")
for _, line := range lines {
branchName, commitHash, ok := parseFormattedBranchLine(line)
if ok && !isIgnoredLocalBranchName(branchName) {
shortHash := commitHash
if len(shortHash) > 8 {
shortHash = shortHash[:8]
}
printf(" %v -> %v\n", branchName, shortHash)
}
}
return "", nil
}