readline/example/main.go

111 lines
2.0 KiB
Go
Raw Normal View History

2015-09-20 18:14:29 +03:00
package main
import (
"io"
"log"
"strconv"
2015-09-25 17:56:00 +03:00
"strings"
2015-09-20 18:14:29 +03:00
"time"
"github.com/chzyer/readline"
)
2015-09-21 17:27:40 +03:00
func usage(w io.Writer) {
io.WriteString(w, `
2015-09-30 09:16:46 +03:00
login
2015-09-27 13:54:26 +03:00
setprompt <prompt>
say <hello>
bye
2015-09-21 17:27:40 +03:00
`[1:])
}
2015-09-25 19:31:09 +03:00
var completer = readline.NewPrefixCompleter(
2015-10-02 05:37:21 +03:00
readline.PcItem("mode",
readline.PcItem("vi"),
readline.PcItem("emacs"),
),
2015-09-30 09:16:46 +03:00
readline.PcItem("login"),
2015-09-25 19:31:09 +03:00
readline.PcItem("say",
readline.PcItem("hello"),
readline.PcItem("bye"),
),
2015-09-27 13:54:26 +03:00
readline.PcItem("setprompt"),
2015-09-25 19:31:09 +03:00
readline.PcItem("bye"),
readline.PcItem("help"),
readline.PcItem("go",
readline.PcItem("build"),
readline.PcItem("install"),
readline.PcItem("test"),
),
)
2015-09-25 17:56:00 +03:00
2015-09-20 18:14:29 +03:00
func main() {
2015-09-22 13:16:24 +03:00
l, err := readline.NewEx(&readline.Config{
2015-09-25 17:56:00 +03:00
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
2015-09-25 19:31:09 +03:00
AutoComplete: completer,
2015-09-22 13:16:24 +03:00
})
2015-09-20 18:14:29 +03:00
if err != nil {
panic(err)
}
2015-09-21 08:30:10 +03:00
defer l.Close()
2015-09-20 18:14:29 +03:00
log.SetOutput(l.Stderr())
for {
line, err := l.Readline()
if err != nil {
break
}
2015-10-02 05:37:21 +03:00
line = strings.TrimSpace(line)
2015-09-25 19:31:09 +03:00
switch {
2015-10-02 05:37:21 +03:00
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")
}
2015-09-30 09:16:46 +03:00
case line == "login":
pswd, err := l.ReadPassword("please enter your password: ")
if err != nil {
break
}
println("you enter:", strconv.Quote(string(pswd)))
2015-09-25 19:31:09 +03:00
case line == "help":
2015-09-21 17:27:40 +03:00
usage(l.Stderr())
2015-09-27 13:54:26 +03:00
case strings.HasPrefix(line, "setprompt"):
prompt := line[10:]
if prompt == "" {
log.Println("setprompt <prompt>")
break
}
l.SetPrompt(prompt)
2015-09-25 19:31:09 +03:00
case strings.HasPrefix(line, "say"):
line := strings.TrimSpace(line[3:])
if len(line) == 0 {
log.Println("say what?")
break
}
2015-09-20 18:14:29 +03:00
go func() {
for _ = range time.Tick(time.Second) {
2015-09-25 19:31:09 +03:00
log.Println(line)
2015-09-20 18:14:29 +03:00
}
}()
2015-09-25 19:31:09 +03:00
case line == "bye":
2015-09-20 18:14:29 +03:00
goto exit
2015-09-25 19:31:09 +03:00
case line == "":
2015-09-20 18:14:29 +03:00
default:
log.Println("you said:", strconv.Quote(line))
}
}
exit:
}