@@ -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-}