main.go
This file
Path
examples/exec/main.go
71 lines · 1.3 KiB · Go
Last changed by
chore: rename StartReturningModel to RunChristian Muehlhaeuserbefore adoption6b77c8f
History of this fileTake it
add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 1–13why, one step back1package main23import (4 "fmt"5 "os"6 "os/exec"78 tea "github.com/charmbracelet/bubbletea"9)1011type editorFinishedMsg struct{ err error }1213func openEditor() tea.Cmd {docs: default to vim if no EDITOR on exec example (#325)Carlos Alexandro Beckerbefore adoptionb566614
lines 14–18why, one step back14 editor := os.Getenv("EDITOR")15 if editor == "" {16 editor = "vim"17 }18 c := exec.Command(editor) //nolint:gosecchore(exec): small API edits (#323)Christian Rochabefore adoption775dbfb
line 19why, one step back19 return tea.ExecProcess(c, func(err error) tea.Msg {add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 20–66why, one step back20 return editorFinishedMsg{err}21 })22}2324type model struct {25 altscreenActive bool26 err error27}2829func (m model) Init() tea.Cmd {30 return nil31}3233func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {34 switch msg := msg.(type) {35 case tea.KeyMsg:36 switch msg.String() {37 case "a":38 m.altscreenActive = !m.altscreenActive39 cmd := tea.EnterAltScreen40 if !m.altscreenActive {41 cmd = tea.ExitAltScreen42 }43 return m, cmd44 case "e":45 return m, openEditor()46 case "ctrl+c", "q":47 return m, tea.Quit48 }49 case editorFinishedMsg:50 if msg.err != nil {51 m.err = msg.err52 return m, tea.Quit53 }54 }55 return m, nil56}5758func (m model) View() string {59 if m.err != nil {60 return "Error: " + m.err.Error() + "\n"61 }62 return "Press 'e' to open your EDITOR.\nPress 'a' to toggle the altscreen\nPress 'q' to quit.\n"63}6465func main() {66 m := model{}chore: rename StartReturningModel to RunChristian Muehlhaeuserbefore adoption6b77c8f
line 67why, one step back67 if _, err := tea.NewProgram(m).Run(); err != nil {add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)Christian Muehlhaeuserbefore adoption3795c03
lines 68–71why, one step back68 fmt.Println("Error running program:", err)69 os.Exit(1)70 }71}