-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
620 lines (558 loc) · 14.6 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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path"
"slices"
"strings"
"sync"
"time"
"github.com/adrg/xdg"
"github.com/gdamore/tcell/v2"
"github.com/lithammer/fuzzysearch/fuzzy"
"github.com/rivo/tview"
"gopkg.in/yaml.v3"
)
const (
maxLogLines = 10000
BOX_LIST = "list"
BOX_STDOUT = "stdout"
BOX_STDERR = "stderr"
)
var (
commands *[]Command
list *tview.List
layout *tview.Flex
info *tview.TextView
errors *tview.TextView
exitCode *tview.TextView
bottomLeftText *tview.TextView
bottomLeftSearch *tview.InputField
globalProcessesRunning int
app *tview.Application
runIndex sync.Map
isSearching bool
searchTerm string
config Config
currentlyFocusedBox string
filteredResults []string
)
type Config struct {
Commands []ConfigCommand `yaml:"commands"`
IdleRefreshRateMs int `yaml:"idleRefreshRateMs"`
ProcessRunningRefreshRateMs int `yaml:"processRunningRefreshRateMs"`
}
func loadConfig() (c Config, err error) {
xdgConfig := path.Join(xdg.ConfigHome, "frequencmd", "config.yml")
xdgHome := path.Join(xdg.Home, "frequencmd", "config.yml")
curConf := "config.yml"
b, err := os.ReadFile(curConf)
if err == nil {
err = yaml.Unmarshal(b, &c)
if err != nil {
return c, fmt.Errorf(
"failed to read config from %v: %v",
curConf,
err.Error(),
)
}
return c, nil
}
b, err = os.ReadFile(xdgConfig)
if err == nil {
err = yaml.Unmarshal(b, &c)
if err != nil {
return c, fmt.Errorf(
"failed to read config from %v: %v",
xdgConfig,
err.Error(),
)
}
return c, nil
}
b, err = os.ReadFile(xdgHome)
if err == nil {
err = yaml.Unmarshal(b, &c)
if err != nil {
return c, fmt.Errorf(
"failed to read config from %v: %v",
xdgHome,
err.Error(),
)
}
return c, nil
}
return c, fmt.Errorf(
"failed to read config from %v, %v, and %v: %v",
curConf,
xdgConfig,
xdgHome,
err.Error(),
)
}
func parseConfigCommands(conf Config) {
commands = &[]Command{}
for i := range conf.Commands {
c := conf.Commands[i]
n := Command{
Command: c.Command,
Env: c.Env,
Label: c.Label,
ShellBashArgs: c.ShellBashArgs,
LaunchSeparately: c.LaunchSeparately,
}
if c.Shell != "" {
if c.ShellBashArgs != "" {
n.Args = []string{}
n.Args = append(n.Args, strings.Split(c.ShellBashArgs, " ")...)
n.Args = append(n.Args, "-c", c.Shell)
} else {
n.Args = []string{"-c", c.Shell}
}
} else {
n.Args = strings.Split(c.Args, " ")
}
*commands = append(*commands, n)
}
}
func getNowStr() string {
return time.Now().Format("15:04:05")
}
func setLastCommandText(cmd *Command) {
exitCode.SetTitle(fmt.Sprintf("exit code for: %v", cmd.Label))
}
func setBottomLeftText(t string) {
bottomLeftText.SetText(fmt.Sprintf("[white][ctrl+c][gray] to quit | %v", t))
}
func pidRunningDrawLoop() {
for {
// setStatusText(fmt.Sprintf("%v loops", loops))
sleepTime := time.Duration(config.IdleRefreshRateMs) * time.Millisecond
processesRunning := 0
keysToDelete := []int64{}
shouldRedrawApp := false
runIndex.Range(func(key, value any) bool {
if value == true {
if app != nil {
shouldRedrawApp = true
}
processesRunning += 1
errors.ScrollToEnd()
info.ScrollToEnd()
} else {
keysToDelete = append(keysToDelete, key.(int64))
}
return true
})
// last process finished running; do a one-time update on the status bar
if processesRunning == 0 && globalProcessesRunning > 0 {
globalProcessesRunning = 0
setBottomLeftText(fmt.Sprintf("%v running", globalProcessesRunning))
app.QueueUpdateDraw(func() {})
}
// sync up with the global counter
globalProcessesRunning = processesRunning
if globalProcessesRunning > 0 {
setBottomLeftText(fmt.Sprintf("%v running", globalProcessesRunning))
app.QueueUpdateDraw(func() {})
}
if shouldRedrawApp {
// draw a little faster if we know something is running
sleepTime = time.Duration(config.ProcessRunningRefreshRateMs) * time.Millisecond
setBottomLeftText(fmt.Sprintf("%v running", globalProcessesRunning))
app.QueueUpdateDraw(func() {})
}
for key := range keysToDelete {
keyToDelete := key
runIndex.Delete(keyToDelete)
}
time.Sleep(sleepTime)
}
}
func runCommand(command *Command /* command string, args []string, env []string */) {
jobId := time.Now().UnixNano()
runIndex.Store(jobId, true)
setLastCommandText(command)
exitCode.SetText(fmt.Sprintf("[gray]%v [aqua] running command:[white] %v", getNowStr(), command.Label))
info.Clear()
errors.Clear()
cmd := exec.Command(command.Command, command.Args...)
cmd.Env = append(cmd.Env, command.Env...)
info.SetText(fmt.Sprintf("Running:\n%v %v %v\n\n", strings.Join(command.Env, " "), command.Command, strings.Join(command.Args, " ")))
cmd.Stdout = info
cmd.Stderr = errors
// Run the command
var err error
if command.LaunchSeparately {
err = cmd.Start()
} else {
err = cmd.Run()
}
if err != nil {
runIndex.Store(jobId, false)
errors.SetText(fmt.Sprintf("error running command: %v", err.Error()))
exitCode.SetText(fmt.Sprintf("[red] Exit code: %v", cmd.ProcessState.ExitCode()))
app.QueueUpdateDraw(func() {})
return
}
runIndex.Store(jobId, false)
exitCode.SetText(fmt.Sprintf("[green] Exit code: %v", cmd.ProcessState.ExitCode()))
app.QueueUpdateDraw(func() {})
}
func FuzzyFind(input string, commands []Command) []string {
commandList := []string{}
for _, c := range commands {
commandList = append(commandList, c.Label)
}
return fuzzy.Find(input, commandList)
}
type Command struct {
Color tcell.Color
Label string
Command string
Args []string
Env []string
// Arguments to always pass to the /bin/bash executable when using a shell.
// For example, normally commands are executed via /bin/bash -c "shell"
// but you may want to specify a login shell via /bin/bash -i -c "shell",
// in which case ShellBashArgs would be "-i".
ShellBashArgs string
// Instead of following the output, the program gets launched and
// frequencmd doesn't care about it. Useful for graphical apps.
LaunchSeparately bool
}
type ConfigCommand struct {
Label string `yaml:"label"`
Command string `yaml:"command"`
Shell string `yaml:"shell"`
Args string `yaml:"args"`
Env []string `yaml:"env"`
ShellBashArgs string `yaml:"shellBashArgs"`
LaunchSeparately bool `yaml:"launchSeparately"`
}
func getFilteredList(l *tview.List, commands []Command, filterString string) {
if l != nil {
l.Clear()
}
filteredCommands := FuzzyFind(filterString, commands)
filteredResults = []string{}
for i := range commands {
c := &(commands[i])
matchedMarker := ""
if !slices.Contains(filteredCommands, c.Label) {
continue
}
l.AddItem(fmt.Sprintf("%v%v", (*c).Label, matchedMarker), "", 0, func() { go runCommand(c) }).ShowSecondaryText(false) // .SetMainTextColor(c.Color)
filteredResults = append(filteredResults, (*c).Label)
}
l.SetBorder(true)
}
func getLayout(commands []Command) {
getFilteredList(list, commands, searchTerm)
info = tview.NewTextView().SetTextAlign(tview.AlignLeft).SetText("").SetDynamicColors(true)
errors = tview.NewTextView().SetTextAlign(tview.AlignLeft).SetText("").SetDynamicColors(true)
exitCode = tview.NewTextView().SetTextAlign(tview.AlignLeft).SetText("").SetDynamicColors(true)
bottomLeftText = tview.NewTextView().SetTextAlign(tview.AlignLeft).SetDynamicColors(true)
bottomLeftSearch = tview.NewInputField()
setBottomLeftText("0 processes running")
info.SetBorder(true).SetTitle("stdout")
errors.SetBorder(true).SetTitle("stderr")
exitCode.SetBorder(true).SetTitle("exit code")
bottomLeftText.SetBorder(true)
bottomLeftSearch.SetBorder(true)
bottomLeftSearch.SetDisabled(true)
logViews := tview.NewFlex().SetDirection(tview.FlexRow).
AddItem(info, 0, 5, false).
AddItem(errors, 0, 5, false)
// AddItem(exitCode, 0, 1, false)
mainColumns := tview.NewFlex().
SetDirection(tview.FlexColumn).
AddItem(list, 0, 1, true).
AddItem(logViews, 0, 2, false)
bottomRow := tview.NewFlex().SetDirection(tview.FlexColumn)
bottomLeftFlex := tview.NewFlex().SetDirection(tview.FlexColumn).
AddItem(bottomLeftText, 0, 1, false).
AddItem(bottomLeftSearch, 0, 1, false)
bottomRow.AddItem(bottomLeftFlex, 0, 2, false).
AddItem(exitCode, 0, 1, false)
layout = tview.NewFlex().
SetDirection(tview.FlexRow).
AddItem(mainColumns, 0, 1, false).
AddItem(bottomRow, 3, 0, false)
}
func endSearch(msg string) {
isSearching = false
searchTerm = ""
bottomLeftSearch.SetDisabled(true)
app.SetFocus(list)
setBottomLeftText(msg)
}
func main() {
runIndex = sync.Map{}
var err error
config, err = loadConfig()
if err != nil {
log.Fatalf("failed to load config: %v", err.Error())
}
parseConfigCommands(config)
app = tview.NewApplication()
go pidRunningDrawLoop()
list = tview.NewList()
getLayout(*commands)
currentlyFocusedBox = BOX_LIST
app.SetFocus(list)
app.SetInputCapture(func(e *tcell.EventKey) *tcell.EventKey {
if e.Rune() == '/' {
if !isSearching {
isSearching = true
searchTerm = ""
// app.SetFocus(bottomLeftSearch)
// getLayout(commands)
setBottomLeftText("[aqua]searching:")
bottomLeftSearch.SetText("")
bottomLeftSearch.SetDisabled(false)
// searchTerm = fmt.Sprintf("%v%v", searchTerm, string(e.Rune()))
app.SetFocus(bottomLeftSearch)
bottomLeftSearch.SetChangedFunc(func(text string) {
if list != nil {
list.Clear()
}
searchTerm = text
getFilteredList(list, *commands, searchTerm)
})
return nil
}
} else if e.Key() == tcell.KeyEnter {
if isSearching {
if len(filteredResults) == 0 {
getFilteredList(list, *commands, "")
}
endSearch(fmt.Sprintf("searched: %v", searchTerm))
return nil
}
} else if e.Key() == tcell.KeyEscape {
if isSearching {
endSearch(fmt.Sprintf("canceled search: %v", searchTerm))
return nil
} else {
app.Stop()
}
} else if e.Key() == tcell.KeyLeft {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_STDERR:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_LIST:
fallthrough
default:
app.SetFocus(info)
currentlyFocusedBox = BOX_STDOUT
}
return nil
} else if e.Key() == tcell.KeyRight {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_STDERR:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_LIST:
fallthrough
default:
app.SetFocus(info)
currentlyFocusedBox = BOX_STDOUT
}
return nil
} else if e.Key() == tcell.KeyTab {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(errors)
currentlyFocusedBox = BOX_STDERR
case BOX_STDERR:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_LIST:
fallthrough
default:
app.SetFocus(info)
currentlyFocusedBox = BOX_STDOUT
}
return nil
} else if e.Key() == tcell.KeyBacktab {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(list)
currentlyFocusedBox = BOX_LIST
case BOX_STDERR:
app.SetFocus(info)
currentlyFocusedBox = BOX_STDOUT
case BOX_LIST:
fallthrough
default:
app.SetFocus(errors)
currentlyFocusedBox = BOX_STDERR
}
return nil
} else if e.Key() == tcell.KeyPgUp {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(info)
r, c := info.GetScrollOffset()
_, _, _, h := info.GetRect()
newRow := r - h + 2 // the borders add some extra distance
if newRow < 0 {
newRow = 0
}
info.ScrollTo(newRow, c)
return nil
case BOX_STDERR:
app.SetFocus(errors)
r, c := errors.GetScrollOffset()
_, _, _, h := errors.GetRect()
newRow := r - h + 2 // the borders add some extra distance
if newRow < 0 {
newRow = 0
}
errors.ScrollTo(newRow, c)
return nil
case BOX_LIST:
fallthrough
default:
app.SetFocus(list)
return e
}
} else if e.Key() == tcell.KeyPgDn {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(info)
r, c := info.GetScrollOffset()
_, _, _, h := info.GetRect()
newRow := r + h - 2 // the borders add some extra distance
info.ScrollTo(newRow, c)
return nil
case BOX_STDERR:
app.SetFocus(errors)
r, c := info.GetScrollOffset()
_, _, _, h := errors.GetRect()
newRow := r + h - 2 // the borders add some extra distance
errors.ScrollTo(newRow, c)
return nil
case BOX_LIST:
fallthrough
default:
app.SetFocus(list)
return e
}
} else if e.Key() == tcell.KeyUp {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(info)
r, c := info.GetScrollOffset()
newRow := r - 1
info.ScrollTo(newRow, c)
return nil
case BOX_STDERR:
app.SetFocus(errors)
r, c := errors.GetScrollOffset()
newRow := r - 1
errors.ScrollTo(newRow, c)
return nil
case BOX_LIST:
fallthrough
default:
app.SetFocus(list)
return e
}
} else if e.Key() == tcell.KeyDown {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
app.SetFocus(info)
r, c := info.GetScrollOffset()
newRow := r + 1
info.ScrollTo(newRow, c)
return nil
case BOX_STDERR:
app.SetFocus(errors)
r, c := info.GetScrollOffset()
newRow := r + 1
errors.ScrollTo(newRow, c)
return nil
case BOX_LIST:
fallthrough
default:
app.SetFocus(list)
return e
}
} else if e.Key() == tcell.KeyHome {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
info.ScrollToBeginning()
return nil
case BOX_STDERR:
errors.ScrollToBeginning()
return nil
case BOX_LIST:
fallthrough
default:
return e
}
} else if e.Key() == tcell.KeyEnd {
if isSearching {
return e
}
switch currentlyFocusedBox {
case BOX_STDOUT:
info.ScrollToEnd()
return nil
case BOX_STDERR:
errors.ScrollToEnd()
return nil
case BOX_LIST:
fallthrough
default:
return e
}
} else {
if !isSearching {
app.SetFocus(list)
}
}
return e
})
if err := app.SetRoot(layout, true).EnableMouse(false).Run(); err != nil {
panic(err)
}
}