gunk-dev/the-valley

prepare.go

source6ee9fbfcf100main's published tip history
6.6 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, and that context is bounded (cleanupContext).
62 adding, added, prepared := false, false, false
63 defer func() {
64 done, cancel := cleanupContext(ctx)
65 defer cancel()
66 if !prepared {
67 p.Release(done, g)
68 }
69 // git runs in dir only once it is a worktree: a directory that is
70 // not one would leave git to find the repository above it.
71 if added {
72 wt.succeeds(done, true, "rebase", "--abort")
73 }
74 // worktree remove refuses a worktree whose directory holds no .git
75 // file, as a killed worktree add can leave it, unless the
76 // directory is gone. Forced twice, it also removes a worktree that
77 // is still locked: worktree add locks one until it is checked out.
78 os.RemoveAll(dir)
79 if adding {
80 g.succeeds(done, true, "worktree", "remove", "--force", "--force", dir)
81 }
82 }()
83 stopped := func(err error) error {
84 var exit *exec.ExitError
85 switch {
86 case ctx.Err() != nil:
87 return ctx.Err()
88 case errors.As(err, &exit) && exit.ExitCode() == -1:
89 return ErrInterrupted
90 }
91 return nil
92 }
93
94 bottom := f.Bottom()
95 adding = true
96 if _, err := g.output(ctx, false, "worktree", "add", "--quiet", "--detach", dir, bottom.Head); err != nil {
97 if err := stopped(err); err != nil {
98 return nil, err
99 }
100 return nil, &Refusal{Kind: NoCheckout, Layer: bottom}
101 }
102 added = true
103 for _, l := range f.Layers {
104 onto, below := f.Tip, Target
105 if l.Below != nil {
106 onto, below = p.Heads[l.Below], l.Below.Name+" as rebased"
107 }
108 // rebase.updateRefs would move the person's own branches that
109 // point into the commits rebased.
110 args := []string{"-c", "rebase.updateRefs=false", "rebase", "--quiet"}
111 if l == bottom && len(f.Cut) == 0 {
112 args = append(args, onto, l.Head)
113 } else {
114 args = append(args, "--onto", onto, l.Base, l.Head)
115 }
116 if err := wt.passing(ctx, args...); err != nil {
117 if err := stopped(err); err != nil {
118 return nil, err
119 }
120 return nil, &Refusal{Kind: Conflict, Layer: l, Below: below, Paths: conflicted(ctx, wt)}
121 }
122 head, err := wt.output(ctx, true, "rev-parse", "HEAD")
123 if err != nil {
124 if err := stopped(err); err != nil {
125 return nil, err
126 }
127 return nil, &Refusal{Kind: NoNewHead, Layer: l}
128 }
129 if head == onto {
130 return nil, &Refusal{Kind: EmptyLayer, Layer: l, Below: below}
131 }
132 p.Heads[l] = head
133 }
134 if err := p.hold(ctx, g); err != nil {
135 return nil, err
136 }
137 prepared = true
138 return p, nil
139}
140
141// conflicted is every path a stopped rebase left unmerged, as git names
142// it, whatever bytes the name holds. None is left out: a caller that
143// shows them within a bound, as a restack report does, cuts its own view.
144func conflicted(ctx context.Context, wt Git) []string {
145 out, err := wt.output(ctx, true, "diff", "--name-only", "--diff-filter=U", "-z")
146 if err != nil {
147 return nil
148 }
149 var paths []string
150 for _, p := range strings.Split(out, "\x00") {
151 if p != "" {
152 paths = append(paths, p)
153 }
154 }
155 return paths
156}
157
158// hold keeps every prepared head reachable, under refs of its own in the
159// repository, so the objects outlive the worktree until Release. Each ref
160// is in p.keep before update-ref runs, so Release deletes any it created
161// however it ended.
162func (p *Prepared) hold(ctx context.Context, g Git) error {
163 var token [8]byte
164 if _, err := rand.Read(token[:]); err != nil {
165 return err
166 }
167 var stdin strings.Builder
168 for k, l := range p.Family.Layers {
169 ref := fmt.Sprintf("%s%s/%d", keepPrefix, hex.EncodeToString(token[:]), k)
170 fmt.Fprintf(&stdin, "create %s %s\n", ref, p.Heads[l])
171 p.keep = append(p.keep, ref)
172 }
173 if _, err := g.input(ctx, true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil {
174 if ctx.Err() != nil {
175 return ctx.Err()
176 }
177 return errors.New("could not keep the rebased heads; nothing pushed")
178 }
179 return nil
180}
181
182// Release lets the prepared heads go: their refs are deleted, and git may
183// collect the objects no other ref reaches. It runs under a cancelled or
184// expired context too, as cleanup does, and for at most cleanupBound.
185func (p *Prepared) Release(ctx context.Context, g Git) error {
186 if len(p.keep) == 0 {
187 return nil
188 }
189 var stdin strings.Builder
190 for _, ref := range p.keep {
191 fmt.Fprintf(&stdin, "delete %s\n", ref)
192 }
193 done, cancel := cleanupContext(ctx)
194 defer cancel()
195 if _, err := g.input(done, true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil {
196 return errors.New("could not delete the refs that kept the rebased heads")
197 }
198 p.keep = nil
199 return nil
200}