1 Star 3 Fork 1

Joshua Conero / uymas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
repl.go 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
package bin
import (
"bufio"
"fmt"
"gitee.com/conero/uymas/bin/parser"
"gitee.com/conero/uymas/util"
"os"
"strings"
)
const (
ReplContinue = iota
ReplBreak
ReplExit
)
type Repl struct {
Name string
Title string
HandlerFunc func(string) int
BeforeExit func() // 退出前回调
Exit []string // 退出列表,默认为 exit
}
// Run to start repl command
func (c Repl) Run(cli *CLI) {
var input = bufio.NewScanner(os.Stdin)
name := c.Name
if name != "" {
name = " " + name
}
tip := fmt.Sprintf("$%v> ", name)
if c.Title != "" {
fmt.Println(c.Title)
}
// 退出命令
toExit := func() {
if c.BeforeExit != nil {
c.BeforeExit()
}
os.Exit(0)
}
fmt.Print(tip)
for input.Scan() {
text := input.Text()
text = strings.TrimSpace(text)
isBreak := false
switch text {
default:
if c.Exit == nil && text == "exit" {
toExit()
} else if util.ListIndex(c.Exit, text) > -1 {
toExit()
}
if c.HandlerFunc != nil {
switch c.HandlerFunc(text) {
case ReplBreak:
isBreak = true
case ReplExit:
os.Exit(0)
case ReplContinue:
continue
}
}
if isBreak {
break
}
var cmdsList = parser.NewParser(text)
for _, cmdArgs := range cmdsList {
cli.Run(cmdArgs...)
}
}
if isBreak {
break
}
fmt.Println()
fmt.Println()
fmt.Print(tip)
}
}
// ReplCommand create a repl cli sub command
func ReplCommand(name string, cli *CLI) {
repl := Repl{
Name: name,
}
repl.Run(cli)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/conero/uymas.git
git@gitee.com:conero/uymas.git
conero
uymas
uymas
v1.4.0-alpha.1

搜索帮助

344bd9b3 5694891 D2dac590 5694891