summaryrefslogtreecommitdiffstats
path: root/pkg/gui/controllers/undo_controller.go
blob: 8bd44a86debea3a2d1d1992eb42a07a15f9456ec (plain)
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
package controllers

import (
	"errors"
	"fmt"

	"github.com/jesseduffield/gocui"
	"github.com/jesseduffield/lazygit/pkg/commands/types/enums"
	"github.com/jesseduffield/lazygit/pkg/gui/types"
	"github.com/jesseduffield/lazygit/pkg/utils"
)

// Quick summary of how this all works:
// when you want to undo or redo, we start from the top of the reflog and work
// down until we've reached the last user-initiated reflog entry that hasn't already been undone
// we then do the reverse of what that reflog describes.
// When we do this, we create a new reflog entry, and tag it as either an undo or redo
// Then, next time we want to undo, we'll use those entries to know which user-initiated
// actions we can skip. E.g. if I do three things, A, B, and C, and hit undo twice,
// the reflog will read UUCBA, and when I read the first two undos, I know to skip the following
// two user actions, meaning we end up undoing reflog entry C. Redoing works in a similar way.

type UndoController struct {
	baseController
	c *ControllerCommon
}

var _ types.IController = &UndoController{}

func NewUndoController(
	c *ControllerCommon,
) *UndoController {
	return &UndoController{
		baseController: baseController{},
		c:              c,
	}
}

type ReflogActionKind int

const (
	CHECKOUT ReflogActionKind = iota
	COMMIT
	REBASE
	CURRENT_REBASE
)

type reflogAction struct {
	kind ReflogActionKind
	from string
	to   string
}

