-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmodify.go
More file actions
339 lines (281 loc) · 9.14 KB
/
modify.go
File metadata and controls
339 lines (281 loc) · 9.14 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
package cmd
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/github/gh-stack/internal/config"
"github.com/github/gh-stack/internal/git"
"github.com/github/gh-stack/internal/modify"
"github.com/github/gh-stack/internal/tui/modifyview"
"github.com/github/gh-stack/internal/tui/stackview"
"github.com/spf13/cobra"
)
type modifyOptions struct {
abort bool
cont bool
}
func ModifyCmd(cfg *config.Config) *cobra.Command {
opts := &modifyOptions{}
cmd := &cobra.Command{
Use: "modify",
Short: "Interactively restructure a stack",
Long: `Open an interactive TUI to restructure the current stack.
Operations available:
• Drop branches from the stack
• Fold branches into adjacent branches
• Reorder branches
• Rename branches
All changes are staged in the TUI and applied together when you press Ctrl+S.
After applying, run 'gh stack submit' to push changes and recreate the stack on GitHub.`,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.abort {
return runModifyAbort(cfg)
}
if opts.cont {
return runModifyContinue(cfg)
}
return runModify(cfg)
},
}
cmd.Flags().BoolVar(&opts.abort, "abort", false, "Abort the modify session and restore the stack to its pre-modify state")
cmd.Flags().BoolVar(&opts.cont, "continue", false, "Continue after resolving conflicts")
return cmd
}
func runModify(cfg *config.Config) error {
// Run all precondition checks
result, err := checkModifyPreconditions(cfg)
if err != nil {
return err
}
gitDir := result.GitDir
sf := result.StackFile
s := result.Stack
currentBranch := result.CurrentBranch
// Load branch data for the TUI
viewNodes := stackview.LoadBranchNodes(cfg, s, currentBranch, result.PRDetails)
// Reverse so index 0 = top of stack (matching visual order)
reversed := make([]stackview.BranchNode, len(viewNodes))
for i, n := range viewNodes {
reversed[len(viewNodes)-1-i] = n
}
// Convert to ModifyBranchNodes
modifyNodes := make([]modifyview.ModifyBranchNode, len(reversed))
for i, n := range reversed {
modifyNodes[i] = modifyview.ModifyBranchNode{
BranchNode: n,
OriginalPosition: i,
}
}
// Run the TUI
model := modifyview.New(modifyNodes, s.Trunk, Version)
p := tea.NewProgram(
model,
tea.WithAltScreen(),
tea.WithMouseAllMotion(),
)
finalModel, err := p.Run()
if err != nil {
return fmt.Errorf("running TUI: %w", err)
}
m, ok := finalModel.(modifyview.Model)
if !ok {
return fmt.Errorf("unexpected model type")
}
// Handle TUI result
if m.Cancelled() {
return nil
}
if !m.ApplyRequested() {
return nil
}
// Apply the staged changes
// Re-reverse nodes back to stack order (bottom to top) for the apply engine
applyNodes := m.Nodes()
reordered := make([]modifyview.ModifyBranchNode, len(applyNodes))
for i, n := range applyNodes {
reordered[len(applyNodes)-1-i] = n
}
applyResult, conflict, applyErr := modify.ApplyPlan(cfg, gitDir, s, sf, reordered, currentBranch, updateBaseSHAs)
if conflict != nil {
isCherryPick := applyErr != nil && strings.Contains(applyErr.Error(), "cherry-pick")
if isCherryPick {
cfg.Warningf("Cherry-pick conflict folding %s", conflict.Branch)
} else {
cfg.Warningf("Rebasing %s — conflict", conflict.Branch)
}
printConflictDetailsWithContinue(cfg, conflict.Branch, "gh stack modify --continue")
cfg.Printf("")
cfg.Printf("Or restore the stack to its pre-modify state with `%s`",
cfg.ColorCyan("gh stack modify --abort"))
return ErrConflict
}
if applyErr != nil {
cfg.Errorf("failed to apply modifications: %s", applyErr)
return ErrSilent
}
// Print success summary
printModifySuccess(cfg, applyResult, s.ID != "")
return nil
}
// printModifySuccess prints a summary of what was applied.
func printModifySuccess(cfg *config.Config, result *modifyview.ApplyResult, hasRemoteStack bool) {
if result == nil {
return
}
cfg.Printf("")
cfg.Successf("Stack modified successfully")
for _, r := range result.RenamedBranches {
cfg.Printf(" Renamed: %s → %s", r.OldName, r.NewName)
}
for _, d := range result.DroppedPRs {
cfg.Printf(" Dropped: %s (PR #%d remains open — close with `%s`)",
d.Branch, d.PRNumber, cfg.ColorCyan(fmt.Sprintf("gh pr close %d", d.PRNumber)))
}
if result.MovedBranches > 0 {
cfg.Printf(" Rebased %d %s", result.MovedBranches,
plural(result.MovedBranches, "branch", "branches"))
}
cfg.Printf("")
if hasRemoteStack {
cfg.Printf("Run `%s` to push your changes and update the stack of PRs on GitHub",
cfg.ColorCyan("gh stack submit"))
}
}
// runModifyAbort handles recovery to a pre-modify state.
func runModifyAbort(cfg *config.Config) error {
gitDir, err := git.GitDir()
if err != nil {
cfg.Errorf("not a git repository")
return ErrNotInStack
}
state, err := modify.LoadState(gitDir)
if err != nil {
cfg.Errorf("failed to read modify state: %s", err)
return ErrSilent
}
if state == nil {
cfg.Printf("No modify session to abort")
return nil
}
switch state.Phase {
case modify.PhaseApplying:
cfg.Printf("A modify session was interrupted during the apply phase")
cfg.Printf("Restoring stack to pre-modify state...")
if err := modify.UnwindFromStateFile(cfg, gitDir); err != nil {
cfg.Errorf("recovery failed: %s", err)
cfg.Printf("The stack may be in an inconsistent state.")
cfg.Printf("Try `%s` to fix, or `%s` + `%s` to recreate.",
cfg.ColorCyan("gh stack rebase"), cfg.ColorCyan("gh stack unstack --local"),
cfg.ColorCyan("gh stack init --adopt"))
return ErrSilent
}
cfg.Successf("Stack restored successfully")
return nil
case modify.PhasePendingSubmit:
cfg.Printf("A modify completed but the stack has not been submitted")
cfg.Printf("Run `%s` to push changes and recreate the stack on GitHub",
cfg.ColorCyan("gh stack submit"))
return nil
default:
cfg.Errorf("unexpected modify state phase: %s", state.Phase)
cfg.Printf("Clearing invalid state file...")
modify.ClearState(gitDir)
return nil
}
}
// runModifyContinue continues applying after the user resolves a rebase conflict.
func runModifyContinue(cfg *config.Config) error {
gitDir, err := git.GitDir()
if err != nil {
cfg.Errorf("not a git repository")
return ErrNotInStack
}
if err := modify.ContinueApply(cfg, gitDir, updateBaseSHAs); err != nil {
cfg.Errorf("%s", err)
return ErrConflict
}
return nil
}
// ---------------------------------------------------------------------------
// Preconditions
// ---------------------------------------------------------------------------
// checkModifyPreconditions runs all precondition checks for the modify command.
func checkModifyPreconditions(cfg *config.Config) (*loadStackResult, error) {
if !cfg.IsInteractive() {
cfg.Errorf("modify requires an interactive terminal")
return nil, ErrSilent
}
result, err := loadStack(cfg, "")
if err != nil {
return nil, ErrNotInStack
}
gitDir := result.GitDir
s := result.Stack
// No existing modify state file
if err := checkNoModifyInProgress(cfg, gitDir); err != nil {
return nil, err
}
// No rebase in progress
if git.IsRebaseInProgress() {
cfg.Errorf("a rebase is currently in progress")
cfg.Printf("Complete the rebase with `%s` or abort with `%s`",
cfg.ColorCyan("gh stack rebase --continue"),
cfg.ColorCyan("gh stack rebase --abort"))
return nil, ErrRebaseActive
}
// Clean working tree
if dirty, err := git.HasUncommittedChanges(); err != nil {
cfg.Errorf("failed to check working tree status: %s", err)
return nil, ErrSilent
} else if dirty {
cfg.Errorf("uncommitted changes in working tree")
cfg.Printf("Commit or stash your changes before running modify")
return nil, ErrSilent
}
// Show loading indicator while syncing PRs
fmt.Fprintf(cfg.Err, "Loading stack...")
// Sync PR state and check merge queue
prDetails := syncStackPRs(cfg, s)
result.PRDetails = prDetails
fmt.Fprintf(cfg.Err, "\r\033[2K")
if err := modify.CheckNoMergeQueuePRs(cfg, s); err != nil {
return nil, ErrSilent
}
// Stack linearity check
if err := modify.CheckStackLinearity(cfg, s); err != nil {
return nil, ErrSilent
}
return result, nil
}
// checkNoModifyInProgress checks if a modify state file already exists.
func checkNoModifyInProgress(cfg *config.Config, gitDir string) error {
state, err := modify.LoadState(gitDir)
if err != nil {
cfg.Warningf("failed to read modify state: %v", err)
return nil
}
if state == nil {
return nil
}
switch state.Phase {
case modify.PhaseApplying:
cfg.Errorf("a previous modify session was interrupted")
cfg.Printf("Run `%s` to restore your stack",
cfg.ColorCyan("gh stack modify --abort"))
return ErrModifyRecovery
case modify.PhaseConflict:
cfg.Errorf("a modify has unresolved conflicts")
cfg.Printf("Run `%s` to continue, or `%s` to restore your stack",
cfg.ColorCyan("gh stack modify --continue"),
cfg.ColorCyan("gh stack modify --abort"))
return ErrSilent
case modify.PhasePendingSubmit:
cfg.Errorf("a modify was completed but the stack has not been submitted yet")
cfg.Printf("Run `%s` to push changes and recreate the stack on GitHub",
cfg.ColorCyan("gh stack submit"))
return ErrSilent
default:
cfg.Errorf("unexpected modify state phase: %s", state.Phase)
return ErrSilent
}
}