From c1adc97620bdfd1d3f538a5951cf7215950b3381 Mon Sep 17 00:00:00 2001 From: Cheney Date: Fri, 20 Nov 2015 21:32:53 +0800 Subject: [PATCH] example: improve usage content --- complete_helper.go | 29 ++++++++++++++++++++++++++++- example/main.go | 8 ++------ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/complete_helper.go b/complete_helper.go index 114190e..7e8a807 100644 --- a/complete_helper.go +++ b/complete_helper.go @@ -1,12 +1,39 @@ package readline -import "github.com/chzyer/readline/runes" +import ( + "bytes" + "strings" + + "github.com/chzyer/readline/runes" +) type PrefixCompleter struct { Name []rune Children []*PrefixCompleter } +func (p *PrefixCompleter) Tree(prefix string) string { + buf := bytes.NewBuffer(nil) + p.Print(prefix, 0, buf) + return buf.String() +} + +func (p *PrefixCompleter) Print(prefix string, level int, buf *bytes.Buffer) { + if strings.TrimSpace(string(p.Name)) != "" { + buf.WriteString(prefix) + if level > 0 { + buf.WriteString("├") + buf.WriteString(strings.Repeat("─", (level*4)-2)) + buf.WriteString(" ") + } + buf.WriteString(string(p.Name) + "\n") + level++ + } + for _, ch := range p.Children { + ch.Print(prefix, level, buf) + } +} + func NewPrefixCompleter(pc ...*PrefixCompleter) *PrefixCompleter { return PcItem("", pc...) } diff --git a/example/main.go b/example/main.go index 5b5ed3b..23b1ffc 100644 --- a/example/main.go +++ b/example/main.go @@ -12,12 +12,8 @@ import ( ) func usage(w io.Writer) { - io.WriteString(w, ` -login -setprompt -say -bye -`[1:]) + io.WriteString(w, "commands:\n") + io.WriteString(w, completer.Tree(" ")) } var completer = readline.NewPrefixCompleter(