bedrocktool/utils/iui.go

95 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-03-06 14:50:36 +00:00
package utils
import (
"bufio"
2023-03-06 14:50:36 +00:00
"context"
"flag"
"fmt"
"os"
"strings"
"github.com/bedrock-tool/bedrocktool/locale"
2023-03-18 11:12:54 +00:00
"github.com/bedrock-tool/bedrocktool/ui/messages"
2023-03-06 14:50:36 +00:00
"github.com/google/subcommands"
"github.com/sirupsen/logrus"
2023-03-06 14:50:36 +00:00
)
type UI interface {
Init() bool
2023-03-08 11:46:16 +00:00
Start(context.Context, context.CancelFunc) error
2023-04-01 22:22:50 +00:00
Message(data interface{}) messages.MessageResponse
ServerInput(context.Context, string) (string, string, error)
2023-03-06 14:50:36 +00:00
}
type BaseUI struct {
2023-03-06 14:50:36 +00:00
UI
}
2023-04-01 22:22:50 +00:00
func (u *BaseUI) Message(data interface{}) messages.MessageResponse {
2023-03-18 11:12:54 +00:00
return messages.MessageResponse{
Ok: false,
Data: nil,
}
}
func (u *BaseUI) ServerInput(ctx context.Context, server string) (string, string, error) {
address, name, err := ServerInput(ctx, server)
return address, name, err
2023-03-06 14:50:36 +00:00
}
2023-03-14 01:07:39 +00:00
var CurrentUI UI
func SetCurrentUI(ui UI) {
2023-03-14 01:07:39 +00:00
CurrentUI = ui
}
type InteractiveCLI struct {
BaseUI
}
func (c *InteractiveCLI) Init() bool {
2023-03-14 01:07:39 +00:00
CurrentUI = c
return true
}
2023-03-08 11:46:16 +00:00
func (c *InteractiveCLI) Start(ctx context.Context, cancel context.CancelFunc) error {
2023-03-06 14:50:36 +00:00
select {
case <-ctx.Done():
return nil
2023-03-06 14:50:36 +00:00
default:
fmt.Println(locale.Loc("available_commands", nil))
for name, cmd := range ValidCMDs {
fmt.Printf("\t%s\t%s\n", name, cmd.Synopsis())
}
fmt.Println(locale.Loc("use_to_run_command", nil))
2023-05-05 17:52:18 +00:00
cmd, cancelled := UserInput(ctx, locale.Loc("input_command", nil), func(s string) bool {
for k := range ValidCMDs {
if s == k {
return true
}
}
return false
})
2023-03-06 14:50:36 +00:00
if cancelled {
2023-03-08 11:46:16 +00:00
cancel()
return nil
2023-03-06 14:50:36 +00:00
}
_cmd := strings.Split(cmd, " ")
os.Args = append(os.Args, _cmd...)
}
flag.Parse()
subcommands.Execute(ctx)
if Options.IsInteractive {
logrus.Info(locale.Loc("enter_to_exit", nil))
input := bufio.NewScanner(os.Stdin)
input.Scan()
}
2023-03-06 14:50:36 +00:00
return nil
}
var MakeGui = func() UI {
return &InteractiveCLI{}
}