gum/input/command.go

64 lines
1.3 KiB
Go
Raw Normal View History

package input
import (
"fmt"
"os"
2022-07-20 19:39:22 +02:00
"github.com/alecthomas/kong"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
2022-08-05 00:45:19 +02:00
2022-07-31 03:29:09 +02:00
"github.com/charmbracelet/gum/internal/exit"
"github.com/charmbracelet/gum/internal/stdin"
2022-07-20 19:39:22 +02:00
"github.com/charmbracelet/gum/style"
)
// Run provides a shell script interface for the text input bubble.
// https://github.com/charmbracelet/bubbles/textinput
func (o Options) Run() error {
i := textinput.New()
2022-07-30 23:40:33 +02:00
if in, _ := stdin.Read(); in != "" && o.Value == "" {
i.SetValue(in)
} else {
i.SetValue(o.Value)
}
i.Focus()
i.Prompt = o.Prompt
i.Placeholder = o.Placeholder
i.Width = o.Width
i.PromptStyle = o.PromptStyle.ToLipgloss()
i.Cursor.Style = o.CursorStyle.ToLipgloss()
i.CharLimit = o.CharLimit
if o.Password {
i.EchoMode = textinput.EchoPassword
i.EchoCharacter = '•'
}
2022-07-31 03:29:09 +02:00
p := tea.NewProgram(model{
2022-12-13 21:05:10 +01:00
textinput: i,
aborted: false,
header: o.Header,
headerStyle: o.HeaderStyle.ToLipgloss(),
2022-07-31 03:29:09 +02:00
}, tea.WithOutput(os.Stderr))
2022-10-18 02:23:59 +02:00
tm, err := p.Run()
2022-08-05 00:45:19 +02:00
if err != nil {
return fmt.Errorf("failed to run input: %w", err)
}
2022-07-31 03:29:09 +02:00
m := tm.(model)
if m.aborted {
2022-07-31 03:41:18 +02:00
return exit.ErrAborted
2022-07-31 03:29:09 +02:00
}
fmt.Println(m.textinput.Value())
2022-08-05 00:45:19 +02:00
return nil
}
2022-07-20 19:39:22 +02:00
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
2022-08-05 00:45:19 +02:00
style.HideFlags(ctx)
return nil
2022-07-20 19:39:22 +02:00
}