Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve autocompletion indexing using a radix tree. #149

Merged
merged 4 commits into from
Aug 8, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
446 changes: 204 additions & 242 deletions cmd/wavelet/shell.go → cmd/wavelet/actions.go

Large diffs are not rendered by default.

245 changes: 245 additions & 0 deletions cmd/wavelet/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
// Copyright (c) 2019 Perlin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package main

import (
"encoding/csv"
"fmt"
"io"
"strings"
"text/tabwriter"

"github.com/benpye/readline"
"github.com/perlin-network/noise/skademlia"
"github.com/perlin-network/wavelet"
"github.com/perlin-network/wavelet/log"
"github.com/rs/zerolog"
"github.com/urfave/cli"
)

const (
vtRed = "\033[31m"
vtReset = "\033[39m"
prompt = "»»»"
)

type CLI struct {
app *cli.App
rl *readline.Instance
client *skademlia.Client
ledger *wavelet.Ledger
logger zerolog.Logger
keys *skademlia.Keypair

completion []string
}

func NewCLI(client *skademlia.Client, ledger *wavelet.Ledger, keys *skademlia.Keypair) (*CLI, error) {
c := &CLI{
client: client,
ledger: ledger,
logger: log.Node(),
keys: keys,
app: cli.NewApp(),
}

c.app.Name = "wavelet"
c.app.HideVersion = true
c.app.UsageText = "command [arguments...]"
c.app.CommandNotFound = func(ctx *cli.Context, s string) {
c.logger.Error().
Msg("Unknown command: " + s)
}

// List of commands and their actions
c.app.Commands = []cli.Command{
{
Name: "status",
Aliases: []string{"l"},
Action: a(c.status),
Description: "print out information about your node",
},
{
Name: "pay",
Aliases: []string{"p"},
Action: a(c.pay),
Description: "pay the address an amount of PERLs",
},
{
Name: "call",
Aliases: []string{"c"},
Action: a(c.call),
Description: "invoke a function on a smart contract",
},
{
Name: "find",
Aliases: []string{"f"},
Action: a(c.find),
Description: "search for any wallet/smart contract/transaction",
},
{
Name: "spawn",
Aliases: []string{"s"},
Action: a(c.spawn),
Description: "test deploy a smart contract",
},
{
Name: "deposit-gas",
Aliases: []string{"g"},
Action: a(c.depositGas),
Description: "deposit gas to a smart contract",
},
{
Name: "place-stake",
Aliases: []string{"ps"},
Action: a(c.placeStake),
Description: "deposit a stake of PERLs into the network",
},
{
Name: "withdraw-stake",
Aliases: []string{"ws"},
Action: a(c.withdrawStake),
Description: "withdraw stake and diminish voting power",
},
{
Name: "withdraw-reward",
Aliases: []string{"wr"},
Action: a(c.withdrawReward),
Description: "withdraw rewards into PERLs",
},
{
Name: "exit",
Aliases: []string{"quit", ":q"},
Action: a(c.exit),
},
}

// Generate the help message
s := strings.Builder{}
s.WriteString("Commands:\n")
w := tabwriter.NewWriter(&s, 0, 0, 1, ' ', 0)

for _, c := range c.app.VisibleCommands() {
fmt.Fprintf(w,
" %s (%s) %s\t%s\n",
c.Name, strings.Join(c.Aliases, ", "), c.Usage,
c.Description,
)
}

w.Flush()
c.app.CustomAppHelpTemplate = s.String()

// Add in autocompletion
var completers = make(
[]readline.PrefixCompleterInterface,
0, len(c.app.Commands)*2+1,
)

for _, cmd := range c.app.Commands {
completers = append(completers, readline.PcItem(
cmd.Name, c.getCompleter(),
))

for _, alias := range cmd.Aliases {
completers = append(completers, readline.PcItem(
alias, c.getCompleter(),
))
}
}

var completer = readline.NewPrefixCompleter(completers...)

// Make a new readline struct
rl, err := readline.NewEx(&readline.Config{
Prompt: vtRed + prompt + vtReset + " ",
AutoComplete: completer,
HistoryFile: "/tmp/wavelet-history.tmp",
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
})

if err != nil {
return nil, err
}

c.rl = rl

log.SetWriter(
log.LoggerWavelet,
log.NewConsoleWriter(rl.Stdout(), log.FilterFor(
log.ModuleNode,
log.ModuleNetwork,
log.ModuleSync,
log.ModuleConsensus,
log.ModuleContract,
)),
)

return c, nil
}

