main.go
This file
Path
examples/pipe/main.go
97 lines · 1.8 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23// An example illustrating how to pipe in data to a Bubble Tea application.4// More so, this serves as proof that Bubble Tea will automatically listen for5// keystrokes when input is not a TTY, such as when data is piped or redirected6// in.78import (9 "bufio"10 "fmt"11 "io"12 "os"13 "strings"1415 "charm.land/bubbles/v2/textinput"16 tea "charm.land/bubbletea/v2"17 "charm.land/lipgloss/v2"18)1920func main() {21 stat, err := os.Stdin.Stat()22 if err != nil {23 panic(err)24 }2526 if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {27 fmt.Println("Try piping in some text.")28 os.Exit(1)29 }3031 reader := bufio.NewReader(os.Stdin)32 var b strings.Builder3334 for {35 r, _, err := reader.ReadRune()36 if err != nil && err == io.EOF {37 break38 }39 _, err = b.WriteRune(r)40 if err != nil {41 fmt.Println("Error getting input:", err)42 os.Exit(1)43 }44 }4546 model := newModel(strings.TrimSpace(b.String()))4748 if _, err := tea.NewProgram(model).Run(); err != nil {49 fmt.Println("Couldn't start program:", err)50 os.Exit(1)51 }52}5354type model struct {55 userInput textinput.Model56}5758func newModel(initialValue string) (m model) {59 i := textinput.New()60 i.Prompt = ""6162 s := i.Styles()63 s.Cursor.Color = lipgloss.Color("63")64 i.SetStyles(s)6566 i.SetWidth(48)67 i.SetValue(initialValue)68 i.CursorEnd()69 i.Focus()7071 m.userInput = i72 return m73}7475func (m model) Init() tea.Cmd {76 return textinput.Blink77}7879func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {80 if key, ok := msg.(tea.KeyMsg); ok {81 switch key.String() {82 case "ctrl+c", "esc", "enter":83 return m, tea.Quit84 }85 }8687 var cmd tea.Cmd88 m.userInput, cmd = m.userInput.Update(msg)89 return m, cmd90}9192func (m model) View() tea.View {93 return tea.NewView(fmt.Sprintf(94 "\nYou piped in: %s\n\nPress ^C to exit",95 m.userInput.View(),96 ))97}