-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
105 lines (91 loc) · 1.83 KB
/
history.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
package cli
type line struct {
original, edited string
isEdited bool
}
type history struct {
entries []*line
index int
}
func (h *history) isNew() bool {
return len(h.entries) == 0 || h.index == len(h.entries)
}
func (h *history) isFirst() bool {
return len(h.entries) == 0 || h.index == 0
}
func (h *history) isLast() bool {
return len(h.entries) == 0 || h.index == len(h.entries)-1
}
func (h *history) first() bool {
if h.isFirst() {
return false
}
h.index = 0
return true
}
func (h *history) last() bool {
if h.isLast() {
return false
}
h.index = len(h.entries) - 1
return true
}
func (h *history) prev() bool {
if h.isFirst() {
return false
}
h.index--
return true
}
func (h *history) next() bool {
if h.isLast() {
return false
}
h.index++
return true
}
func (h *history) new() {
h.last()
if h.get() == "" {
return
}
h.index++
h.entries = append(h.entries, &line{})
}
func (h *history) get() string {
if h.isNew() {
return ""
}
if h.entries[h.index].isEdited {
return h.entries[h.index].edited
}
return h.entries[h.index].original
}
func (h *history) set(s string) {
// If last history entry, store changes in original, otherwise store in edited
if h.isNew() {
h.entries = append(h.entries, &line{original: s})
return
} else if h.isLast() {
h.entries[h.index].original = s
} else if s == h.entries[h.index].original {
h.entries[h.index].isEdited = false
} else {
h.entries[h.index].edited = s
h.entries[h.index].isEdited = true
}
}
func (h *history) revert() {
if h.isNew() || !h.entries[h.index].isEdited {
return
}
h.entries[h.index].edited = ""
h.entries[h.index].isEdited = false
}
func (h *history) revertAndAdd() {
if h.isLast() || !h.entries[h.index].isEdited {
return
}
h.entries[len(h.entries)-1] = &line{original: h.entries[h.index].edited}
h.revert()
}