-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
449 lines (386 loc) · 10 KB
/
main.go
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"unsafe"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"golang.org/x/sys/unix"
)
var (
highlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000"))
normalStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFFFFF"))
headerStyle = lipgloss.NewStyle().
Background(lipgloss.Color("#6b0582")).
Foreground(lipgloss.Color("#FFFFFF")).
Bold(false).
PaddingLeft(1).
PaddingRight(1)
selectedStyle = lipgloss.NewStyle().Background(lipgloss.Color("#1C0023")).Foreground(lipgloss.Color("#CC00FF"))
)
const headerSize = 4
type Mode int
const (
ExactMatching Mode = iota
Keywords
Regex
)
func (m Mode) String() string {
switch m {
case ExactMatching:
return "exact"
case Keywords:
return "keywords"
case Regex:
return "regex"
default:
return "unknown"
}
}
type TextCase int
const (
Insensitive TextCase = iota
Sensitive
)
func (c TextCase) String() string {
switch c {
case Insensitive:
return "insensitive"
case Sensitive:
return "sensitive"
default:
return "unknown"
}
}
type model struct {
commands []string // All commands from history
filtered []string // Filtered commands based on query
query string // Current user input for filtering
selected int // Currently selected command index
viewStart int // Index in `filtered` where the view starts
viewEnd int // Index in `filtered` where the view ends
displaySize int // Number of commands to display at a time
textInput textinput.Model
width int
height int
injectSelection bool
runSelection bool
mode Mode
textCase TextCase
}
func getHistoryLocation() string {
historyLocation := os.Getenv("HISTORY_LOCATION")
if historyLocation == "" {
historyLocation = os.Getenv("HOME") + "/.bash_history"
}
return historyLocation
}
func initialModel(initialQuery string) model {
ti := textinput.New()
ti.Placeholder = "Filter..."
ti.Focus()
ti.Prompt = "$ "
ti.CharLimit = 10000
ti.SetValue(initialQuery)
// Assuming we want to display 10 commands at a time
displaySize := 20
history, _ := readHistory(getHistoryLocation())
m := model{
commands: history,
filtered: []string{},
selected: 0,
viewStart: 0,
viewEnd: displaySize,
displaySize: displaySize,
textInput: ti,
injectSelection: false,
runSelection: false,
}
m.query = initialQuery
m.filterCommands()
return m
}
func fillTerminalInput(cmd string, padding bool) {
if cmd == "" {
return
}
fd := int(os.Stdin.Fd())
for _, c := range cmd {
_, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(fd),
uintptr(unix.TIOCSTI),
uintptr(unsafe.Pointer(&c)),
)
if errno != 0 {
fmt.Fprintf(os.Stderr, "Failed to simulate terminal input: %v\n", errno)
return
}
}
if padding {
fmt.Println()
}
}
func removeDuplicates(elements []string) []string {
seen := make(map[string]bool)
var result []string
for _, element := range elements {
if _, found := seen[element]; !found {
seen[element] = true
result = append(result, element)
}
}
return result
}
func removeComments(elements []string) []string {
var result []string
for _, element := range elements {
if !strings.HasPrefix(element, "#") {
result = append(result, element)
}
}
return result
}
func readHistory(filePath string) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var commands []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
command := scanner.Text()
commands = append(commands, command)
}
for i, j := 0, len(commands)-1; i < j; i, j = i+1, j-1 {
commands[i], commands[j] = commands[j], commands[i]
}
results := removeComments(commands)
return removeDuplicates(results), scanner.Err()
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m *model) filterCommands() {
var query string
if m.textCase == Insensitive {
query = strings.ToLower(m.query)
} else {
query = m.query
}
var filtered []string
for _, cmd := range m.commands {
var cmdTextSearch string
if m.textCase == Insensitive {
cmdTextSearch = strings.ToLower(cmd) // Convert to lowercase for case-insensitive comparison.
} else {
cmdTextSearch = cmd
}
switch m.mode {
case ExactMatching:
if strings.HasPrefix(cmdTextSearch, query) {
filtered = append(filtered, cmd)
}
case Keywords:
matches := true
for _, word := range strings.Split(query, " ") {
if !strings.Contains(cmdTextSearch, word) {
matches = false
break
}
}
if matches {
filtered = append(filtered, cmd)
}
case Regex:
matched, err := regexp.MatchString(query, cmdTextSearch)
if err == nil && matched {
filtered = append(filtered, cmd)
}
default:
filtered = append(filtered, cmd)
}
}
m.filtered = filtered
// Reset view and selection
m.viewStart = 0
m.selected = 0
m.viewEnd = m.height - headerSize
if m.viewEnd > len(m.filtered) {
m.viewEnd = len(m.filtered)
}
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
m.textInput, cmd = m.textInput.Update(msg)
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC, tea.KeyEsc:
return m, tea.Quit
case tea.KeyUp:
if m.selected > 0 {
m.selected--
if m.selected < m.viewStart {
m.viewStart--
m.viewEnd--
}
}
case tea.KeyDown:
if m.selected < len(m.filtered)-1 {
m.selected++
if m.selected >= m.viewEnd {
m.viewStart++
m.viewEnd++
}
}
case tea.KeyTab:
m.injectSelection = true
return m, tea.Quit
case tea.KeyEnter:
m.injectSelection = true
m.runSelection = true
return m, tea.Quit
case tea.KeyCtrlE:
m.switchMode()
m.query = m.textInput.Value()
m.filterCommands()
//return m, nil
case tea.KeyCtrlT:
m.switchCase()
m.query = m.textInput.Value()
m.filterCommands()
//return m, nil
default:
m.query = m.textInput.Value()
m.filterCommands()
}
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.viewEnd = m.height - headerSize
}
return m, cmd
}
func (m *model) switchMode() {
m.mode = (m.mode + 1) % 3
}
func (m *model) switchCase() {
m.textCase = (m.textCase + 1) % 2
}
func fitStringToWidth(s string, width int) string {
if len(s) <= width || width < 10 {
return s
}
partLength := (width - 3) / 2 // Subtract 3 for the ellipsis and divide by 2 for two parts.
return s[:partLength] + "..." + s[len(s)-partLength:]
}
// highlightMatches applies styling to parts of the command that match the query
func (m *model) highlightMatches(cmd string) string {
var result string
cmdLower := strings.ToLower(cmd)
queryLower := strings.ToLower(m.query)
switch m.mode {
case ExactMatching:
// Check if the command starts with the query, excluding trailing spaces in the query
trimmedQuery := strings.TrimSpace(queryLower)
if strings.HasPrefix(cmdLower, trimmedQuery) {
// Apply highlight to the matching part, excluding trailing spaces in the command
matchEnd := len(trimmedQuery)
highlighted := lipgloss.JoinHorizontal(lipgloss.Top,
highlightStyle.Render(cmd[:matchEnd]),
normalStyle.Render(cmd[matchEnd:]),
)
result = highlighted
} else {
result = cmd
}
case Keywords:
// Split the query into words, ignoring extra spaces
words := strings.Fields(queryLower) // Fields uses spaces as separators and ignores extra spaces
highlightedCmd := cmd
for _, word := range words {
re := regexp.MustCompile("(?i)" + regexp.QuoteMeta(word))
highlightedCmd = re.ReplaceAllStringFunc(highlightedCmd, func(match string) string {
return highlightStyle.Render(match)
})
}
result = highlightedCmd
case Regex:
re, err := regexp.Compile("(?i)" + m.query)
if err == nil {
highlightedCmd := re.ReplaceAllStringFunc(cmd, func(match string) string {
return highlightStyle.Render(match)
})
result = highlightedCmd
} else {
result = cmd // If regex is invalid, display the command unmodified
}
default:
result = cmd // Default case to handle unstyled commands
}
// Ensures that styling is not applied to trailing spaces or if the query is only spaces
if strings.TrimSpace(m.query) == "" {
return normalStyle.Render(cmd)
}
return result
}
func (m model) View() string {
var b strings.Builder
b.WriteString(m.textInput.View())
b.WriteString("\nType to filter, UP/DOWN move, RET/TAB select\n")
headerText := fmt.Sprintf("- HISTORY - match:%s (C-e) - case:%s (C-t)", m.mode, m.textCase)
styledHeaderLength := lipgloss.Width(headerStyle.Render(headerText))
remainingWidth := m.width - styledHeaderLength
if remainingWidth > 0 {
// Generate the dashed line to fill the remaining width
dashLine := strings.Repeat("-", remainingWidth-1)
headerText += " " + dashLine
}
b.WriteString(headerStyle.Render(headerText))
b.WriteString("\n")
displayEnd := min(m.viewEnd, len(m.filtered))
for i := m.viewStart; i < displayEnd; i++ {
cmd := m.filtered[i]
isSelected := i == m.selected
cmdDisplay := fitStringToWidth(cmd, m.width-2)
if isSelected {
b.WriteString(selectedStyle.Width(m.width).Render(" "+cmdDisplay) + "\n")
} else {
highlightedCmd := m.highlightMatches(cmdDisplay)
b.WriteString(normalStyle.Render(" "+highlightedCmd) + "\n")
}
}
return b.String()
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func main() {
var initialQuery string
if len(os.Args) > 1 {
initialQuery = strings.Join(os.Args[2:], " ") // Assuming os.Args[1] is '--'
}
p := tea.NewProgram(initialModel(initialQuery), tea.WithAltScreen())
finalModel, err := p.Run()
if err != nil {
fmt.Printf("Alas, there's been an error: %v", err)
os.Exit(1)
}
// Assert the finalModel back to your specific model type to access its fields.
if m, ok := finalModel.(model); ok && m.injectSelection {
selection := m.filtered[m.selected]
if m.runSelection {
selection += "\n"
}
fillTerminalInput(selection, true)
}
}