sqs-browse: started working on put commands

This commit is contained in:
Leon Mika 2022-03-24 12:54:32 +11:00
parent 43680000a8
commit cecdbafabb
17 changed files with 339 additions and 26 deletions

View file

@ -0,0 +1,48 @@
package commandctrl
import (
"context"
"github.com/lmika/awstools/internal/common/ui/events"
"github.com/lmika/awstools/internal/common/ui/uimodels"
"github.com/lmika/shellwords"
"github.com/pkg/errors"
"strings"
)
type CommandController struct {
commands map[string]uimodels.Operation
}
func NewCommandController(commands map[string]uimodels.Operation) *CommandController {
return &CommandController{
commands: commands,
}
}
func (c *CommandController) Prompt() uimodels.Operation {
return uimodels.OperationFn(func(ctx context.Context) error {
uiCtx := uimodels.Ctx(ctx)
uiCtx.Send(events.PromptForInput{
Prompt: ":",
OnDone: c.Execute(),
})
return nil
})
}
func (c *CommandController) Execute() uimodels.Operation {
return uimodels.OperationFn(func(ctx context.Context) error {
input := strings.TrimSpace(uimodels.PromptValue(ctx))
if input == "" {
return nil
}
tokens := shellwords.Split(input)
command, ok := c.commands[tokens[0]]
if !ok {
return errors.New("no such command: " + tokens[0])
}
return command.Execute(WithCommandArgs(ctx, tokens[1:]))
})
}

View file

@ -0,0 +1,25 @@
package commandctrl_test
import (
"context"
"github.com/lmika/awstools/internal/common/ui/commandctrl"
"github.com/lmika/awstools/internal/common/ui/events"
"github.com/lmika/awstools/test/testuictx"
"github.com/stretchr/testify/assert"
"testing"
)
func TestCommandController_Prompt(t *testing.T) {
t.Run("prompt user for a command", func(t *testing.T) {
cmd := commandctrl.NewCommandController()
ctx, uiCtx := testuictx.New(context.Background())
err := cmd.Prompt().Execute(ctx)
assert.NoError(t, err)
promptMsg, ok := uiCtx.Messages[0].(events.PromptForInput)
assert.True(t, ok)
assert.Equal(t, ":", promptMsg.Prompt)
})
}

View file

@ -0,0 +1,15 @@
package commandctrl
import "context"
type commandArgContextKeyType struct {}
var commandArgContextKey = commandArgContextKeyType{}
func WithCommandArgs(ctx context.Context, args []string) context.Context {
return context.WithValue(ctx, commandArgContextKey, args)
}
func CommandArgs(ctx context.Context) []string {
args, _ := ctx.Value(commandArgContextKey).([]string)
return args
}