xonecas.io
5119
Lh

lazy-history / commit bac787a

feat: implement bubbletea simple list

Sean2025-05-11 bac787a8c36e981b8b6e4694c2b356350e7befb6 parent 0f95f39

6 files changed

cmd/main.go+78−0
@@ -1 +1,79 @@
11 package main
2+
3+import (
4+ "bufio"
5+ "log"
6+ "os"
7+ "os/exec"
8+ "path/filepath"
9+
10+ tea "github.com/charmbracelet/bubbletea"
11+ internal_list "github.com/sacenox/lazy-history/internal/list"
12+ "github.com/sacenox/lazy-history/internal/search"
13+)
14+
15+func main() {
16+ if os.Getenv("DEBUG") == "true" {
17+ f, err := tea.LogToFile("debug.log", "debug")
18+ if err != nil {
19+ log.Fatalf("Failed to log to file: %v", err)
20+ }
21+ defer f.Close()
22+ }
23+
24+ // Get the output of `history`
25+ history := []string{} // one cmd per entry
26+
27+ historyFilePaths := []string{
28+ filepath.Join(os.Getenv("HOME"), ".history"),
29+ filepath.Join(os.Getenv("HOME"), ".zsh_history"),
30+ filepath.Join(os.Getenv("HOME"), ".bash_history"),
31+ }
32+
33+ // Run `history -a` to append the history to the files
34+ exec.Command("history", "-a").Run()
35+
36+ // Read the history files
37+ for _, historyFilePath := range historyFilePaths {
38+ if _, err := os.Stat(historyFilePath); os.IsNotExist(err) {
39+ continue
40+ }
41+
42+ historyFile, err := os.Open(historyFilePath)
43+ if err != nil {
44+ log.Fatalf("Failed to open history file: %v", err)
45+ }
46+
47+ scanner := bufio.NewScanner(historyFile)
48+ // Read each line from the history file
49+ for scanner.Scan() {
50+ line := scanner.Text()
51+ history = append(history, line)
52+ }
53+
54+ // Check for scanner errors
55+ if err := scanner.Err(); err != nil {
56+ log.Fatalf("Error reading history file %s: %v", historyFilePath, err)
57+ }
58+
59+ historyFile.Close()
60+ }
61+
62+ log.Printf("History: %v", history)
63+
64+ query := os.Args[1] // args without program name
65+
66+ log.Printf("Searching for %s", query)
67+
68+ // Search the history output for the query
69+ results := search.Search(history, query)
70+
71+ log.Printf("Found %d results", len(results))
72+ log.Printf("Results: %v", results)
73+
74+ ui := internal_list.New(results)
75+
76+ if _, err := tea.NewProgram(ui).Run(); err != nil {
77+ log.Fatal("Error running program: ", err)
78+ }
79+}
go.mod+1−4
@@ -5,7 +5,7 @@ go 1.24.0
55 require (
66 github.com/charmbracelet/bubbles v0.21.0
77 github.com/charmbracelet/bubbletea v1.3.5
8- github.com/kr/pretty v0.3.1
8+ github.com/samber/lo v1.50.0
99 )
1010
1111 require (
@@ -17,7 +17,6 @@ require (
1717 github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
1818 github.com/charmbracelet/x/term v0.2.1 // indirect
1919 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
20- github.com/kr/text v0.2.0 // indirect
2120 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
2221 github.com/mattn/go-isatty v0.0.20 // indirect
2322 github.com/mattn/go-localereader v0.0.1 // indirect
@@ -26,9 +25,7 @@ require (
2625 github.com/muesli/cancelreader v0.2.2 // indirect
2726 github.com/muesli/termenv v0.16.0 // indirect
2827 github.com/rivo/uniseg v0.4.7 // indirect
29- github.com/rogpeppe/go-internal v1.9.0 // indirect
3028 github.com/sahilm/fuzzy v0.1.1 // indirect
31- github.com/samber/lo v1.50.0 // indirect
3229 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
3330 golang.org/x/sync v0.13.0 // indirect
3431 golang.org/x/sys v0.32.0 // indirect
go.sum+8−10
@@ -20,13 +20,10 @@ github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payR
2020 github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
2121 github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
2222 github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
23-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
23+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
24+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2425 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
2526 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
26-github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
27-github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
28-github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
29-github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
3027 github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
3128 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
3229 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
@@ -43,16 +40,17 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
4340 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
4441 github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
4542 github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
46-github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
43+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
44+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
4745 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
4846 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
4947 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
50-github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
51-github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
5248 github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
5349 github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
5450 github.com/samber/lo v1.50.0 h1:XrG0xOeHs+4FQ8gJR97zDz5uOFMW7OwFWiFVzqopKgY=
5551 github.com/samber/lo v1.50.0/go.mod h1:RjZyNk6WSnUFRKK6EyOhsRJMqft3G+pg7dCWHQCWvsc=
52+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
53+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
5654 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
5755 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
5856 golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
@@ -63,7 +61,7 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc
6361 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
6462 golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
6563 golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
66-golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
67-golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
6864 golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
6965 golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
66+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
67+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
internal/list/list.go+90−4
@@ -1,14 +1,51 @@
1-package list
1+package internal_list
22
33 import (
4+ "fmt"
5+ "io"
6+
47 "github.com/charmbracelet/bubbles/list"
58 tea "github.com/charmbracelet/bubbletea"
6- "github.com/lazy-history/internal/search"
9+ "github.com/charmbracelet/lipgloss"
10+ "github.com/samber/lo"
711 )
812
13+type item string
14+
15+func (i item) FilterValue() string {
16+ return ""
17+}
18+
19+type itemDelegate struct{}
20+
21+func (d itemDelegate) Height() int {
22+ return 1
23+}
24+
25+func (d itemDelegate) Spacing() int {
26+ return 0
27+}
28+
29+func (d itemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd {
30+ return nil
31+}
32+
33+func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
34+ i, ok := listItem.(item)
35+ if !ok {
36+ return
37+ }
38+
39+ if index == m.Index() {
40+ fmt.Fprint(w, "→ ")
41+ }
42+
43+ fmt.Fprint(w, i)
44+}
45+
946 type model struct {
1047 list list.Model
11- choice search.SearchResult
48+ choice string
1249 }
1350
1451 func (m model) Init() tea.Cmd {
@@ -16,5 +53,54 @@ func (m model) Init() tea.Cmd {
1653 }
1754
1855 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
19- return m, nil
56+ switch msg := msg.(type) {
57+ case tea.WindowSizeMsg:
58+ m.list.SetWidth(msg.Width)
59+ return m, nil
60+
61+ case tea.KeyMsg:
62+ switch keypress := msg.String(); keypress {
63+ case "q", "ctrl+c":
64+ return m, tea.Quit
65+
66+ case "enter":
67+ i, ok := m.list.SelectedItem().(item)
68+ if ok {
69+ m.choice = string(i)
70+ }
71+ return m, tea.Quit
72+ }
73+ }
74+
75+ var cmd tea.Cmd
76+ m.list, cmd = m.list.Update(msg)
77+ return m, cmd
78+}
79+
80+func (m model) View() string {
81+ if m.choice != "" {
82+ return ""
83+ }
84+
85+ return "\n" + m.list.View()
86+}
87+
88+func New(lines []string) model {
89+ items := lo.Map(lines, func(line string, _ int) list.Item {
90+ return item(line)
91+ })
92+
93+ highlight := "13"
94+ height := 20
95+ width := 80
96+
97+ l := list.New(items, itemDelegate{}, width, height)
98+ l.Title = "— Lazy History —"
99+ l.Styles.Title = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(highlight))
100+ l.SetFilteringEnabled(false)
101+ l.SetShowStatusBar(false)
102+
103+ return model{
104+ list: l,
105+ }
20106 }
internal/search/search.go+26−4
@@ -11,16 +11,38 @@ type SearchResult struct {
1111 Distance int
1212 }
1313
14+func Search(slice []string, substring string) []string {
15+ results := search(slice, substring)
16+
17+ return lo.Map(results, func(result SearchResult, _ int) string {
18+ return result.Value
19+ })
20+}
21+
1422 // Search a slice of strings for a substring and sort by levenshtein distance.
15-func Search(slice []string, substring string) []SearchResult {
23+func search(slice []string, substring string) []SearchResult {
1624 results := lo.Reduce(slice, func(agg []SearchResult, item string, index int) []SearchResult {
17- distance := levenshteinDistance(item, substring)
25+ // Skip empty lines
26+ if len(item) <= 0 {
27+ return agg
28+ }
29+
30+ // Skip lines that already exist in the results
1831 contains := lo.ContainsBy(agg, func(result SearchResult) bool {
1932 return result.Value == item
2033 })
21- if distance <= 3 && !contains {
22- agg = append(agg, SearchResult{Value: item, Distance: distance})
34+ if contains {
35+ return agg
36+ }
37+
38+ // Skip lines with a levenshtein distance greater than 3
39+ distance := levenshteinDistance(item, substring)
40+ if distance > 4 {
41+ return agg
2342 }
43+
44+ agg = append(agg, SearchResult{Value: item, Distance: distance})
45+
2446 return agg
2547 }, []SearchResult{})
2648
internal/search/search_test.go+2−2
@@ -25,8 +25,8 @@ func TestSearch(t *testing.T) {
2525 }
2626
2727 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)
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)
3030 }
3131 }
3232 }