gunk-dev/the-valley

prepare.go

source61364523a8d7main's published tip history
6.4 KiB
1package rebase
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "strings"
12)
13
14// ErrInterrupted is a rebase whose git was ended by a signal, as by an
15// interrupt from the terminal. The worktree is cleaned up all the same.
16var ErrInterrupted = errors.New("the rebase was interrupted; nothing changed")
17
18// keepPrefix is where a prepared family's heads are kept reachable in the
19// repository it was prepared in, one ref per layer, until it is released.
20// The refs are local and are never pushed.
21const keepPrefix = "refs/valley-rebase/"
22
23// Prepared is a family rebased and not yet published: each layer's new
24// head, kept reachable in the repository until Release.
25type Prepared struct {
26 Family *Family
27 Heads map[*Layer]string // each layer's prepared head
28 keep []string
29}
30
31// Prepare rebases every layer of a checked family in one throwaway
32// worktree, the caller's checkout untouched: the bottom onto main, and
33// each layer above onto the prepared layer below it, so a shared lower
34// layer is prepared once and every layer on it sits on the same new head.
35// Each layer's own commits are rebased, so every layer keeps its own
36// delta. A conflict or a layer left empty anywhere ends it with nothing
37// prepared and nothing pushed.
38//
39// The worktree is removed however Prepare ends, and a Prepare that
40// returns no Prepared leaves no ref behind. A cancelled context ends the
41// git it is running, and Prepare returns the context's error; git ended
42// by a signal gives ErrInterrupted.
43func Prepare(ctx context.Context, g Git, f *Family) (*Prepared, error) {
44 if err := f.Check(); err != nil {
45 return nil, err
46 }
47 if err := ctx.Err(); err != nil {
48 return nil, err
49 }
50 dir, err := os.MkdirTemp("", "valley-rebase.")
51 if err != nil {
52 return nil, &Refusal{Kind: NoWorktree}
53 }
54 wt := g.in(dir)
55 p := &Prepared{Family: f, Heads: map[*Layer]string{}}
56 // A step killed part way may have done some of its work. A worktree
57 // add may have registered the worktree and not checked it out, and an
58 // update-ref may have created the refs before it returned. So each
59 // step's cleanup is armed before the step starts. The cleanup runs
60 // under a context of its own, since it must run when the caller's is
61 // cancelled.
62 adding, added, prepared := false, false, false
63 defer func() {
64 done := context.WithoutCancel(ctx)
65 if !prepared {
66 p.Release(done, g)
67 }
68 // git runs in dir only once it is a worktree: a directory that is
69 // not one would leave git to find the repository above it.
70 if added {
71 wt.succeeds(done, true, "rebase", "--abort")
72 }
73 // worktree remove refuses a worktree whose directory holds no .git
74 // file, as a killed worktree add can leave it, unless the
75 // directory is gone. Forced twice, it also removes a worktree that
76 // is still locked: worktree add locks one until it is checked out.
77 os.RemoveAll(dir)
78 if adding {
79 g.succeeds(done, true, "worktree", "remove", "--force", "--force", dir)
80 }
81 }()
82 stopped := func(err error) error {
83 var exit *exec.ExitError
84 switch {
85 case ctx.Err() != nil:
86 return ctx.Err()
87 case errors.As(err, &exit) && exit.ExitCode() == -1:
88 return ErrInterrupted
89 }
90 return nil
91 }
92
93 bottom := f.Bottom()
94 adding = true
95 if _, err := g.output(ctx, false, "worktree", "add", "--quiet", "--detach", dir, bottom.Head); err != nil {
96 if err := stopped(err); err != nil {
97 return nil, err
98 }
99 return nil, &Refusal{Kind: NoCheckout, Layer: bottom}
100 }
101 added = true
102 for _, l := range f.Layers {
103 onto, below := f.Tip, Target
104 if l.Below != nil {
105 onto, below = p.Heads[l.Below], l.Below.Name+" as rebased"
106 }
107 // rebase.updateRefs would move the person's own branches that
108 // point into the commits rebased.
109 args := []string{"-c", "rebase.updateRefs=false", "rebase", "--quiet"}
110 if l == bottom && len(f.Cut) == 0 {
111 args = append(args, onto, l.Head)
112 } else {
113 args = append(args, "--onto", onto, l.Base, l.Head)
114 }
115 if err := wt.passing(ctx, args...); err != nil {
116 if err := stopped(err); err != nil {
117 return nil, err
118 }
119 return nil, &Refusal{Kind: Conflict, Layer: l, Below: below, Paths: conflicted(ctx, wt)}
120 }
121 head, err := wt.output(ctx, true, "rev-parse", "HEAD")
122 if err != nil {
123 if err := stopped(err); err != nil {
124 return nil, err
125 }
126 return nil, &Refusal{Kind: NoNewHead, Layer: l}
127 }
128 if head == onto {
129 return nil, &Refusal{Kind: EmptyLayer, Layer: l, Below: below}
130 }
131 p.Heads[l] = head
132 }
133 if err := p.hold(ctx, g); err != nil {
134 return nil, err
135 }
136 prepared = true
137 return p, nil
138}
139
140// conflicted is the paths a stopped rebase left unmerged, at most
141// maxConflictPaths of them.
142func conflicted(ctx context.Context, wt Git) []string {
143 out, err := wt.output(ctx, true, "diff", "--name-only", "--diff-filter=U", "-z")
144 if err != nil {
145 return nil
146 }
147 var paths []string
148 for _, p := range strings.Split(out, "\x00") {
149 if p != "" && len(paths) < maxConflictPaths {
150 paths = append(paths, p)
151 }
152 }
153 return paths
154}
155
156// hold keeps every prepared head reachable, under refs of its own in the
157// repository, so the objects outlive the worktree until Release. Each ref
158// is in p.keep before update-ref runs, so Release deletes any it created
159// however it ended.
160func (p *Prepared) hold(ctx context.Context, g Git) error {
161 var token [8]byte
162 if _, err := rand.Read(token[:]); err != nil {
163 return err
164 }
165 var stdin strings.Builder
166 for k, l := range p.Family.Layers {
167 ref := fmt.Sprintf("%s%s/%d", keepPrefix, hex.EncodeToString(token[:]), k)
168 fmt.Fprintf(&stdin, "create %s %s\n", ref, p.Heads[l])
169 p.keep = append(p.keep, ref)
170 }
171 if _, err := g.input(ctx, true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil {
172 if ctx.Err() != nil {
173 return ctx.Err()
174 }
175 return errors.New("could not keep the rebased heads; nothing pushed")
176 }
177 return nil
178}
179
180// Release lets the prepared heads go: their refs are deleted, and git may
181// collect the objects no other ref reaches. It runs under a cancelled
182// context too, as cleanup does.
183func (p *Prepared) Release(ctx context.Context, g Git) error {
184 if len(p.keep) == 0 {
185 return nil
186 }
187 var stdin strings.Builder
188 for _, ref := range p.keep {
189 fmt.Fprintf(&stdin, "delete %s\n", ref)
190 }
191 if _, err := g.input(context.WithoutCancel(ctx), true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil {
192 return errors.New("could not delete the refs that kept the rebased heads")
193 }
194 p.keep = nil
195 return nil
196}