feat(history): add ignore duplicates option

This commit is contained in:
franklin 2021-04-23 09:29:39 +02:00
parent 82a9122745
commit d9a5389cfc
3 changed files with 49 additions and 10 deletions

@ -2,14 +2,25 @@ package prompt
// History stores the texts that are entered. // History stores the texts that are entered.
type History struct { type History struct {
histories []string histories []string
tmp []string tmp []string
selected int selected int
ignoreDuplicates bool
} }
// Add to add text in history. // Add to add text in history.
func (h *History) Add(input string) { func (h *History) Add(input string) {
h.histories = append(h.histories, input) if h.ignoreDuplicates {
var histories []string
for _, history := range h.histories {
if history != input {
histories = append(histories, history)
}
}
h.histories = append(histories, input)
} else {
h.histories = append(h.histories, input)
}
h.Clear() h.Clear()
} }

@ -10,9 +10,10 @@ func TestHistoryClear(t *testing.T) {
h.Add("foo") h.Add("foo")
h.Clear() h.Clear()
expected := &History{ expected := &History{
histories: []string{"foo"}, histories: []string{"foo"},
tmp: []string{"foo", ""}, tmp: []string{"foo", ""},
selected: 1, selected: 1,
ignoreDuplicates: false,
} }
if !reflect.DeepEqual(expected, h) { if !reflect.DeepEqual(expected, h) {
t.Errorf("Should be %#v, but got %#v", expected, h) t.Errorf("Should be %#v, but got %#v", expected, h)
@ -23,9 +24,27 @@ func TestHistoryAdd(t *testing.T) {
h := NewHistory() h := NewHistory()
h.Add("echo 1") h.Add("echo 1")
expected := &History{ expected := &History{
histories: []string{"echo 1"}, histories: []string{"echo 1"},
tmp: []string{"echo 1", ""}, tmp: []string{"echo 1", ""},
selected: 1, selected: 1,
ignoreDuplicates: false,
}
if !reflect.DeepEqual(h, expected) {
t.Errorf("Should be %v, but got %v", expected, h)
}
}
func TestHistoryAddIgnoreDuplicates(t *testing.T) {
h := NewHistory()
h.ignoreDuplicates = true
h.Add("echo 1")
h.Add("echo 2")
h.Add("echo 1")
expected := &History{
histories: []string{"echo 2", "echo 1"},
tmp: []string{"echo 2", "echo 1", ""},
selected: 2,
ignoreDuplicates: true,
} }
if !reflect.DeepEqual(h, expected) { if !reflect.DeepEqual(h, expected) {
t.Errorf("Should be %v, but got %v", expected, h) t.Errorf("Should be %v, but got %v", expected, h)

@ -206,6 +206,15 @@ func OptionHistory(x []string) Option {
} }
} }
// OptionHistoryIgnoreDuplicates to set history not display a line previously found
func OptionHistoryIgnoreDuplicates(x bool) Option {
return func(p *Prompt) error {
p.history.ignoreDuplicates = x
p.history.Clear()
return nil
}
}
// OptionSwitchKeyBindMode set a key bind mode. // OptionSwitchKeyBindMode set a key bind mode.
func OptionSwitchKeyBindMode(m KeyBindMode) Option { func OptionSwitchKeyBindMode(m KeyBindMode) Option {
return func(p *Prompt) error { return func(p *Prompt) error {