Files
bubbletea/examples/exec/main.go
Christian Muehlhaeuser 3795c036c4 add: Exec, ReleaseTerminal and RestoreTerminal to re-use input and terminal (#237)
* add: program.ReleaseTerminal and RestoreTerminal to re-use input & terminal

* chore(examples): add altscreen toggling to exec demo

* chore: put low-level altscreen stuff alongside other screen funcs

* docs: edit GoDocs for ReleaseTerminal and RestoreTerminal

* feat(renderer): add internal Msg renderMsg to immediately repaint

* fix: repaint instantly on RestoreTerminal

* fix: restore the altscreen state when restoring the terminal

* feat: implement Cmd-based API for blocking *exec.Cmds

* feat: allow Exec to return custom messages

* feat: allow Exec to be run without a callback

* fix: separate parameters for exec.Command examples

* fix: error message would get printed over by prompt in exec example

* fix: ignore signals while child process is running

* feat: allow to execute other things besides exec.Commands (#280)

* feat: allow to execute other things besides exec.Commands.

* fix: lint issues

* fix: renames, examples

* fix: callback type should be exported

* docs(exce): tiny ExecCommand doc comment correction

* chore(exec): break out Cmd for clarity's sake in example

* fix(exec): give the terminal a moment to catch up if exiting altscreen

* docs(exec): tidy up doc comments

* chore(exec): disambiguate methods for restoring the terminal state vs input

Co-authored-by: Christian Rocha <christian@rocha.is>
Co-authored-by: Carlos A Becker <caarlos0@gmail.com>
2022-04-12 10:23:10 -04:00

68 lines
1.2 KiB
Go

package main
import (
"fmt"
"os"
"os/exec"
tea "github.com/charmbracelet/bubbletea"
)
type editorFinishedMsg struct{ err error }
func openEditor() tea.Cmd {
c := exec.Command(os.Getenv("EDITOR")) //nolint:gosec
return tea.Exec(tea.WrapExecCommand(c), func(err error) tea.Msg {
return editorFinishedMsg{err}
})
}
type model struct {
altscreenActive bool
err error
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "a":
m.altscreenActive = !m.altscreenActive
cmd := tea.EnterAltScreen
if !m.altscreenActive {
cmd = tea.ExitAltScreen
}
return m, cmd
case "e":
return m, openEditor()
case "ctrl+c", "q":
return m, tea.Quit
}
case editorFinishedMsg:
if msg.err != nil {
m.err = msg.err
return m, tea.Quit
}
}
return m, nil
}
func (m model) View() string {
if m.err != nil {
return "Error: " + m.err.Error() + "\n"
}
return "Press 'e' to open your EDITOR.\nPress 'a' to toggle the altscreen\nPress 'q' to quit.\n"
}
func main() {
m := model{}
if err := tea.NewProgram(m).Start(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}