func (cli *CLI) Start() {
ReadLoop:
for {
line, err := cli.rl.Readline()
switch err {
case readline.ErrInterrupt:
if len(line) == 0 {
break ReadLoop
}

continue ReadLoop

case io.EOF:
break ReadLoop
}

r := csv.NewReader(strings.NewReader(line))
r.Comma = ' '

s, err := r.Read()
if err != nil {
s = strings.Fields(line)
}

// Add an app name as $0
s = append([]string{cli.app.Name}, s...)

if err := cli.app.Run(s); err != nil {
cli.logger.Error().Err(err).
Msg("Failed to run command.")
}
}

cli.rl.Close()
}

func (cli *CLI) exit(ctx *cli.Context) {
cli.rl.Close()
}

func a(f func(*cli.Context)) func(*cli.Context) error {
return func(ctx *cli.Context) error {
f(ctx)
return nil
}
}
39 changes: 39 additions & 0 deletions cmd/wavelet/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) 2019 Perlin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package main

import (
"strings"

"github.com/benpye/readline"
)

func (cli *CLI) getCompleter() *readline.PrefixCompleter {
return readline.PcItemDynamic(func(line string) []string {
f := strings.Split(line, " ")
if len(f) < 2 {
return nil
}

text := f[len(f)-1]

return cli.ledger.Find(text, 10)
})
}
34 changes: 23 additions & 11 deletions cmd/wavelet/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,17 @@ type Config struct {
}

func main() {
log.SetWriter(log.LoggerWavelet, log.NewConsoleWriter(nil, log.FilterFor(log.ModuleNode, log.ModuleNetwork, log.ModuleSync, log.ModuleConsensus, log.ModuleContract)))
log.SetWriter(
log.LoggerWavelet,
log.NewConsoleWriter(nil, log.FilterFor(
log.ModuleNode,
log.ModuleNetwork,
log.ModuleSync,
log.ModuleConsensus,
log.ModuleContract,
)),
)

logger := log.Node()

app := cli.NewApp()
Expand Down Expand Up @@ -166,13 +176,15 @@ func main() {
}

// apply the toml before processing the flags
app.Before = altsrc.InitInputSourceWithContext(app.Flags, func(c *cli.Context) (altsrc.InputSourceContext, error) {
filePath := c.String("config")
if len(filePath) > 0 {
return altsrc.NewTomlSourceFromFile(filePath)
}
return &altsrc.MapInputSource{}, nil
})
app.Before = altsrc.InitInputSourceWithContext(
app.Flags, func(c *cli.Context) (altsrc.InputSourceContext, error) {
filePath := c.String("config")
if len(filePath) > 0 {
return altsrc.NewTomlSourceFromFile(filePath)
}
return &altsrc.MapInputSource{}, nil
},
)

cli.VersionPrinter = func(c *cli.Context) {
fmt.Printf("Version: %s\n", c.App.Version)
Expand Down Expand Up @@ -216,9 +228,9 @@ func main() {
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))

err := app.Run(os.Args)
if err != nil {
logger.Fatal().Err(err).Msg("Failed to parse configuration/command-line arguments.")
if err := app.Run(os.Args); err != nil {
logger.Fatal().Err(err).
Msg("Failed to parse configuration/command-line arguments.")
}
}

Expand Down
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ go 1.12
replace github.com/go-interpreter/wagon => github.com/perlin-network/wagon v0.3.1-0.20180825141017-f8cb99b55a39

require (
github.com/armon/go-radix v1.0.0
github.com/benpye/readline v0.0.0-20181117181432-5ff4ccac79cf
github.com/buaazp/fasthttprouter v0.1.1
github.com/chzyer/logex v1.1.10 // indirect
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 // indirect
github.com/dghubble/trie v0.0.0-20190512033633-6d8e3fa705df
github.com/fasthttp/websocket v1.4.0
github.com/gogo/protobuf v1.2.1
github.com/golang/snappy v0.0.1
Expand All @@ -23,6 +23,7 @@ require (
github.com/rs/zerolog v1.14.3
github.com/stretchr/testify v1.3.0
github.com/syndtr/goleveldb v1.0.0
github.com/urfave/cli v1.21.0
github.com/valyala/bytebufferpool v1.0.0
github.com/valyala/fasthttp v1.3.0
github.com/valyala/fastjson v1.4.1
Expand Down
Loading