func (self *UndoController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {
	bindings := []*types.Binding{
		{
			Key:         opts.GetKey(opts.Config.Universal.Undo),
			Handler:     self.reflogUndo,
			Description: self.c.Tr.UndoReflog,
			Tooltip:     self.c.Tr.UndoTooltip,
		},
		{
			Key:         opts.GetKey(opts.Config.Universal.Redo),
			Handler:     self.reflogRedo,
			Description: self.c.Tr.RedoReflog,
			Tooltip:     self.c.Tr.RedoTooltip,
		},
	}

	return bindings
}

func (self *UndoController) Context() types.Context {
	return nil
}

func (self *UndoController) reflogUndo() error {
	undoEnvVars := []string{"GIT_REFLOG_ACTION=[lazygit undo]"}
	undoingStatus := self.c.Tr.UndoingStatus

	if self.c.Git().Status.WorkingTreeState() == enums.REBASE_MODE_REBASING {
		return errors.New(self.c.Tr.CantUndoWhileRebasing)
	}

	return self.parseReflogForActions(func(counter int, action reflogAction) (bool, error) {
		if counter != 0 {
			return false, nil
		}

		switch action.kind {
		case COMMIT, REBASE:
			return true, self.c.Confirm(types.ConfirmOpts{
				Title:  self.c.Tr.Actions.Undo,
				Prompt: fmt.Sprintf(self.c.Tr.HardResetAutostashPrompt, action.from),
				HandleConfirm: func() error {
					self.c.LogAction(self.c.Tr.Actions.Undo)
					return self.hardResetWithAutoStash(action.from, hardResetOptions{
						EnvVars:       undoEnvVars,
						WaitingStatus: undoingStatus,
					})
				},
			})
		case CHECKOUT:
			return true, self.c.Confirm(types.ConfirmOpts{
				Title:  self.c.Tr.Actions.Undo,
				Prompt: fmt.Sprintf(self.c.Tr.CheckoutPrompt, action.from),
				HandleConfirm: func() error {
					self.c.LogAction(self.c.Tr.Actions.Undo)
					return self.c.Helpers().Refs.CheckoutRef(action.from, types.CheckoutRefOptions{
						EnvVars:       undoEnvVars,
						WaitingStatus: undoingStatus,
					})
				},
			})

		case CURRENT_REBASE:
			// do nothing
		}

		self.c.Log.Error("didn't match on the user action when trying to undo")
		return true, nil
	})
}

func (self *UndoController) reflogRedo() error {
	redoEnvVars := []string{"GIT_REFLOG_ACTION=[lazygit redo]"}
	redoingStatus := self.c.Tr.RedoingStatus

	if self.c.Git().Status.WorkingTreeState() == enums.REBASE_MODE_REBASING {
		return errors.New(self.c.Tr.CantRedoWhileRebasing)
	}

	return self.parseReflogForActions(func(counter int, action reflogAction) (bool, error) {
		// if we're redoing and the counter is zero, we just return
		if counter == 0 {
			return true, nil
		} else if counter > 1 {
			return false, nil
		}

		switch action.kind {
		case COMMIT, REBASE:
			return true, self.c.Confirm(types.ConfirmOpts{
				Title:  self.c.Tr.Actions.Redo,
				Prompt: fmt.Sprintf(self.c.Tr.HardResetAutostashPrompt, action.to),
				HandleConfirm: func() error {
					self.c.LogAction(self.c.Tr.Actions.Redo)
					return self.hardResetWithAutoStash(action.to, hardResetOptions{
						EnvVars:       redoEnvVars,
						WaitingStatus: redoingStatus,
					})
				},
			})

		case CHECKOUT:
			return true, self.c.Confirm(types.ConfirmOpts{
				Title:  self.c.Tr.Actions.Redo,
				Prompt: fmt.Sprintf(self.c.Tr.CheckoutPrompt, action.to),
				HandleConfirm: func() error {
					self.c.LogAction(self.c.Tr.Actions.Redo)
					return self.c.Helpers().Refs.CheckoutRef(action.to, types.CheckoutRefOptions{
						EnvVars:       redoEnvVars,
						WaitingStatus: redoingStatus,
					})
				},
			})
		case CURRENT_REBASE:
			// do nothing
		}

		self.c.Log.Error("didn't match on the user action when trying to redo")
		return true, nil
	})
}

// Here we're going through the reflog and maintaining a counter that represents how many
// undos/redos/user actions we've seen. when we hit a user action we call the callback specifying
// what the counter is up to and the nature of the action.
// If we find ourselves mid-rebase, we just return because undo/redo mid rebase
// requires knowledge of previous TODO file states, which you can't just get from the reflog.
// Though we might support this later, hence the use of the CURRENT_REBASE action kind.
func (self *UndoController) parseReflogForActions(onUserAction func(counter int, action reflogAction) (bool, error)) error {
	counter := 0
	reflogCommits := self.c.Model().FilteredReflogCommits
	rebaseFinishCommitHash := ""
	var action *reflogAction
	for reflogCommitIdx, reflogCommit := range reflogCommits {
		action = nil

		prevCommitHash := ""
		if len(reflogCommits)-1 >= reflogCommitIdx+1 {
			prevCommitHash = reflogCommits[reflogCommitIdx+1].Hash
		}

		if rebaseFinishCommitHash == "" {
			if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^\[lazygit undo\]`); ok {
				counter++
			} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^\[lazygit redo\]`); ok {
				counter--
			} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(abort\)|^rebase (-i )?\(finish\)`); ok {
				rebaseFinishCommitHash = reflogCommit.Hash
			} else if ok, match := utils.FindStringSubmatch(reflogCommit.Name, `^checkout: moving from ([\S]+) to ([\S]+)`); ok {
				action = &reflogAction{kind: CHECKOUT, from: match[1], to: match[2]}
			} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^commit|^reset: moving to|^pull`); ok {
				action = &reflogAction{kind: COMMIT, from: prevCommitHash, to: reflogCommit.Hash}
			} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok {
				// if we're here then we must be currently inside an interactive rebase
				action = &reflogAction{kind: CURRENT_REBASE, from: prevCommitHash}
			}
		} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok {
			action = &reflogAction{kind: REBASE, from: prevCommitHash, to: