-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_rebase.go
More file actions
208 lines (185 loc) · 5.55 KB
/
Copy pathcli_rebase.go
File metadata and controls
208 lines (185 loc) · 5.55 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
package main
import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"
)
// runRebaseCmd handles `loom rebase` and `loom rebase pr <number>`.
func runRebaseCmd(args []string) error {
if len(args) == 0 {
if err := rebaseUpstream(); err != nil {
return err
}
return pushCurrentBranch()
}
switch args[0] {
case "pr":
if len(args) < 2 {
return fmt.Errorf("usage: loom rebase pr <number>")
}
number, err := strconv.Atoi(args[1])
if err != nil {
return fmt.Errorf("invalid PR number %q: %w", args[1], err)
}
return rebasePR(number)
default:
return fmt.Errorf("unknown rebase subcommand %q (expected: pr <number>)", args[0])
}
}
// gitOutput runs a git command and returns trimmed stdout, or an error.
func gitOutput(args ...string) (string, error) {
cmd := exec.Command("git", args...)
out, err := cmd.Output()
if err != nil {
if exit, ok := err.(*exec.ExitError); ok {
return "", fmt.Errorf("%s", strings.TrimSpace(string(exit.Stderr)))
}
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// gitRun runs a git command, inheriting stdin/stdout/stderr so interactive
// editors and rebase sequences work correctly.
func gitRun(args ...string) error {
cmd := exec.Command("git", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// pushCurrentBranch force-pushes (with lease) the current branch to its
// upstream. Since a rebase rewrites history, a force-push is required.
// --force-with-lease is used to avoid overwriting remote changes that we
// don't know about locally.
func pushCurrentBranch() error {
fmt.Fprintln(os.Stderr, "Pushing...")
if err := gitRun("push", "--force-with-lease"); err != nil {
return fmt.Errorf("push: %w", err)
}
return nil
}
// currentBranch returns the name of the current branch.
func currentBranch() (string, error) {
out, err := gitOutput("rev-parse", "--abbrev-ref", "HEAD")
if err != nil {
return "", fmt.Errorf("get current branch: %w", err)
}
if out == "HEAD" {
return "", fmt.Errorf("HEAD is detached (no current branch)")
}
return out, nil
}
// remoteExists reports whether a git remote with the given name exists.
func remoteExists(name string) bool {
out, err := gitOutput("remote")
if err != nil {
return false
}
for _, r := range strings.Fields(out) {
if r == name {
return true
}
}
return false
}
// defaultBranchForRemote returns the default branch of the given remote
// (e.g. "main", "master") by querying the remote's HEAD ref.
func defaultBranchForRemote(remote string) (string, error) {
out, err := gitOutput("symbolic-ref", "refs/remotes/"+remote+"/HEAD")
if err != nil {
return "", fmt.Errorf("determine default branch for %s: %w", remote, err)
}
// Output: refs/remotes/<remote>/<branch>
branch := out
if idx := strings.LastIndex(out, "/"); idx >= 0 {
branch = out[idx+1:]
}
return branch, nil
}
// rebaseUpstream rebases the current branch onto the remote's default branch
// (e.g. origin/main). It fetches the remote first.
func rebaseUpstream() error {
branch, err := currentBranch()
if err != nil {
return err
}
remote := "origin"
if !remoteExists(remote) {
out, err := gitOutput("remote")
if err != nil || out == "" {
return fmt.Errorf("no remotes configured")
}
remote = strings.Fields(out)[0]
}
defBranch, err := defaultBranchForRemote(remote)
if err != nil {
return err
}
target := remote + "/" + defBranch
fmt.Fprintf(os.Stderr, "Fetching %s...\n", remote)
if err := gitRun("fetch", remote); err != nil {
return fmt.Errorf("fetch %s: %w", remote, err)
}
fmt.Fprintf(os.Stderr, "Rebasing %s onto %s...\n", branch, target)
return gitRun("rebase", target)
}
// rebasePR checks out the PR branch via `gh`, rebases it onto the upstream
// default branch, then returns to the original branch.
func rebasePR(number int) error {
origBranch, err := currentBranch()
if err != nil {
return err
}
// Find the PR's head branch name.
prOut, err := exec.Command("gh", "pr", "view", strconv.Itoa(number), "--json", "headRefName").Output()
if err != nil {
return fmt.Errorf("gh pr view %d: %w", number, err)
}
out := strings.TrimSpace(string(prOut))
branch := parseJSONField(out, "headRefName")
if branch == "" {
return fmt.Errorf("could not determine PR branch name from gh output")
}
// Determine where to return if something goes wrong.
defer func() {
if cur, err := currentBranch(); err == nil && cur != origBranch {
fmt.Fprintf(os.Stderr, "Returning to %s...\n", origBranch)
_ = gitRun("checkout", origBranch)
}
}()
fmt.Fprintf(os.Stderr, "Checking out PR #%d (%s)...\n", number, branch)
if err := gitRun("checkout", branch); err != nil {
return fmt.Errorf("checkout %s: %w", branch, err)
}
fmt.Fprintf(os.Stderr, "Rebasing %s onto upstream...\n", branch)
if err := rebaseUpstream(); err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Pushing...")
if err := gitRun("push", "--force-with-lease"); err != nil {
return fmt.Errorf("push: %w", err)
}
fmt.Fprintf(os.Stderr, "Returning to %s...\n", origBranch)
if err := gitRun("checkout", origBranch); err != nil {
return fmt.Errorf("return to %s: %w", origBranch, err)
}
return nil
}
// parseJSONField extracts a string field value from minimal JSON like
// {"headRefName":"feat/x"}. It avoids pulling in encoding/json for a single
// field and tolerates extra fields.
func parseJSONField(json, field string) string {
key := `"` + field + `":"`
idx := strings.Index(json, key)
if idx < 0 {
return ""
}
start := idx + len(key)
end := strings.Index(json[start:], `"`)
if end < 0 {
return ""
}
return json[start : start+end]
}