-
Notifications
You must be signed in to change notification settings - Fork 23
/
prune.go
362 lines (332 loc) · 10.3 KB
/
prune.go
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package gitui
import (
"fmt"
"strings"
"emperror.dev/errors"
"github.com/aviator-co/av/internal/git"
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/colors"
"github.com/aviator-co/av/internal/utils/uiutils"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/erikgeiser/promptkit/selection"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
)
const (
continueDeletion = "Yes. Delete these merged branches."
abortDeletion = "No. Do not delete the merged branches."
reasonNoPullRequest = "PR not found."
reasonHasChild = "PR is already merged, but still have a child."
reasonPRHeadNotFound = "PR is already merged, but we cannot find which commit is merged."
reasonPRHeadIsDifferent = "PR is already merged, but the local branch points to a different commit than the merged commit."
)
type deleteCandidate struct {
branch plumbing.ReferenceName
commit plumbing.Hash
}
type noDeleteBranch struct {
branch plumbing.ReferenceName
reason string
}
func NewPruneBranchModel(
repo *git.Repo,
db meta.DB,
pruneFlag string,
targetBranches []plumbing.ReferenceName,
initialBranch string,
) *PruneBranchModel {
return &PruneBranchModel{
repo: repo,
db: db,
pruneFlag: pruneFlag,
targetBranches: targetBranches,
initialBranch: initialBranch,
spinner: spinner.New(spinner.WithSpinner(spinner.Dot)),
help: help.New(),
chooseNoPrune: pruneFlag == "no",
}
}
type PruneBranchModel struct {
repo *git.Repo
db meta.DB
pruneFlag string
targetBranches []plumbing.ReferenceName
initialBranch string
spinner spinner.Model
help help.Model
chooseNoPrune bool
deleteCandidates []deleteCandidate
noDeleteBranches []noDeleteBranch
deletePrompt *selection.Model[string]
calculatingCandidates bool
askingForConfirmation bool
runningDeletion bool
done bool
}
type PruneBranchProgress struct {
candidateCalculationDone bool
deletionDone bool
}
type PruneBranchDone struct{}
func (vm *PruneBranchModel) Init() tea.Cmd {
vm.calculatingCandidates = true
return tea.Batch(vm.spinner.Tick, vm.calculateMergedBranches)
}
func (vm *PruneBranchModel) Update(msg tea.Msg) (*PruneBranchModel, tea.Cmd) {
switch msg := msg.(type) {
case *PruneBranchProgress:
if msg.candidateCalculationDone {
vm.calculatingCandidates = false
if len(vm.deleteCandidates) == 0 || vm.chooseNoPrune {
vm.done = true
return vm, func() tea.Msg { return &PruneBranchDone{} }
}
if vm.pruneFlag == "yes" {
vm.runningDeletion = true
return vm, vm.runDelete
}
vm.askingForConfirmation = true
vm.deletePrompt = uiutils.NewPromptModel("Are you OK with deleting these merged branches?", []string{continueDeletion, abortDeletion})
return vm, vm.deletePrompt.Init()
}
if msg.deletionDone {
vm.runningDeletion = false
vm.done = true
return vm, func() tea.Msg { return &PruneBranchDone{} }
}
case tea.KeyMsg:
if vm.askingForConfirmation {
switch msg.String() {
case "enter":
c, err := vm.deletePrompt.Value()
if err != nil {
return vm, func() tea.Msg { return err }
}
vm.askingForConfirmation = false
vm.deletePrompt = nil
if c != continueDeletion {
vm.chooseNoPrune = true
vm.done = true
return vm, func() tea.Msg { return &PruneBranchDone{} }
}
vm.runningDeletion = true
return vm, vm.runDelete
case "ctrl+c":
return vm, tea.Quit
default:
_, cmd := vm.deletePrompt.Update(msg)
return vm, cmd
}
}
case spinner.TickMsg:
var cmd tea.Cmd
vm.spinner, cmd = vm.spinner.Update(msg)
return vm, cmd
}
return vm, nil
}
func (vm *PruneBranchModel) View() string {
if vm.calculatingCandidates {
return colors.ProgressStyle.Render(vm.spinner.View() + "Finding the changed branches...\n")
}
sb := strings.Builder{}
if len(vm.deleteCandidates) == 0 {
sb.WriteString(colors.SuccessStyle.Render("✓ No merged branches to delete\n"))
} else if vm.askingForConfirmation {
sb.WriteString("Confirming the deletion of merged branches\n")
} else if vm.runningDeletion {
sb.WriteString(colors.ProgressStyle.Render(vm.spinner.View() + "Deleting merged branches...\n"))
} else if vm.done {
if vm.chooseNoPrune {
sb.WriteString(colors.SuccessStyle.Render("✓ Not deleting merged branches\n"))
} else {
sb.WriteString(colors.SuccessStyle.Render("✓ Deleted the merged branches\n"))
}
}
if len(vm.noDeleteBranches) > 0 {
sb.WriteString("\n")
sb.WriteString(" Following merged branches will be kept.\n")
sb.WriteString("\n")
sb.WriteString(lipgloss.NewStyle().MarginLeft(4).Render(vm.viewNoDeleteBranches()))
}
if len(vm.deleteCandidates) > 0 {
sb.WriteString("\n")
if vm.runningDeletion {
sb.WriteString(" Following merged branches are being deleted ...\n")
} else if vm.done && !vm.chooseNoPrune {
sb.WriteString(" Following merged branches are deleted.\n")
} else {
sb.WriteString(" Following merged branches can be deleted.\n")
}
sb.WriteString("\n")
sb.WriteString(lipgloss.NewStyle().MarginLeft(4).Render(vm.viewCandidates()))
}
if vm.deletePrompt != nil {
sb.WriteString("\n")
sb.WriteString(vm.deletePrompt.View())
sb.WriteString(vm.help.ShortHelpView(uiutils.PromptKeys))
}
return sb.String()
}
func (vm *PruneBranchModel) viewCandidates() string {
sb := strings.Builder{}
for _, branch := range vm.deleteCandidates {
sb.WriteString(fmt.Sprintf("%s: %s\n", branch.branch.Short(), branch.commit.String()))
}
return sb.String()
}
func (vm *PruneBranchModel) viewNoDeleteBranches() string {
sb := strings.Builder{}
for _, branch := range vm.noDeleteBranches {
sb.WriteString(branch.branch.Short() + ": " + branch.reason + "\n")
}
return sb.String()
}
func (vm *PruneBranchModel) runDelete() tea.Msg {
// Checkout the detached HEAD so that we can delete the branches. We cannot delete the
// branches that are checked out.
if err := vm.repo.Detach(); err != nil {
return err
}
// Delete in the reverse order just in case. The targetBranches are sorted in the parent ->
// child order.
for i := len(vm.deleteCandidates) - 1; i >= 0; i-- {
branch := vm.deleteCandidates[i]
if _, err := vm.repo.Git("branch", "-D", branch.branch.Short()); err != nil {
return errors.Errorf("cannot delete merged branch %q: %v", branch.branch.Short(), err)
}
tx := vm.db.WriteTx()
tx.DeleteBranch(branch.branch.Short())
if err := tx.Commit(); err != nil {
return err
}
}
// Restore the checked out state.
if err := vm.CheckoutInitialState(); err != nil {
return err
}
return &PruneBranchProgress{deletionDone: true}
}
func (vm *PruneBranchModel) CheckoutInitialState() error {
if vm.initialBranch != "" {
initialHead, err := vm.repo.GoGitRepo().
Reference(plumbing.NewBranchReferenceName(vm.initialBranch), true)
if err == nil {
if initialHead.Type() == plumbing.HashReference {
// Normal reference that points to a commit. Checking out.
if _, err := vm.repo.CheckoutBranch(&git.CheckoutBranch{Name: initialHead.Name().Short()}); err != nil {
return err
}
return nil
}
} else if err != plumbing.ErrReferenceNotFound {
return err
}
}
// The branch is deleted. Let's checkout the default branch.
defaultBranch, err := vm.repo.DefaultBranch()
if err != nil {
return err
}
defaultBranchRef := plumbing.NewBranchReferenceName(defaultBranch)
ref, err := vm.repo.GoGitRepo().Reference(defaultBranchRef, true)
if err == nil {
if _, err := vm.repo.CheckoutBranch(&git.CheckoutBranch{Name: ref.Name().Short()}); err != nil {
return err
}
return nil
}
// The default branch doesn't exist. Check the remote tracking branch.
remote, err := vm.repo.GoGitRepo().Remote(vm.repo.GetRemoteName())
if err != nil {
return errors.Errorf("failed to get remote %s: %v", vm.repo.GetRemoteName(), err)
}
remoteConfig := remote.Config()
rtb := mapToRemoteTrackingBranch(remoteConfig, defaultBranchRef)
if rtb != nil {
ref, err = vm.repo.GoGitRepo().Reference(*rtb, true)
if err == nil {
if _, err := vm.repo.CheckoutBranch(&git.CheckoutBranch{Name: ref.Hash().String()}); err != nil {
return err
}
return nil
}
}
// No remote tracking branch. Skip.
return nil
}
func (vm *PruneBranchModel) calculateMergedBranches() tea.Msg {
remoteBranches, err := vm.repo.LsRemote(vm.repo.GetRemoteName())
if err != nil {
return err
}
var noDeleteBranches []noDeleteBranch
var deleteCandidates []deleteCandidate
for _, br := range vm.targetBranches {
avbr, _ := vm.db.ReadTx().Branch(br.Short())
if avbr.MergeCommit == "" {
continue
}
if vm.hasOpenChildren(br) {
noDeleteBranches = append(
noDeleteBranches,
noDeleteBranch{branch: br, reason: reasonHasChild},
)
continue
}
if avbr.PullRequest == nil {
noDeleteBranches = append(
noDeleteBranches,
noDeleteBranch{branch: br, reason: reasonNoPullRequest},
)
continue
}
remoteHash, ok := remoteBranches[fmt.Sprintf("refs/pull/%d/head", avbr.PullRequest.Number)]
if !ok {
noDeleteBranches = append(
noDeleteBranches,
noDeleteBranch{branch: br, reason: reasonPRHeadNotFound},
)
continue
}
ref, err := vm.repo.GoGitRepo().Reference(plumbing.ReferenceName(br), true)
if err != nil {
return err
}
if ref.Hash().String() != remoteHash {
noDeleteBranches = append(
noDeleteBranches,
noDeleteBranch{branch: br, reason: reasonPRHeadIsDifferent},
)
continue
}
deleteCandidates = append(deleteCandidates, deleteCandidate{branch: br, commit: ref.Hash()})
}
vm.noDeleteBranches = noDeleteBranches
vm.deleteCandidates = deleteCandidates
return &PruneBranchProgress{candidateCalculationDone: true}
}
func (vm *PruneBranchModel) hasOpenChildren(br plumbing.ReferenceName) bool {
for _, child := range meta.SubsequentBranches(vm.db.ReadTx(), br.Short()) {
childBr, _ := vm.db.ReadTx().Branch(child)
if childBr.MergeCommit == "" {
return true
}
}
return false
}
func mapToRemoteTrackingBranch(
remoteConfig *config.RemoteConfig,
refName plumbing.ReferenceName,
) *plumbing.ReferenceName {
for _, fetch := range remoteConfig.Fetch {
if fetch.Match(refName) {
dst := fetch.Dst(refName)
return &dst
}
}
return nil
}