本文整理汇总了Golang中github.com/chzyer/readline.NewEx函数的典型用法代码示例。如果您正苦于以下问题:Golang NewEx函数的具体用法?Golang NewEx怎么用?Golang NewEx使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewEx函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: internalRun
func (a *App) internalRun() error {
if a.commandTitle == "" {
a.commandTitle = ">"
}
var historyFile string
usr, err := user.Current()
// Only load history if we can get the user
if err == nil {
historyFile = filepath.Join(usr.HomeDir, ".command_history")
}
l, err := readline.NewEx(&readline.Config{
Prompt: a.commandTitle,
HistoryFile: historyFile,
AutoComplete: readline.NewPrefixCompleter(a.completeOptions...),
})
if err != nil {
return err
}
a.line = l
log.SetOutput(l.Stderr())
for {
l, e := a.line.Readline()
if e != nil {
return e
}
if !a.parseCommand(l) {
break // exit main loop
}
}
return nil
}
示例2: main
func main() {
rl, err := readline.NewEx(&readline.Config{
Prompt: "> ",
HistoryFile: "/tmp/readline-multiline",
DisableAutoSaveHistory: true,
})
if err != nil {
panic(err)
}
defer rl.Close()
var cmds []string
for {
line, err := rl.Readline()
if err != nil {
break
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
cmds = append(cmds, line)
if !strings.Contains(line, ";") {
rl.SetPrompt(">>> ")
continue
}
cmd := strings.Join(cmds, " ")
cmds = cmds[:0]
rl.SetPrompt("> ")
rl.SaveHistory(cmd)
println(cmd)
}
}
示例3: main
func main() {
l, err := readline.NewEx(&readline.Config{
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
})
if err != nil {
panic(err)
}
defer l.Close()
log.SetOutput(l.Stderr())
for {
line, err := l.Readline()
if err != nil {
break
}
switch line {
case "help":
usage(l.Stderr())
case "sayhello":
go func() {
for _ = range time.Tick(time.Second) {
log.Println("hello")
}
}()
case "bye":
goto exit
case "":
default:
log.Println("you said:", strconv.Quote(line))
}
}
exit:
}
示例4: runInteractive
// runInteractive runs the SQL client interactively, presenting
// a prompt to the user for each statement.
func runInteractive(conn *sqlConn, config *readline.Config) (exitErr error) {
c := cliState{conn: conn}
state := cliStart
for {
if state == cliStop {
break
}
switch state {
case cliStart:
// The readline initialization is not placed in
// the doStart() method because of the defer.
c.ins, c.exitErr = readline.NewEx(config)
if c.exitErr != nil {
return c.exitErr
}
defer func() { _ = c.ins.Close() }()
state = c.doStart(cliQuerySyntax)
case cliQuerySyntax:
state = c.doQuerySyntax(cliStartLine)
case cliStartLine:
state = c.doStartLine(cliReadLine)
case cliContinueLine:
state = c.doContinueLine(cliReadLine)
case cliReadLine:
state = c.doReadLine(cliDecidePath)
case cliDecidePath:
state = c.doDecidePath()
case cliProcessFirstLine:
state = c.doProcessFirstLine(cliReadLine, cliHandleCliCmd)
case cliHandleCliCmd:
state = c.doHandleCliCmd(cliReadLine, cliPrepareStatementLine)
case cliPrepareStatementLine:
state = c.doPrepareStatementLine(
cliStartLine, cliContinueLine, cliCheckStatement, cliRunStatement,
)
case cliCheckStatement:
state = c.doCheckStatement(cliStartLine, cliContinueLine, cliRunStatement)
case cliRunStatement:
state = c.doRunStatement(cliQuerySyntax)
default:
panic(fmt.Sprintf("unknown state: %d", state))
}
}
return c.exitErr
}
示例5: Interactive
func (app *App) Interactive() {
rl, err := readline.NewEx(&readline.Config{
Prompt: color.BlueString("say » "),
HistoryFile: app.Config.HistoryFile,
})
if err != nil {
log.Fatal(err)
}
defer rl.Close()
app.Log.SetOutput(rl.Stderr())
log.SetOutput(rl.Stderr())
color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr())
pings := make(map[string]time.Time)
// Subscribe to all replies and print them to stdout
app.Client.Subscribe("", "self", func(msg sarif.Message) {
text := msg.Text
if text == "" {
text = msg.Action + " from " + msg.Source
}
if msg.IsAction("err") {
text = color.RedString(text)
}
if sent, ok := pings[msg.CorrId]; ok {
text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3)
}
log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n ", -1))
})
// Interactive mode sends all lines from stdin.
for {
line, err := rl.Readline()
if err != nil {
if err == io.EOF {
return
}
log.Fatal(err)
}
if len(line) == 0 {
continue
}
// Publish natural message
msg := sarif.Message{
Id: sarif.GenerateId(),
Action: "natural/handle",
Text: line,
}
if *profile {
pings[msg.Id] = time.Now()
}
app.Client.Publish(msg)
}
}
示例6: GetInput
// GetInput input terminal
func GetInput(addr string) (string, error) {
prpt := fmt.Sprintf("(%s) > ", addr)
rl, err := readline.NewEx(&readline.Config{Prompt: prpt, HistoryFile: "/tmp/mem_cli_history.tmp"})
defer rl.Close()
if err != nil {
return "", err
}
line, _ := rl.Readline()
return line, nil
}
示例7: main
func main() {
//Initialize Config
GetConfig()
CheckState()
Clear()
Msg(HeaderMsg, "discord-cli - version: %s\n\n", Version)
//NewSession
Session = DiscordState.NewSession(Config.Username, Config.Password) //Please don't abuse
err := Session.Start()
if err != nil {
log.Println("Session Failed")
log.Fatalln(err)
}
//Attach New Window
InitWindow()
//Attach Even Handlers
State.Session.DiscordGo.AddHandler(newMessage)
//Setup Readline
rl, err := readline.NewEx(&readline.Config{
Prompt: "> ",
UniqueEditLine: true,
})
defer rl.Close()
log.SetOutput(rl.Stderr()) // let "log" write to l.Stderr instead of os.Stderr
//Start Listening
for {
line, _ := rl.Readline()
//QUIT
if line == ":q" {
break
}
//Parse Commands
line = ParseForCommands(line)
line = ParseForMentions(line)
if line != "" {
State.Session.DiscordGo.ChannelMessageSend(State.Channel.ID, line)
}
}
return
}
示例8: main
func main() {
rl, err := readline.NewEx(&readline.Config{
UniqueEditLine: true,
})
if err != nil {
panic(err)
}
defer rl.Close()
rl.SetPrompt("username: ")
username, err := rl.Readline()
if err != nil {
return
}
rl.ResetHistory()
log.SetOutput(rl.Stderr())
fmt.Fprintln(rl, "Hi,", username+"! My name is Dave.")
rl.SetPrompt(username + "> ")
done := make(chan struct{})
go func() {
rand.Seed(time.Now().Unix())
loop:
for {
select {
case <-time.After(time.Duration(rand.Intn(20)) * 100 * time.Millisecond):
case <-done:
break loop
}
log.Println("Dave:", "hello")
}
log.Println("Dave:", "bye")
done <- struct{}{}
}()
for {
ln := rl.Line()
if ln.CanContinue() {
continue
} else if ln.CanBreak() {
break
}
log.Println(username+":", ln.Line)
}
rl.Clean()
done <- struct{}{}
<-done
}
示例9: startLocal
func startLocal() {
rl, err := readline.NewEx(
&readline.Config{
Prompt: "> ",
},
)
if err != nil {
panic(err)
}
g := NewLocalGame(rl)
g.play()
}
示例10: main
func main() {
l, err := readline.NewEx(&readline.Config{
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
AutoComplete: completer,
})
if err != nil {
panic(err)
}
defer l.Close()
log.SetOutput(l.Stderr())
for {
line, err := l.Readline()
if err != nil {
break
}
switch {
case line == "help":
usage(l.Stderr())
case strings.HasPrefix(line, "setprompt"):
prompt := line[10:]
if prompt == "" {
log.Println("setprompt <prompt>")
break
}
l.SetPrompt(prompt)
case strings.HasPrefix(line, "say"):
line := strings.TrimSpace(line[3:])
if len(line) == 0 {
log.Println("say what?")
break
}
go func() {
for _ = range time.Tick(time.Second) {
log.Println(line)
}
}()
case line == "bye":
goto exit
case line == "":
default:
log.Println("you said:", strconv.Quote(line))
}
}
exit:
}
示例11: NewShell
// NewShell creates a new shell with default settings. Uses standard output and default prompt ">>".
func NewShell(completer *readline.PrefixCompleter) *Shell {
shell := &Shell{
prompt: defaultPrompt,
showPrompt: true,
functions: make(map[string]CmdFunc),
reader: &shellReader{
scanner: bufio.NewReader(os.Stdin),
},
writer: os.Stdout,
haltChan: make(chan struct{}),
}
rl, err := readline.NewEx(&readline.Config{Prompt: shell.prompt, AutoComplete: completer})
if err != nil {
panic(err)
}
shell.rl = rl
addDefaultFuncs(shell)
return shell
}
示例12: modeInteractive
func (c *ConsoleCommand) modeInteractive(session *repl.Session, ui cli.Ui) int {
// Configure input
l, err := readline.NewEx(wrappedreadline.Override(&readline.Config{
Prompt: "> ",
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
}))
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing console: %s",
err))
return 1
}
defer l.Close()
for {
// Read a line
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
out, err := session.Handle(line)
if err == repl.ErrSessionExit {
break
}
if err != nil {
ui.Error(err.Error())
continue
}
ui.Output(out)
}
return 0
}
示例13: main
func main() {
rl, err := readline.NewEx(&readline.Config{
Prompt: "> ",
HistoryFile: "/tmp/flagly-shell.readline",
})
if err != nil {
println(err.Error())
os.Exit(1)
}
defer rl.Close()
var p Program
fset, err := flagly.Compile("", &p)
if err != nil {
println(err.Error())
os.Exit(1)
}
rl.Config.AutoComplete = &readline.SegmentComplete{fset.Completer()}
for {
line, err := rl.Readline()
if err != nil {
break
}
if line == "" {
continue
}
command, err := shlex.Split(line)
if err != nil {
println("error: " + err.Error())
continue
}
if err := fset.Run(command); err != nil {
println(err.Error())
}
}
}
示例14: main
func main() {
l, err := readline.NewEx(&readline.Config{
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
AutoComplete: completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
})
if err != nil {
panic(err)
}
defer l.Close()
setPasswordCfg := l.GenPasswordConfig()
setPasswordCfg.SetListener(func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
l.SetPrompt(fmt.Sprintf("Enter password(%v): ", len(line)))
l.Refresh()
return nil, 0, false
})
log.SetOutput(l.Stderr())
for {
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
line = strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "mode "):
switch line[5:] {
case "vi":
l.SetVimMode(true)
case "emacs":
l.SetVimMode(false)
default:
println("invalid mode:", line[5:])
}
case line == "mode":
if l.IsVimMode() {
println("current mode: vim")
} else {
println("current mode: emacs")
}
case line == "login":
pswd, err := l.ReadPassword("please enter your password: ")
if err != nil {
break
}
println("you enter:", strconv.Quote(string(pswd)))
case line == "help":
usage(l.Stderr())
case line == "setpassword":
pswd, err := l.ReadPasswordWithConfig(setPasswordCfg)
if err == nil {
println("you set:", strconv.Quote(string(pswd)))
}
case strings.HasPrefix(line, "setprompt"):
if len(line) <= 10 {
log.Println("setprompt <prompt>")
break
}
l.SetPrompt(line[10:])
case strings.HasPrefix(line, "say"):
line := strings.TrimSpace(line[3:])
if len(line) == 0 {
log.Println("say what?")
break
}
go func() {
for range time.Tick(time.Second) {
log.Println(line)
}
}()
case line == "bye":
goto exit
case line == "sleep":
log.Println("sleep 4 second")
time.Sleep(4 * time.Second)
case line == "":
default:
log.Println("you said:", strconv.Quote(line))
}
}
exit:
}
示例15: main
func main() {
kingpin.Parse()
var conn net.Conn
var err error
if *rawtls {
conn, err = tls.Dial("tcp", *address, &tls.Config{
InsecureSkipVerify: true,
})
if err != nil {
fmt.Fprintf(os.Stderr, "Connect failed: %v\n", err)
return
}
} else {
conn, err = net.Dial("tcp", *address)
if err != nil {
fmt.Fprintf(os.Stderr, "Connect failed: %v\n", err)
return
}
}
c := client.New(conn)
go func() {
err := c.Serve()
if err != nil {
fmt.Fprintf(os.Stderr, "\nConnection lost: %v\n", err)
os.Exit(-1)
}
}()
_, _, err = c.Version(1024*1024, qp.Version)
if err != nil {
fmt.Fprintf(os.Stderr, "Version failed: %v\n", err)
return
}
root, _, err := c.Attach(nil, *user, *service)
if err != nil {
fmt.Fprintf(os.Stderr, "Attach failed: %v\n", err)
return
}
cwd := root
confirmation, err = readline.New("")
if err != nil {
fmt.Fprintf(os.Stderr, "Could not make confirmation readline instance: %v\n", err)
return
}
if len(*command) > 0 {
args := ""
for i := 1; i < len(*command); i++ {
if i != 1 {
args += " "
}
args += (*command)[i]
}
f, ok := cmds[(*command)[0]]
if !ok {
fmt.Fprintf(os.Stderr, "no such command: [%s]\n", *command)
return
}
cwd, err = f(root, cwd, args)
if err != nil {
fmt.Fprintf(os.Stderr, "\ncommand %s failed: %v\n", *command, err)
}
return
}
completer := readline.NewPrefixCompleter()
for k := range cmds {
completer.Children = append(completer.Children, readline.PcItem(k))
}
rl, err := readline.NewEx(&readline.Config{
Prompt: "9p> ",
AutoComplete: completer,
})
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create readline: %v\n", err)
return
}
defer rl.Close()
fmt.Fprintf(os.Stderr, "Welcome to the qptools 9P cli.\nPress tab to see available commands.\n")
for {
line, err := rl.Readline()
if err != nil { // io.EOF
break
}
idx := strings.Index(line, " ")
var cmd, args string
if idx != -1 {
cmd = line[:idx]
//.........这里部分代码省略.........