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

@ -5,11 +5,22 @@ type History struct {
histories []string
tmp []string
selected int
ignoreDuplicates bool
}
// Add to add text in history.
func (h *History) Add(input string) {
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()
}

@ -13,6 +13,7 @@ func TestHistoryClear(t *testing.T) {
histories: []string{"foo"},
tmp: []string{"foo", ""},
selected: 1,
ignoreDuplicates: false,
}
if !reflect.DeepEqual(expected, h) {
t.Errorf("Should be %#v, but got %#v", expected, h)
@ -26,6 +27,24 @@ func TestHistoryAdd(t *testing.T) {
histories: []string{"echo 1"},
tmp: []string{"echo 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) {
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.
func OptionSwitchKeyBindMode(m KeyBindMode) Option {
return func(p *Prompt) error {