example: improve usage content

This commit is contained in:
Cheney 2015-11-20 21:32:53 +08:00
parent 839c0013a8
commit c1adc97620
2 changed files with 30 additions and 7 deletions

View File

@ -1,12 +1,39 @@
package readline package readline
import "github.com/chzyer/readline/runes" import (
"bytes"
"strings"
"github.com/chzyer/readline/runes"
)
type PrefixCompleter struct { type PrefixCompleter struct {
Name []rune Name []rune
Children []*PrefixCompleter 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 { func NewPrefixCompleter(pc ...*PrefixCompleter) *PrefixCompleter {
return PcItem("", pc...) return PcItem("", pc...)
} }

View File

@ -12,12 +12,8 @@ import (
) )
func usage(w io.Writer) { func usage(w io.Writer) {
io.WriteString(w, ` io.WriteString(w, "commands:\n")
login io.WriteString(w, completer.Tree(" "))
setprompt <prompt>
say <hello>
bye
`[1:])
} }
var completer = readline.NewPrefixCompleter( var completer = readline.NewPrefixCompleter(