From d9a5389cfcfec963a25daaac3d68115c6c83520a Mon Sep 17 00:00:00 2001 From: franklin Date: Fri, 23 Apr 2021 09:29:39 +0200 Subject: [PATCH] feat(history): add ignore duplicates option --- history.go | 19 +++++++++++++++---- history_test.go | 31 +++++++++++++++++++++++++------ option.go | 9 +++++++++ 3 files changed, 49 insertions(+), 10 deletions(-) diff --git a/history.go b/history.go index e75c645..68c0e62 100644 --- a/history.go +++ b/history.go @@ -2,14 +2,25 @@ package prompt // History stores the texts that are entered. type History struct { - histories []string - tmp []string - selected int + histories []string + tmp []string + selected int + ignoreDuplicates bool } // Add to add text in history. 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() } diff --git a/history_test.go b/history_test.go index bf63869..ac07611 100644 --- a/history_test.go +++ b/history_test.go @@ -10,9 +10,10 @@ func TestHistoryClear(t *testing.T) { h.Add("foo") h.Clear() expected := &History{ - histories: []string{"foo"}, - tmp: []string{"foo", ""}, - selected: 1, + 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) @@ -23,9 +24,27 @@ func TestHistoryAdd(t *testing.T) { h := NewHistory() h.Add("echo 1") expected := &History{ - histories: []string{"echo 1"}, - tmp: []string{"echo 1", ""}, - selected: 1, + 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) diff --git a/option.go b/option.go index 9fbd680..a2df8f6 100644 --- a/option.go +++ b/option.go @@ -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 {