Init mx; we have working readline
Anirudh Oppiliappan x@icyphox.sh
Mon, 28 Jun 2021 10:09:33 +0530
4 files changed,
73 insertions(+),
0 deletions(-)
A
go.mod
@@ -0,0 +1,5 @@
+module git.icyphox.sh/mx + +go 1.16 + +require github.com/peterh/liner v1.2.1
A
go.sum
@@ -0,0 +1,4 @@
+github.com/mattn/go-runewidth v0.0.3 h1:a+kO+98RDGEfo6asOGMmpodZq4FNtnGP54yps8BzLR4= +github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/peterh/liner v1.2.1 h1:O4BlKaq/LWu6VRWmol4ByWfzx6MfXc5Op5HETyIy5yg= +github.com/peterh/liner v1.2.1/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0=
A
main.go
@@ -0,0 +1,63 @@
+package main + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/peterh/liner" +) + +var ( + hd, _ = os.UserHomeDir() + histfile = filepath.Join(hd, ".mx.hist") + commands = []string{ + "some", + "commands", + "here", + } +) + +func main() { + line := liner.NewLiner() + defer line.Close() + + line.SetCtrlCAborts(true) + + line.SetCompleter(func(line string) (c []string) { + for _, n := range commands { + if strings.HasPrefix(n, strings.ToLower(line)) { + c = append(c, n) + } + } + return + }) + + if f, err := os.Open(histfile); err == nil { + line.ReadHistory(f) + f.Close() + } + + prompt := "" + for { + if cmd, err := line.Prompt(prompt + " > "); err == nil { + // processCmd(cmd) + line.AppendHistory(cmd) + prompt = cmd + } else if err == liner.ErrPromptAborted || err == io.EOF { + fmt.Print("bye!") + break + } else { + fmt.Printf("error reading line: %+v") + } + } + + if f, err := os.Create(histfile); err != nil { + fmt.Printf("error writing history file: %+v", err) + } else { + line.WriteHistory(f) + f.Close() + } +}