-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit.go
More file actions
711 lines (654 loc) · 28.5 KB
/
Copy pathcommit.go
File metadata and controls
711 lines (654 loc) · 28.5 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/smm-h/safegit/internal/commit"
"github.com/smm-h/safegit/internal/exitcode"
"github.com/smm-h/safegit/internal/git"
"github.com/smm-h/safegit/internal/gitexec"
"github.com/smm-h/safegit/internal/lock"
"github.com/smm-h/safegit/internal/repo"
"github.com/smm-h/safegit/internal/trailer"
"github.com/smm-h/strictcli/go/strictcli"
)
// pipelineExitCode is the one place a commit-pipeline error becomes an exit
// code. commit, amend and reword all end the same way -- die(code, err) -- and
// all three read the code from here, so the three paths cannot disagree.
//
// Three typed sources, in order:
//
// - a *commit.PartialError, which is not a refusal at all: the ref MOVED and
// an aftercare step did not finish, so it is the commit-stands family code
// (see aftercare.go). It is checked FIRST because it is the one error whose
// verdict is "the operation succeeded", and every other branch below would
// report it as a failure to commit.
// - a *commit.CommitError, which carries the code the pipeline chose
// deliberately (WriteTree, CommitTree, CoordinationBusy, CASExhausted).
// errors.As rather than a type assertion: the pipeline annotates some
// failures with the path they happened on, so the CommitError arrives
// wrapped.
// - a *lock.TimeoutError, which the pipeline does not wrap in a CommitError
// at all -- it returns the plain "acquiring lock on <ref>: %w" error from
// its ref-lock acquisition. Recognizing it here is what makes a contended
// ref lock exit LockTimeout from commit, amend and reword the way it
// already did from undo and the four rewrite commands. It is the same
// situation with the same remedy (wait, or release the lock), and it was
// reported as the undifferentiated General only because of where in the
// pipeline it happened.
//
// Anything else is General.
func pipelineExitCode(err error) int {
if commitStands(err) != nil {
return exitcode.CommitStands
}
var ce *commit.CommitError
if errors.As(err, &ce) {
return ce.Code
}
if lock.IsTimeout(err) {
return exitcode.LockTimeout
}
return exitcode.General
}
// commitPayload is what `commit` puts in the envelope's payload, in all three
// of its forms: a new commit, an amend, and a reword.
//
// Nothing here is counted from the arguments. `files` is the changed-path list
// the pipeline read off the objects -- for a commit, against its parent; for an
// amend, against the tip it replaced; empty for a reword, which changes no path
// at all. A caller that wants to know what a commit contains reads this rather
// than assuming its own argument list survived intake unchanged, which it does
// not: a directory expands, and a gitignored path under one is skipped.
type commitPayload struct {
Ref string `json:"ref"`
// Parents is the commit's parent list: empty for a root commit. It is a
// list because a merge commit has more than one.
Parents []string `json:"parents"`
Tree string `json:"tree"`
// SHA is the commit that was created, and null under --dry-run: the
// preview builds an object to compute the tree honestly, but no commit
// exists at that name for anyone to fetch, so reporting it as this run's
// commit would be a lie a machine consumer cannot detect.
SHA *string `json:"sha"`
// OldSHA is the commit an amend or reword replaced, and null for a plain
// commit, which replaces nothing.
OldSHA *string `json:"old_sha"`
Files []string `json:"files"`
SkippedIgnored []string `json:"skipped_ignored"`
Attempts int `json:"attempts"`
// ExecutionMode names which form of the command ran where the argv alone
// does not say: `--amend` resolves to an AMEND when files, hunks or untrack
// targets are named and to a REWORD when none are. It is `amend` or `reword`
// on that path and null on a plain commit.
//
// It is the whole of what safegit says about the split, and deliberately so.
// The two forms are identical in authorship and in safety -- both are the
// pipeline's own commit, both move the ref under compare-and-swap, both are
// undoable -- so a stderr line announcing which one happened would be noise
// about a difference that changes nothing an operator has to act on. A
// machine consumer that DOES care reads it here.
ExecutionMode *string `json:"execution_mode"`
// Residue is every step this commit owed AFTER its ref update and did not
// finish, never nil -- reconciling the shared index with the new tip, and
// bumping a parent repository's gitlink. An empty list is a run that
// finished everything it owed; anything in it is what the commit-stands exit
// code (see aftercare.go) is about, and without it an envelope carrying that
// code would name no step at all.
Residue []residueEntry `json:"residue"`
DryRun bool `json:"dry_run"`
// MovedRecords is every move record THIS run put on the commit, in the order
// the message holds them: the caller's declarations first, then the records
// safegit minted from the commit's own delta, each naming which of the two it
// is. A record CARRIED ACROSS from a message being replaced is not one of
// them -- it was reported by the run that wrote it, and repeating it here
// would make an amend look like it minted a record it only preserved.
//
// It answers for the message the commit ended up with: a record the
// repository's own commit-msg hook rewrote away is not reported, because a
// consumer reading this list must be able to find every entry on the commit.
//
// It is never null: a run that recorded no move reports an empty list, which
// is what tells a consumer the question was answered.
MovedRecords []movedRecordEntry `json:"moved_records"`
// RefusedMoves is every candidate this commit's delta suggested and a fence
// declined to record, itemized -- the same facts the one aggregate stderr
// notice only counts. Never null.
RefusedMoves []refusedMoveEntry `json:"refused_moves"`
// MovesOverCap is how many moves the delta witnessed when the cap turned all
// of them down, and 0 otherwise. It is what separates "this commit witnessed
// nothing" from "it witnessed too much to record any of it".
MovesOverCap int `json:"moves_over_cap"`
}
// movedRecordEntry is one move record on the payload.
type movedRecordEntry struct {
ID string `json:"id"`
Old string `json:"old"`
New string `json:"new"`
// Origin is who established the claim: "declared" for a person's statement,
// "observed" for one safegit read off the commit's delta. The word is
// present on every entry, including the declared ones the message spells by
// writing no token at all.
Origin string `json:"origin"`
}
// refusedMoveEntry is one candidate a fence declined. Old and New are lists
// because an AMBIGUOUS candidate has more than one path on the side that was
// ambiguous, and naming only one of them would misreport which question went
// unanswered.
type refusedMoveEntry struct {
Old []string `json:"old"`
New []string `json:"new"`
Reason string `json:"reason"`
}
// movedRecordEntrySchema declares one movedRecordEntry, and it is declared ONCE
// because the entry is one shape: `commit` and `mv` both report the records
// their run put on the commit, in the same member, so a second copy of this
// fragment would be a second authority for what an entry is and the two could
// drift apart at emission-time validation.
var movedRecordEntrySchema = strictcli.SchemaObject(
map[string]interface{}{
"id": strictcli.SchemaType("string"),
"old": strictcli.SchemaType("string"),
"new": strictcli.SchemaType("string"),
"origin": strictcli.SchemaType("string"),
},
[]string{"id", "old", "new", "origin"},
false,
)
// movedRecordEntries renders the pipeline's records for the payload, never nil.
func movedRecordEntries(records []trailer.Record) []movedRecordEntry {
out := make([]movedRecordEntry, 0, len(records))
for _, r := range records {
out = append(out, movedRecordEntry{ID: r.ID, Old: r.Old, New: r.New, Origin: r.Origin.Name()})
}
return out
}
// refusedMoveEntries renders the pipeline's refusals for the payload, never
// nil.
func refusedMoveEntries(refused []commit.RefusedMove) []refusedMoveEntry {
out := make([]refusedMoveEntry, 0, len(refused))
for _, r := range refused {
out = append(out, refusedMoveEntry{Old: orEmpty(r.Old), New: orEmpty(r.New), Reason: r.Reason})
}
return out
}
// The two values ExecutionMode takes. A plain commit reports neither.
const (
executionModeAmend = "amend"
executionModeReword = "reword"
)
// executionMode renders the member for one of the two --amend forms.
func executionMode(mode string) *string { return &mode }
// commitPayloadSchema declares what `commit` puts in the envelope's payload.
// The framework validates the value against it at emission, so the declaration
// and the struct above cannot drift.
var commitPayloadSchema = strictcli.SchemaObject(
map[string]interface{}{
"ref": strictcli.SchemaType("string"),
"parents": strictcli.SchemaArray(strictcli.SchemaType("string")),
"tree": strictcli.SchemaType("string"),
"sha": strictcli.SchemaType("string", "null"),
"old_sha": strictcli.SchemaType("string", "null"),
"files": strictcli.SchemaArray(strictcli.SchemaType("string")),
"skipped_ignored": strictcli.SchemaArray(strictcli.SchemaType("string")),
"attempts": strictcli.SchemaType("integer"),
"execution_mode": strictcli.SchemaType("string", "null"),
"residue": strictcli.SchemaArray(strictcli.SchemaObject(
map[string]interface{}{
"step": strictcli.SchemaType("string"),
"detail": strictcli.SchemaType("string"),
},
[]string{"step", "detail"},
false,
)),
"dry_run": strictcli.SchemaType("boolean"),
"moved_records": strictcli.SchemaArray(movedRecordEntrySchema),
"refused_moves": strictcli.SchemaArray(strictcli.SchemaObject(
map[string]interface{}{
"old": strictcli.SchemaArray(strictcli.SchemaType("string")),
"new": strictcli.SchemaArray(strictcli.SchemaType("string")),
"reason": strictcli.SchemaType("string"),
},
[]string{"old", "new", "reason"},
false,
)),
"moves_over_cap": strictcli.SchemaType("integer"),
},
[]string{"ref", "parents", "tree", "sha", "old_sha", "files", "skipped_ignored", "attempts", "execution_mode",
"residue", "dry_run", "moved_records", "refused_moves", "moves_over_cap"},
false,
)
// joinMessages composes the commit message from repeated -m values, separating
// them with a BLANK line -- `-m subject -m body` is a subject and a body, which
// is what `git commit -m ... -m ...` means and what every reader of a git log
// assumes. Joined with a single newline instead, git reads the whole thing as
// one subject and `git log --oneline` prints every paragraph on one line.
//
// commit, amend and reword all compose their message here, so the three cannot
// disagree about what repeating -m means.
func joinMessages(messages []string) string {
return strings.Join(messages, "\n\n")
}
// realSHA reports the commit SHA a run actually created, and nothing under a
// dry run.
func realSHA(flags globalFlags, sha string) *string {
if flags.dryRun {
return nil
}
return &sha
}
// orEmpty renders an absent list as an empty one, so a payload member is never
// null where the schema declares an array.
func orEmpty(list []string) []string {
if list == nil {
return []string{}
}
return list
}
// runCommit is the commit family's handler, and it RETURNS its exit code rather
// than exiting: an aftercare failure leaves a commit that stands, and reporting
// it takes the envelope the framework emits below a handler's return (see
// aftercare.go). Every refusal above the ref update still dies -- there is
// nothing to report when nothing was written.
func runCommit(flags globalFlags, messages []string, messageFile string, branch string, amend bool, allowEmpty bool, allowNonPortableTargets bool, trailers []string, files []string, hunks []string, untrack []string, moved []string, movedRetract []string) int {
gitDir := mustGitDir()
if err := ensureInitialized(flags, gitDir); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(exitcode.NotInitialized)
}
// Validate: -m and -F are mutually exclusive
if len(messages) > 0 && messageFile != "" {
die(exitcode.Usage, "-m and -F are mutually exclusive")
}
if amend {
// --amend mode: amend (with files) or reword (without files)
if allowEmpty {
die(exitcode.Usage, "--allow-empty cannot be used with --amend")
}
if messageFile != "" {
die(exitcode.Usage, "-F cannot be used with --amend")
}
return runCommitAmend(flags, gitDir, messages, branch, allowNonPortableTargets, trailers, files, hunks, untrack, moved, movedRetract)
}
// Normal commit path
if messageFile != "" {
data, err := os.ReadFile(messageFile)
if err != nil {
die(exitcode.General, fmt.Sprintf("reading message file: %v", err))
}
messages = append(messages, strings.TrimRight(string(data), "\n"))
}
if len(messages) == 0 {
die(exitcode.Usage, "commit message required (-m or -F)")
}
if len(files) == 0 && len(hunks) == 0 && len(untrack) == 0 && !allowEmpty {
die(exitcode.Usage, "no files specified (use -- file1 file2 ..., --hunks path:1,3 or --untrack path)")
}
msg := joinMessages(messages)
fileSpecs, err := buildFileSpecs(files, hunks)
if err != nil {
die(exitcode.Usage, err.Error())
}
sgDir := repo.SafegitDir(gitDir)
cfg, err := loadConfig(flags, gitDir)
if err != nil {
die(exitcode.General, fmt.Sprintf("loading config: %v", err))
}
// Before the pipeline runs at all: a submodule commit moves the parent's
// gitlink, and a parent that has not answered the auto-bump question is a
// refusal, not a commit followed by one.
if err := requireAutoBumpDecision(flags.ctx(), flags); err != nil {
die(exitcode.General, fmt.Sprintf("auto-bump parent: %v", err))
}
// Outermost, around the pipeline's whole run: the in-flight-operation check
// inside it reads state a concurrent passthrough would otherwise be free to
// create between the check and the ref update. The pipeline's per-ref CAS
// lock is taken inside this one.
release, code := acquireOperationLock(flags, gitDir, "commit")
if code != 0 {
os.Exit(code)
}
defer release()
if flags.verbose {
paths := make([]string, len(fileSpecs))
for i, fs := range fileSpecs {
paths[i] = fs.Path
}
fmt.Fprintf(os.Stderr, " files: %s\n", strings.Join(paths, ", "))
if branch != "" {
fmt.Fprintf(os.Stderr, " branch: %s\n", branch)
}
}
p := &commit.Pipeline{SafegitDir: sgDir, Config: *cfg, RefUpdate: effectsRefUpdate{flags}}
result, err := p.Execute(flags.ctx(), commit.CommitRequest{
Message: msg,
FileSpecs: fileSpecs,
Branch: branch,
Trailers: trailers,
AllowEmpty: allowEmpty,
AllowNonPortableTargets: allowNonPortableTargets,
DryRun: flags.dryRun,
Untrack: untrack,
Moved: moved,
MovedRetract: movedRetract,
})
// A commit-stands verdict is not a refusal: the ref moved, so the run goes
// on to report the commit rather than dying above the envelope seam.
var residue []residueEntry
if partial := commitStands(err); partial != nil && result != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
residue = recordAftercareFailure(residue, partial.Step, err.Error())
} else if err != nil {
die(pipelineExitCode(err), err.Error())
}
if flags.verbose {
fmt.Fprintf(os.Stderr, " ref: %s\n", result.Ref)
fmt.Fprintf(os.Stderr, " tree: %s\n", result.Tree)
fmt.Fprintf(os.Stderr, " parents: %s\n", strings.Join(result.Parents, " "))
fmt.Fprintf(os.Stderr, " sha: %s\n", result.SHA)
}
if err := maybeAutoBumpParent(flags.ctx(), flags, gitDir, result.SHA, "commit", firstLine(msg)); err != nil {
residue = reportAftercareFailure(residue, stepParentBump, err)
}
flags.payload(commitPayload{
Ref: result.Ref,
Parents: orEmpty(result.Parents),
Tree: result.Tree,
SHA: realSHA(flags, result.SHA),
OldSHA: nil,
Files: result.Files,
SkippedIgnored: orEmpty(result.SkippedIgnored),
Attempts: result.Attempts,
ExecutionMode: nil,
Residue: orEmptyResidue(residue),
DryRun: flags.dryRun,
MovedRecords: movedRecordEntries(result.MovedRecords),
RefusedMoves: refusedMoveEntries(result.RefusedMoves),
MovesOverCap: result.MovesOverCap,
})
if !flags.silent() {
if flags.dryRun {
fmt.Println(wouldWriteHeader("commit", result.Ref, result.Tree, firstLine(msg)))
fmt.Printf(" %d file(s) would be committed", len(result.Files))
} else {
fmt.Printf("[%s %s] %s\n", refShortName(result.Ref), result.SHA[:8], firstLine(msg))
fmt.Printf(" %d file(s) committed", len(result.Files))
}
if result.Attempts > 1 {
fmt.Printf(" (%d CAS retries)", result.Attempts-1)
}
fmt.Println()
}
return aftercareExit(residue)
}
// wouldWriteHeader is a preview's answer to the `[branch sha]` line a real
// commit prints, and it deliberately does not look like one.
//
// A preview cannot know the commit SHA: the commit object a real run builds
// carries the committer timestamp, so the object the preview could name is
// never the object that will exist. What it CAN state is read off objects the
// preview really computed -- the branch the commit would go on and the tree it
// would carry -- so those are what it prints. The line does not start with `[`,
// which is what the submodule auto-bump reads a child's commit SHA out of: a
// preview line can therefore never be parsed as one.
func wouldWriteHeader(verb, ref, tree, subject string) string {
return fmt.Sprintf("would %s on %s (tree %s): %s", verb, refShortName(ref), shortSHA(tree), subject)
}
// runCommitAmend handles the --amend path: amend with files, or reword without.
// previewCommitPlaceholder stands where the new commit's SHA goes in a recorded
// ref update.
//
// A preview cannot know that SHA. The commit object a real run builds carries
// the committer timestamp, so the object a preview could name is never the
// object that will exist -- and a would-do log stating `update-ref
// refs/heads/main <some sha> <old>` invites a reader to go looking for a commit
// that neither exists now nor will exist under that name later. The rest of the
// argv is exact: the ref that moves and the value it moves away from are both
// known, and the whole line is what the execute path really runs.
//
// It mirrors rewrittenPlaceholder in scrub_preview.go, which stands for the
// same thing on the history-rewrite side.
const previewCommitPlaceholder = "<new-commit>"
// effectsRefUpdate is the commit pipeline's ref update, minted through the
// framework's effects handle.
//
// It is the pipeline's ONLY way to move a ref, and it is one mint site rather
// than two: a handler-side record alongside the pipeline's own update would
// fire twice per commit, and the second would describe a move that had already
// happened. The pipeline calls this from inside its compare-and-swap retry
// loop, holding the ref lock, with the argv that loop needs -- so an executing
// run performs exactly this invocation, retries included, and a preview records
// it and performs nothing.
//
// Check(false) is what lets a failure keep its meaning: the framework's checked
// form turns a nonzero child into a formatted string with git's own stderr
// dropped, and the pipeline reads that stderr to tell a transient ref-lock
// contention ("cannot lock ref") from a real refusal.
type effectsRefUpdate struct{ flags globalFlags }
func (u effectsRefUpdate) Update(_ context.Context, ref, newSHA, expected string) error {
// The same contract git.UpdateRef holds, held at the port too. An empty
// expected old value is git's spelling for an UNCONDITIONAL write, which is
// the opposite of what every ref move in safegit is; a caller that means
// "this ref must not exist yet" passes git.ZeroSHA.
//
// It used to substitute ZeroSHA here, silently turning "I do not know what
// is there" into "I assert nothing is there". The pipeline always decides
// explicitly, so nothing reached it -- which is exactly why it could not be
// left sitting there.
if expected == "" {
return git.ErrNoExpectedValue
}
// A preview cannot name the commit it would create, so the record carries
// the placeholder; the ref and the expected value are real.
recorded := newSHA
if u.flags.dryRun {
recorded = previewCommitPlaceholder
}
argv, err := gitexec.ArgvAny(gitexec.ExemptCommitRefUpdate, gitexec.NoDoor, "update-ref", ref, recorded, expected)
if err != nil {
return err
}
done, err := u.flags.effects().Run(argv, strictcli.Resource("ref:"+ref), strictcli.Check(false))
if err != nil {
// A framework-level refusal: no child ran, and the message is the
// framework's own.
return err
}
if u.flags.dryRun {
// Recorded instead of performed. No child process ran, so the carrier
// is unsettled and asking it anything would panic -- and there is
// nothing to ask: the pipeline reads nil as "the ref did not move",
// which is exactly what happened.
return nil
}
if code := done.ExitCode(); code != 0 {
return fmt.Errorf("update-ref %s %s %s: exit %d: %s",
ref, newSHA, expected, code, strings.TrimSpace(done.Stderr()))
}
return nil
}
func runCommitAmend(flags globalFlags, gitDir string, messages []string, branch string, allowNonPortableTargets bool, trailers []string, files []string, hunks []string, untrack []string, moved []string, movedRetract []string) int {
sgDir := repo.SafegitDir(gitDir)
cfg, err := loadConfig(flags, gitDir)
if err != nil {
die(exitcode.General, fmt.Sprintf("loading config: %v", err))
}
// Same refusal the plain commit path makes, for both the amend and the
// reword below: an unanswered auto-bump question in the parent stops the
// operation before it rewrites anything.
if err := requireAutoBumpDecision(flags.ctx(), flags); err != nil {
die(exitcode.General, fmt.Sprintf("auto-bump parent: %v", err))
}
// Same ordering as the plain commit path: operation lock outermost, the
// pipeline's per-ref CAS lock inside it.
release, code := acquireOperationLock(flags, gitDir, "amend")
if code != 0 {
os.Exit(code)
}
defer release()
p := &commit.Pipeline{SafegitDir: sgDir, Config: *cfg, RefUpdate: effectsRefUpdate{flags}}
// Both arms accumulate their aftercare failures rather than dying on one:
// the amended (or reworded) commit is the branch's tip either way, and the
// report is what says so. See aftercare.go.
var residue []residueEntry
// Three ways to amend, in the order they are decided:
//
// - files, hunks or untrack targets: an amend of the tip's content, with
// the message replaced by -m or kept as it is;
// - no files but a message: a reword;
// - no files and no message, but declared moves: an amend that changes
// nothing but the records the message carries, which is how a move
// committed without its record gets one.
if len(files) > 0 || len(hunks) > 0 || len(untrack) > 0 || ((len(moved) > 0 || len(movedRetract) > 0) && len(messages) == 0) {
// Amend: add new files to the tip commit
var msg string
if len(messages) > 0 {
msg = joinMessages(messages)
}
fileSpecs, err := buildFileSpecs(files, hunks)
if err != nil {
die(exitcode.Usage, err.Error())
}
if flags.verbose {
paths := make([]string, len(fileSpecs))
for i, fs := range fileSpecs {
paths[i] = fs.Path
}
fmt.Fprintf(os.Stderr, " amend files: %s\n", strings.Join(paths, ", "))
if branch != "" {
fmt.Fprintf(os.Stderr, " branch: %s\n", branch)
}
}
result, err := p.Amend(flags.ctx(), commit.AmendRequest{
Message: msg,
FileSpecs: fileSpecs,
Branch: branch,
Trailers: trailers,
AllowNonPortableTargets: allowNonPortableTargets,
DryRun: flags.dryRun,
Untrack: untrack,
Moved: moved,
MovedRetract: movedRetract,
})
if partial := commitStands(err); partial != nil && result != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
residue = recordAftercareFailure(residue, partial.Step, err.Error())
} else if err != nil {
die(pipelineExitCode(err), err.Error())
}
if flags.verbose {
fmt.Fprintf(os.Stderr, " ref: %s\n", result.Ref)
fmt.Fprintf(os.Stderr, " tree: %s\n", result.Tree)
fmt.Fprintf(os.Stderr, " parents: %s\n", strings.Join(result.Parents, " "))
fmt.Fprintf(os.Stderr, " old: %s\n", result.OldSHA)
fmt.Fprintf(os.Stderr, " sha: %s\n", result.SHA)
}
if err := maybeAutoBumpParent(flags.ctx(), flags, gitDir, result.SHA, "amend", firstLine(msg)); err != nil {
residue = reportAftercareFailure(residue, stepParentBump, err)
}
flags.payload(commitPayload{
Ref: result.Ref,
Parents: orEmpty(result.Parents),
Tree: result.Tree,
SHA: realSHA(flags, result.SHA),
OldSHA: &result.OldSHA,
Files: result.Files,
SkippedIgnored: orEmpty(result.SkippedIgnored),
Attempts: result.Attempts,
ExecutionMode: executionMode(executionModeAmend),
Residue: orEmptyResidue(residue),
DryRun: flags.dryRun,
MovedRecords: movedRecordEntries(result.MovedRecords),
RefusedMoves: refusedMoveEntries(result.RefusedMoves),
MovesOverCap: result.MovesOverCap,
})
if !flags.silent() {
msgDisplay := msg
if msgDisplay == "" {
msgDisplay = "(message preserved)"
}
if flags.dryRun {
fmt.Println(wouldWriteHeader("amend", result.Ref, result.Tree, firstLine(msgDisplay)))
fmt.Printf(" %d file(s) would be amended (was %s)", len(result.Files), shortSHA(result.OldSHA))
} else {
fmt.Printf("[%s %s] %s\n", refShortName(result.Ref), result.SHA[:8], firstLine(msgDisplay))
fmt.Printf(" %d file(s) amended (was %s)", len(result.Files), shortSHA(result.OldSHA))
}
if result.Attempts > 1 {
fmt.Printf(" (%d CAS retries)", result.Attempts-1)
}
fmt.Println()
}
} else {
// Reword: change the tip commit message without touching files
if len(messages) == 0 {
die(exitcode.Usage, "commit message required (-m) when using --amend without files")
}
msg := joinMessages(messages)
if flags.verbose {
fmt.Fprintf(os.Stderr, " reword message: %s\n", firstLine(msg))
if branch != "" {
fmt.Fprintf(os.Stderr, " branch: %s\n", branch)
}
}
result, err := p.Reword(flags.ctx(), commit.RewordRequest{
Message: msg,
Branch: branch,
Trailers: trailers,
DryRun: flags.dryRun,
Moved: moved,
MovedRetract: movedRetract,
})
if partial := commitStands(err); partial != nil && result != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
residue = recordAftercareFailure(residue, partial.Step, err.Error())
} else if err != nil {
die(pipelineExitCode(err), err.Error())
}
if flags.verbose {
fmt.Fprintf(os.Stderr, " ref: %s\n", result.Ref)
fmt.Fprintf(os.Stderr, " old: %s\n", result.OldSHA)
// A preview of a reword builds no commit object, so there is no
// SHA to name; the line is omitted rather than printed empty.
if result.SHA != "" {
fmt.Fprintf(os.Stderr, " sha: %s\n", result.SHA)
}
}
if err := maybeAutoBumpParent(flags.ctx(), flags, gitDir, result.SHA, "reword", firstLine(msg)); err != nil {
residue = reportAftercareFailure(residue, stepParentBump, err)
}
// A reword replaces a message and nothing else, so its changed-path
// list is empty by construction rather than by measurement.
flags.payload(commitPayload{
Ref: result.Ref,
Parents: orEmpty(result.Parents),
Tree: result.Tree,
SHA: realSHA(flags, result.SHA),
OldSHA: &result.OldSHA,
Files: []string{},
SkippedIgnored: []string{},
Attempts: result.Attempts,
ExecutionMode: executionMode(executionModeReword),
Residue: orEmptyResidue(residue),
DryRun: flags.dryRun,
// A reword mints nothing and refuses nothing: it changes no tree, so
// there is no delta to read. Its declarations are records all the
// same, and they are what this reports.
MovedRecords: movedRecordEntries(result.MovedRecords),
RefusedMoves: refusedMoveEntries(nil),
MovesOverCap: 0,
})
if !flags.silent() {
if flags.dryRun {
fmt.Println(wouldWriteHeader("reword", result.Ref, result.Tree, firstLine(msg)))
fmt.Printf(" would reword (was %s)\n", shortSHA(result.OldSHA))
} else {
fmt.Printf("[%s %s] %s\n", refShortName(result.Ref), result.SHA[:8], firstLine(msg))
fmt.Printf(" reworded (was %s)\n", shortSHA(result.OldSHA))
}
}
}
return aftercareExit(residue)
}