| 1 | package rebase |
| 2 | |
| 3 | import ( |
| 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. |
| 16 | var 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. |
| 21 | const 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. |
| 25 | type 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. A cancelled context ends |
| 40 | // the git it is running, and Prepare returns the context's error; git |
| 41 | // ended by a signal gives ErrInterrupted. |
| 42 | func Prepare(ctx context.Context, g Git, f *Family) (*Prepared, error) { |
| 43 | if err := f.Check(); err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | if err := ctx.Err(); err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | dir, err := os.MkdirTemp("", "valley-rebase.") |
| 50 | if err != nil { |
| 51 | return nil, &Refusal{Kind: NoWorktree} |
| 52 | } |
| 53 | wt := g.in(dir) |
| 54 | added := false |
| 55 | // git runs in dir only once it is a worktree: a directory that is not |
| 56 | // one would leave git to find the repository above it. The cleanup |
| 57 | // runs under a context of its own, since it must run when the caller's |
| 58 | // is cancelled. |
| 59 | defer func() { |
| 60 | done := context.WithoutCancel(ctx) |
| 61 | if added { |
| 62 | wt.succeeds(done, true, "rebase", "--abort") |
| 63 | g.succeeds(done, true, "worktree", "remove", "--force", dir) |
| 64 | } |
| 65 | os.RemoveAll(dir) |
| 66 | }() |
| 67 | stopped := func(err error) error { |
| 68 | var exit *exec.ExitError |
| 69 | switch { |
| 70 | case ctx.Err() != nil: |
| 71 | return ctx.Err() |
| 72 | case errors.As(err, &exit) && exit.ExitCode() == -1: |
| 73 | return ErrInterrupted |
| 74 | } |
| 75 | return nil |
| 76 | } |
| 77 | |
| 78 | bottom := f.Bottom() |
| 79 | if _, err := g.output(ctx, false, "worktree", "add", "--quiet", "--detach", dir, bottom.Head); err != nil { |
| 80 | if err := stopped(err); err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | return nil, &Refusal{Kind: NoCheckout, Layer: bottom} |
| 84 | } |
| 85 | added = true |
| 86 | p := &Prepared{Family: f, Heads: map[*Layer]string{}} |
| 87 | for _, l := range f.Layers { |
| 88 | onto, below := f.Tip, Target |
| 89 | if l.Below != nil { |
| 90 | onto, below = p.Heads[l.Below], l.Below.Name+" as rebased" |
| 91 | } |
| 92 | // rebase.updateRefs would move the person's own branches that |
| 93 | // point into the commits rebased. |
| 94 | args := []string{"-c", "rebase.updateRefs=false", "rebase", "--quiet"} |
| 95 | if l == bottom && len(f.Cut) == 0 { |
| 96 | args = append(args, onto, l.Head) |
| 97 | } else { |
| 98 | args = append(args, "--onto", onto, l.Base, l.Head) |
| 99 | } |
| 100 | if err := wt.passing(ctx, args...); err != nil { |
| 101 | if err := stopped(err); err != nil { |
| 102 | return nil, err |
| 103 | } |
| 104 | return nil, &Refusal{Kind: Conflict, Layer: l, Below: below, Paths: conflicted(ctx, wt)} |
| 105 | } |
| 106 | head, err := wt.output(ctx, true, "rev-parse", "HEAD") |
| 107 | if err != nil { |
| 108 | if err := stopped(err); err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | return nil, &Refusal{Kind: NoNewHead, Layer: l} |
| 112 | } |
| 113 | if head == onto { |
| 114 | return nil, &Refusal{Kind: EmptyLayer, Layer: l, Below: below} |
| 115 | } |
| 116 | p.Heads[l] = head |
| 117 | } |
| 118 | if err := p.hold(ctx, g); err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | return p, nil |
| 122 | } |
| 123 | |
| 124 | // conflicted is the paths a stopped rebase left unmerged, at most |
| 125 | // maxConflictPaths of them. |
| 126 | func conflicted(ctx context.Context, wt Git) []string { |
| 127 | out, err := wt.output(ctx, true, "diff", "--name-only", "--diff-filter=U", "-z") |
| 128 | if err != nil { |
| 129 | return nil |
| 130 | } |
| 131 | var paths []string |
| 132 | for _, p := range strings.Split(out, "\x00") { |
| 133 | if p != "" && len(paths) < maxConflictPaths { |
| 134 | paths = append(paths, p) |
| 135 | } |
| 136 | } |
| 137 | return paths |
| 138 | } |
| 139 | |
| 140 | // hold keeps every prepared head reachable, under refs of its own in the |
| 141 | // repository, so the objects outlive the worktree until Release. |
| 142 | func (p *Prepared) hold(ctx context.Context, g Git) error { |
| 143 | var token [8]byte |
| 144 | if _, err := rand.Read(token[:]); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | var stdin strings.Builder |
| 148 | for k, l := range p.Family.Layers { |
| 149 | ref := fmt.Sprintf("%s%s/%d", keepPrefix, hex.EncodeToString(token[:]), k) |
| 150 | fmt.Fprintf(&stdin, "create %s %s\n", ref, p.Heads[l]) |
| 151 | p.keep = append(p.keep, ref) |
| 152 | } |
| 153 | if _, err := g.input(ctx, true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil { |
| 154 | if ctx.Err() != nil { |
| 155 | return ctx.Err() |
| 156 | } |
| 157 | return errors.New("could not keep the rebased heads; nothing pushed") |
| 158 | } |
| 159 | return nil |
| 160 | } |
| 161 | |
| 162 | // Release lets the prepared heads go: their refs are deleted, and git may |
| 163 | // collect the objects no other ref reaches. It runs under a cancelled |
| 164 | // context too, as cleanup does. |
| 165 | func (p *Prepared) Release(ctx context.Context, g Git) error { |
| 166 | if len(p.keep) == 0 { |
| 167 | return nil |
| 168 | } |
| 169 | var stdin strings.Builder |
| 170 | for _, ref := range p.keep { |
| 171 | fmt.Fprintf(&stdin, "delete %s\n", ref) |
| 172 | } |
| 173 | if _, err := g.input(context.WithoutCancel(ctx), true, strings.NewReader(stdin.String()), "update-ref", "--stdin"); err != nil { |
| 174 | return errors.New("could not delete the refs that kept the rebased heads") |
| 175 | } |
| 176 | p.keep = nil |
| 177 | return nil |
| 178 | } |