hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/internal/cli/cli.go
blob: 4e394e6e9303bac4ab670faea37cb0935890d29a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package cli

import (
	"fmt"
	"strings"

	"github.com/charmbracelet/bubbles/spinner"
	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"

	"github.com/hachem-wtf/benson/internal/config"
)

type command struct {
	name string
	desc string
	run  func(m *model) tea.Cmd
}

type outputMsg struct {
	text string
}

type model struct {
	cfg     *config.Config
	version string

	input textinput.Model
	spin  spinner.Model

	commands []command
	busy     bool
	quitting bool

	width int
}

func Run(version string) error {
	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("failed to load %s: %w", config.Path(), err)
	}

	_, err = tea.NewProgram(newModel(cfg, version)).Run()
	return err
}

func newModel(cfg *config.Config, version string) *model {
	ti := textinput.New()
	ti.Placeholder = "type a command… (try 'help')"
	ti.Prompt = ""
	ti.CharLimit = 128
	ti.Focus()

	sp := spinner.New()
	sp.Spinner = spinner.Dot
	sp.Style = lipgloss.NewStyle().Foreground(colPrimary)

	m := &model{
		cfg:     cfg,
		version: version,
		input:   ti,
		spin:    sp,
	}
	m.commands = defaultCommands()
	return m
}

func (m *model) Init() tea.Cmd {
	return tea.Batch(textinput.Blink, tea.Println(welcomeBlock(m.cfg, m.version)))
}

func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.input.Width = max(msg.Width-12, 20)
		return m, nil

	case tea.KeyMsg:
		switch msg.Type {
		case tea.KeyCtrlC, tea.KeyCtrlD:
			m.quitting = true
			return m, tea.Quit
		case tea.KeyTab:
			if s := m.firstSuggestion(); s != "" {
				m.input.SetValue(s)
				m.input.CursorEnd()
			}
			return m, nil
		case tea.KeyEnter:
			if m.busy {
				return m, nil
			}
			return m, m.submit()
		}

	case outputMsg:
		m.busy = false
		return m, tea.Println(msg.text)

	case spinner.TickMsg:
		var cmd tea.Cmd
		m.spin, cmd = m.spin.Update(msg)
		return m, cmd
	}

	var cmd tea.Cmd
	m.input, cmd = m.input.Update(msg)
	return m, cmd
}

func (m *model) View() string {
	if m.quitting {
		return ""
	}
	return "\n" + m.suggestionRow() + "\n" + m.promptLine() + "\n"
}

func (m *model) submit() tea.Cmd {
	raw := strings.TrimSpace(m.input.Value())
	m.input.Reset()
	if raw == "" {
		return nil
	}

	echo := tea.Println(promptStyle.Render("benson ❯ ") + raw)

	name := strings.ToLower(strings.Fields(raw)[0])
	if name == "?" {
		name = "help"
	}

	if isExit(name) {
		m.quitting = true
		return tea.Sequence(echo, tea.Println(mutedStyle.Render("Goodbye!")), tea.Quit)
	}

	if c := m.find(name); c != nil {
		return tea.Sequence(echo, c.run(m))
	}

	unknown := tea.Println(errorStyle.Render("Unknown command: "+name) + mutedStyle.Render("  ·  type 'help'"))
	return tea.Sequence(echo, unknown)
}

func (m *model) find(name string) *command {
	for i := range m.commands {
		if m.commands[i].name == name {
			return &m.commands[i]
		}
	}
	return nil
}

func isExit(name string) bool {
	switch name {
	case "exit", "quit", "q":
		return true
	}
	return false
}

func (m *model) promptLine() string {
	if m.busy {
		return "  " + m.spin.View() + " " + mutedStyle.Render("working…")
	}
	return promptStyle.Render("  benson ❯ ") + m.input.View()
}

func (m *model) suggestionRow() string {
	cur := strings.ToLower(strings.TrimSpace(m.input.Value()))

	chips := make([]string, 0, len(m.commands)+1)
	for _, c := range m.commands {
		if cur != "" && strings.HasPrefix(c.name, cur) {
			chips = append(chips, chipActiveStyle.Render(c.name))
		} else {
			chips = append(chips, chipStyle.Render(c.name))
		}
	}
	chips = append(chips, chipStyle.Render("exit"))

	return "  " + lipgloss.JoinHorizontal(lipgloss.Left, chips...)
}

func (m *model) firstSuggestion() string {
	cur := strings.ToLower(strings.TrimSpace(m.input.Value()))
	if cur == "" {
		return ""
	}
	for _, c := range m.commands {
		if c.name != cur && strings.HasPrefix(c.name, cur) {
			return c.name
		}
	}
	return ""
}