-
Notifications
You must be signed in to change notification settings - Fork 1
/
history.go
99 lines (86 loc) · 2.19 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
package ns
import "strings"
type History struct {
commands []string
commandIndex int
maxKeep int
}
// NewHistory creates a new history object with optional pre-loaded history
func NewHistory(maxKeep int, commands ...string) *History {
newCommands := []string{}
newCommands = append(newCommands, commands...)
if len(newCommands) > maxKeep {
newCommands = newCommands[len(newCommands)-maxKeep:]
}
return &History{
commands: newCommands,
commandIndex: -1,
maxKeep: maxKeep,
}
}
// Older returns the next oldest command in the history
func (h *History) Older() string {
if len(h.commands) == 0 {
return ""
}
if h.commandIndex == -1 {
h.commandIndex = len(h.commands) - 1
} else {
h.commandIndex--
if h.commandIndex < 0 {
h.commandIndex = 0
}
}
return h.commands[h.commandIndex]
}
// Newer returns the next newest command in the history
func (h *History) Newer() string {
if len(h.commands) == 0 {
return ""
}
if h.commandIndex == -1 {
h.commandIndex = len(h.commands) - 1
} else {
h.commandIndex++
if h.commandIndex >= len(h.commands) {
h.commandIndex = len(h.commands) - 1
return ""
}
}
return h.commands[h.commandIndex]
}
// Any returns true if there are any commands in the history
func (h *History) Any() bool {
return len(h.commands) > 0
}
// Append appends another command to the history
func (h *History) Append(command string) {
h.commandIndex = -1
if len(h.commands) > 0 {
// Don't append consecutive duplicates (this isn't an audit history, its a convenience history)
if h.commands[len(h.commands)-1] == command {
return
}
}
h.commands = append(h.commands, command)
if len(h.commands) > h.maxKeep {
h.commands = h.commands[len(h.commands)-h.maxKeep:]
}
}
// Export returns the command history
func (h *History) Export() []string {
return h.commands
}
// FindMostRecentMatch returns the most recent command that contains subString, or an empty string
func (h *History) FindMostRecentMatch(subString string) string {
if subString == "" {
return ""
}
for i := len(h.commands) - 1; i >= 0; i-- {
cmd := h.commands[i]
if strings.Contains(strings.ToLower(cmd), strings.ToLower(subString)) {
return cmd
}
}
return ""
}