dynamo-browse/internal/common/ui/commandctrl/commandctrl.go

46 lines
892 B
Go
Raw Normal View History

package commandctrl
import (
2022-03-28 10:36:47 +00:00
tea "github.com/charmbracelet/bubbletea"
"strings"
"github.com/lmika/awstools/internal/common/ui/events"
"github.com/lmika/shellwords"
)
type CommandController struct {
2022-03-28 10:36:47 +00:00
commands map[string]Command
}
2022-03-28 10:36:47 +00:00
func NewCommandController(commands map[string]Command) *CommandController {
return &CommandController{
commands: commands,
}
}
2022-03-28 10:36:47 +00:00
func (c *CommandController) Prompt() tea.Cmd {
return func() tea.Msg {
return events.PromptForInputMsg{
Prompt: ":",
2022-03-28 10:36:47 +00:00
OnDone: func(value string) tea.Cmd {
return c.Execute(value)
},
}
}
}
2022-03-28 10:36:47 +00:00
func (c *CommandController) Execute(commandInput string) tea.Cmd {
input := strings.TrimSpace(commandInput)
if input == "" {
return nil
}
2022-03-28 10:36:47 +00:00
tokens := shellwords.Split(input)
command, ok := c.commands[tokens[0]]
if !ok {
return events.SetStatus("no such command: " + tokens[0])
}
2022-03-28 10:36:47 +00:00
return command(tokens)
}