xonecas.io
5119
Lh

lazy-history / commit 8d86823

feat: search and sort, new module structure

Sean2025-05-11 8d868236509389f32169d549f985761d25c2ef7b parent b8f9409

11 files changed

.gitignore+0−1
@@ -1,2 +1 @@
1-debug.log
21 *.log
README.md+1−7
@@ -1,11 +1,5 @@
11 # lazy history
22
3-Search your history with style
3+Search your history with style.
44
55 Currently still in early development.
6-
7-run locally with:
8-
9-```
10-export DEBUG=true && go run . which
11-```
cmd/main.go+1−0
@@ -0,0 +1 @@
1+package main
go.mod+2−1
@@ -28,8 +28,9 @@ require (
2828 github.com/rivo/uniseg v0.4.7 // indirect
2929 github.com/rogpeppe/go-internal v1.9.0 // indirect
3030 github.com/sahilm/fuzzy v0.1.1 // indirect
31+ github.com/samber/lo v1.50.0 // indirect
3132 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
3233 golang.org/x/sync v0.13.0 // indirect
3334 golang.org/x/sys v0.32.0 // indirect
34- golang.org/x/text v0.3.8 // indirect
35+ golang.org/x/text v0.22.0 // indirect
3536 )
go.sum+4−0
@@ -51,6 +51,8 @@ github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZV
5151 github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
5252 github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
5353 github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
54+github.com/samber/lo v1.50.0 h1:XrG0xOeHs+4FQ8gJR97zDz5uOFMW7OwFWiFVzqopKgY=
55+github.com/samber/lo v1.50.0/go.mod h1:RjZyNk6WSnUFRKK6EyOhsRJMqft3G+pg7dCWHQCWvsc=
5456 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
5557 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
5658 golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
@@ -63,3 +65,5 @@ golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
6365 golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
6466 golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
6567 golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
68+golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
69+golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
internal/search.go+54−0
@@ -0,0 +1,54 @@
1+package search
2+
3+import (
4+ "sort"
5+
6+ "github.com/samber/lo"
7+)
8+
9+type SearchResult struct {
10+ Value string
11+ Distance int
12+}
13+
14+// Search a slice of strings for a substring and sort by levenshtein distance.
15+func Search(slice []string, substring string) []SearchResult {
16+ results := lo.Reduce(slice, func(agg []SearchResult, item string, index int) []SearchResult {
17+ distance := levenshteinDistance(item, substring)
18+ contains := lo.ContainsBy(agg, func(result SearchResult) bool {
19+ return result.Value == item
20+ })
21+ if distance <= 3 && !contains {
22+ agg = append(agg, SearchResult{Value: item, Distance: distance})
23+ }
24+ return agg
25+ }, []SearchResult{})
26+
27+ sort.Slice(results, func(i, j int) bool {
28+ return results[i].Distance < results[j].Distance
29+ })
30+
31+ return results
32+}
33+
34+func levenshteinDistance(s, t string) int {
35+ lenS := len(s)
36+ lenT := len(t)
37+
38+ if lenS == 0 {
39+ return lenT
40+ }
41+ if lenT == 0 {
42+ return lenS
43+ }
44+
45+ if s[lenS-1] == t[lenT-1] {
46+ return levenshteinDistance(s[:lenS-1], t[:lenT-1])
47+ }
48+
49+ return 1 + min(
50+ levenshteinDistance(s[:lenS-1], t),
51+ levenshteinDistance(s, t[:lenT-1]),
52+ levenshteinDistance(s[:lenS-1], t[:lenT-1]),
53+ )
54+}
internal/search_test.go+55−0
@@ -0,0 +1,55 @@
1+package search
2+
3+import (
4+ "reflect"
5+ "testing"
6+)
7+
8+// Test the search function.
9+func TestSearch(t *testing.T) {
10+ tests := []struct {
11+ slice []string
12+ substring string
13+ want []SearchResult
14+ }{
15+ {
16+ slice: []string{"apple", "banana", "cherry", "date"},
17+ substring: "ban",
18+ want: []SearchResult{{"banana", 3}, {"date", 3}},
19+ },
20+ {
21+ slice: []string{"apple", "banana", "cherry", "date"},
22+ substring: "banana",
23+ want: []SearchResult{{"banana", 0}},
24+ },
25+ }
26+
27+ for _, test := range tests {
28+ if got := Search(test.slice, test.substring); !reflect.DeepEqual(got, test.want) {
29+ t.Errorf("Search(%v, %q) = %v; want %v", test.slice, test.substring, got, test.want)
30+ }
31+ }
32+}
33+
34+// Test the levenshtein distance function.
35+func TestLevenshteinDistance(t *testing.T) {
36+ tests := []struct {
37+ s, t string
38+ want int
39+ }{
40+ {"ban", "apple", 5},
41+ {"ban", "banana", 3},
42+ {"ban", "cherry", 6},
43+ {"ban", "date", 3},
44+ {"banana", "banana", 0},
45+ {"banana", "apple", 5},
46+ {"banana", "cherry", 6},
47+ {"banana", "date", 5},
48+ }
49+
50+ for _, test := range tests {
51+ if got := levenshteinDistance(test.s, test.t); got != test.want {
52+ t.Errorf("levenshteinDistance(%q, %q) = %d; want %d", test.s, test.t, got, test.want)
53+ }
54+ }
55+}
lazy-history.go+0−69
@@ -1,69 +0,0 @@
1-package main
2-
3-import (
4- "bufio"
5- "os"
6- "path/filepath"
7-
8- tea "github.com/charmbracelet/bubbletea"
9- lib "github.com/sacenox/lazy-history/lib"
10-)
11-
12-func main() {
13-
14- if lib.IsDebug {
15- f, err := tea.LogToFile("debug.log", "debug")
16- if err != nil {
17- lib.Fatalf("Failed to log to file: %v", err)
18- }
19- defer f.Close()
20- }
21-
22- query := os.Args[1] // args without program name
23-
24- lib.Debugf("Query: %s", query)
25-
26- history := []string{} // one cmd per entry
27-
28- historyFilePaths := []string{
29- filepath.Join(os.Getenv("HOME"), ".history"),
30- filepath.Join(os.Getenv("HOME"), ".zsh_history"),
31- filepath.Join(os.Getenv("HOME"), ".bash_history"),
32- }
33-
34- for _, historyFilePath := range historyFilePaths {
35- if _, err := os.Stat(historyFilePath); os.IsNotExist(err) {
36- lib.Debugf("History file %s does not exist", historyFilePath)
37- continue
38- }
39-
40- historyFile, err := os.Open(historyFilePath)
41- if err != nil {
42- lib.Fatalf("Failed to open history file: %v", err)
43- }
44-
45- scanner := bufio.NewScanner(historyFile)
46- // Read each line from the history file
47- for scanner.Scan() {
48- line := scanner.Text()
49- history = append(history, line)
50- }
51-
52- lib.Debugf("Read %d lines from history file %s", len(history), historyFilePath)
53-
54- // Check for scanner errors
55- if err := scanner.Err(); err != nil {
56- lib.Debugf("Error reading history file %s: %v", historyFilePath, err)
57- }
58-
59- historyFile.Close()
60- }
61-
62- results := lib.Search(history, query)
63- p := tea.NewProgram(lib.NewHistory(results), tea.WithAltScreen())
64-
65- _, err := p.Run()
66- if err != nil {
67- lib.Fatalf("Failed to run program: %v", err)
68- }
69-}
lib/log-util.go+0−30
@@ -1,30 +0,0 @@
1-package lib
2-
3-import (
4- "log"
5- "os"
6-
7- "github.com/kr/pretty"
8-)
9-
10-var IsDebug = os.Getenv("DEBUG") != ""
11-
12-func Debug(v ...interface{}) {
13- if IsDebug {
14- PrettyPrint(v)
15- }
16-}
17-
18-func Debugf(format string, v ...interface{}) {
19- if IsDebug {
20- log.Printf(format, v...)
21- }
22-}
23-
24-func Fatalf(format string, v ...interface{}) {
25- log.Fatalf(format, v...)
26-}
27-
28-func PrettyPrint(v interface{}) {
29- log.Printf("%# v\n", pretty.Formatter(v))
30-}
lib/models.go+0−104
@@ -1,104 +0,0 @@
1-package lib
2-
3-import (
4- "bytes"
5- "os/exec"
6- "strings"
7-
8- "github.com/charmbracelet/bubbles/list"
9- tea "github.com/charmbracelet/bubbletea"
10-)
11-
12-type ListItem struct {
13- title string
14-}
15-
16-func (l ListItem) Title() string {
17- return l.title
18-}
19-
20-func (l ListItem) Description() string {
21- return ""
22-}
23-
24-func (l ListItem) FilterValue() string {
25- return l.title
26-}
27-
28-type History struct {
29- Entries []string
30- Selected int
31- Output *bytes.Buffer
32- List list.Model
33-}
34-
35-type ExecuteEntryMsg struct {
36- Error error
37-}
38-
39-func NewHistory(entries []string) *History {
40- items := make([]list.Item, len(entries))
41- for i, entry := range entries {
42- items[i] = ListItem{title: entry}
43- }
44- return &History{
45- Selected: 0,
46- Output: &bytes.Buffer{},
47- List: list.New(items, list.NewDefaultDelegate(), 0, 0),
48- }
49-}
50-
51-func (h *History) Init() tea.Cmd {
52- return nil
53-}
54-
55-func (h *History) ExecuteEntry(entry string) tea.Cmd {
56- parts := strings.Split(entry, " ")
57- cmd := exec.Command(parts[0], parts[1:]...)
58- cmd.Stdout = h.Output
59- return tea.ExecProcess(cmd, func(err error) tea.Msg {
60- return ExecuteEntryMsg{Error: err}
61- })
62-}
63-
64-func (h *History) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
65- switch msg := msg.(type) {
66-
67- case ExecuteEntryMsg:
68- if msg.Error != nil {
69- Debugf("error: %v", msg.Error)
70- return h, nil
71- }
72- return h, tea.Quit
73-
74- case tea.WindowSizeMsg:
75- h.List.SetSize(msg.Width, msg.Height)
76-
77- // Is it a key press?
78- case tea.KeyMsg:
79- switch msg.String() {
80- // These keys should exit the program.
81- case "ctrl+c", "q":
82- return h, tea.Quit
83- case "enter":
84- // return the selected entry, and run the command
85- selected := h.List.SelectedItem().(ListItem)
86- Debugf("executing: %s", selected.title)
87- return h, h.ExecuteEntry(selected.title)
88- }
89- }
90-
91- var cmd tea.Cmd
92- h.List, cmd = h.List.Update(msg)
93- return h, cmd
94-}
95-
96-func (h *History) View() string {
97- // render the history
98- output := h.Output.String()
99- if output != "" {
100- return output
101- }
102-
103- return h.List.View()
104-}
lib/search.go+0−45
@@ -1,45 +0,0 @@
1-package lib
2-
3-import (
4- "slices"
5- "sort"
6- "strings"
7-)
8-
9-func FindOne(history []string, query string) (string, int) {
10- // search using a binary search
11- i := sort.Search(len(history), func(i int) bool {
12- return history[i] >= query
13- })
14- if i < len(history) && strings.Contains(history[i], query) {
15- Debugf("found %q at index %d: %q", query, i, history[i])
16- return history[i], i
17- } else {
18- Debugf("%q not found\n", query)
19- return "", -1
20- }
21-}
22-
23-func Search(history []string, query string) []string {
24- results := []string{}
25-
26- // sort the array
27- slices.Sort(history)
28-
29- // deduplicate the history
30- // TODO: We should keep track of the number of dupes
31- history = slices.Compact(history)
32-
33- // Keep searching for matches until we don't find any more
34- for {
35- result, i := FindOne(history, query)
36- if result == "" {
37- break
38- }
39-
40- results = append(results, result)
41- history = slices.Delete(history, i, i+1)
42- }
43-
44- return results
45-}