Skip to content

Commit

Permalink
connect: cleanup the module
Browse files Browse the repository at this point in the history
As far as the module has been copied from cartridge-cli without any
changes, this patch has the following targets:
* add a description for public methods
* remove unneeded code
* squash similar part of code

Part of #15
  • Loading branch information
LeonidVas committed Apr 20, 2022
1 parent c0cd097 commit e2053f0
Show file tree
Hide file tree
Showing 15 changed files with 92 additions and 220 deletions.
7 changes: 6 additions & 1 deletion cli/cmd/connect.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package cmd

import (
"syscall"

"github.com/apex/log"
"github.com/spf13/cobra"
"github.com/tarantool/tt/cli/cmdcontext"
"github.com/tarantool/tt/cli/connect"
"github.com/tarantool/tt/cli/modules"
"golang.org/x/crypto/ssh/terminal"
)

var (
Expand Down Expand Up @@ -38,7 +41,9 @@ func internalConnectModule(cmdCtx *cmdcontext.CmdCtx, args []string) error {
cmdCtx.Connect.Username = connectUser
cmdCtx.Connect.Password = connectPassword

log.Info("Connecting to the instance...")
if terminal.IsTerminal(syscall.Stdin) {
log.Info("Connecting to the instance...")
}
if err := connect.Connect(cmdCtx, args); err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cli/cmd/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func getInternalHelpFunc(cmd *cobra.Command, help DefaultHelpFunc) modules.Inter

// helpFlagError prints some help information if the user entered an invalid flag.
func helpFlagError(cmd *cobra.Command, errMsg error) error {
templatedStr, err := util.GetTemplatedStr(&errorUsageTemplate, map[string]interface{}{
templatedStr, err := util.GetHTMLTemplatedStr(&errorUsageTemplate, map[string]interface{}{
"ErrorMsg": errMsg,
"Cmd": cmd.CommandPath(),
"HasFlags": cmd.HasAvailableFlags(),
Expand Down
1 change: 0 additions & 1 deletion cli/codegen/generate_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ var luaCodeFiles = []generateLuaCodeOpts{
VariablesMap: map[string]string{
"evalFuncBody": "cli/connect/lua/eval_func_body.lua",
"getSuggestionsFuncBody": "cli/connect/lua/get_suggestions_func_body.lua",
"getTitleFuncBody": "cli/connect/lua/get_title_func_body.lua",
},
},
{
Expand Down
70 changes: 0 additions & 70 deletions cli/connect/common.go

This file was deleted.

15 changes: 9 additions & 6 deletions cli/connect/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,26 @@ import (
"fmt"

"github.com/tarantool/tt/cli/cmdcontext"
"github.com/tarantool/tt/cli/connector"
)

const (
// see https://github.com/tarantool/tarantool/blob/b53cb2aeceedc39f356ceca30bd0087ee8de7c16/src/box/lua/console.c#L265
tarantoolWordSeparators = "\t\r\n !\"#$%&'()*+,-/;<=>?@[\\]^`{|}~"
)

func getConnOpts(connString string, cmdCtx *cmdcontext.CmdCtx) *connector.ConnOpts {
return connector.GetConnOpts(connString, cmdCtx.Connect.Username, cmdCtx.Connect.Password)
}

// Connect establishes a connection to the instance and starts the console.
func Connect(cmdCtx *cmdcontext.CmdCtx, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Should be specified one connection string")
}

connString := args[0]

connOpts, err := getConnOpts(connString, cmdCtx)
if err != nil {
return fmt.Errorf("Failed to get connection opts: %s", err)
}
connOpts := getConnOpts(connString, cmdCtx)

if err := runConsole(connOpts, ""); err != nil {
return fmt.Errorf("Failed to run interactive console: %s", err)
Expand All @@ -30,7 +32,8 @@ func Connect(cmdCtx *cmdcontext.CmdCtx, args []string) error {
return nil
}

func runConsole(connOpts *ConnOpts, title string) error {
// runConsole run a new console.
func runConsole(connOpts *connector.ConnOpts, title string) error {
console, err := NewConsole(connOpts, title)
if err != nil {
return fmt.Errorf("Failed to create new console: %s", err)
Expand Down
80 changes: 32 additions & 48 deletions cli/connect/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,28 @@ import (
"path/filepath"
"sort"
"strings"
"syscall"
"time"

"github.com/adam-hanna/arrayOperations"
"github.com/apex/log"
lua "github.com/yuin/gopher-lua"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/yaml.v2"

"github.com/c-bata/go-prompt"
"github.com/tarantool/tt/cli/connector"
"github.com/tarantool/tt/cli/util"
)

// EvalFunc defines a function type for evaluating an expression via connection.
type EvalFunc func(console *Console, funcBodyFmt string, args ...interface{}) (interface{}, error)

const (
HistoryFileName = ".tarantool_history"

MaxLivePrefixIndent = 15
MaxHistoryLines = 10000
)

var (
Expand All @@ -38,6 +42,7 @@ func init() {
ControlRightBytes = []byte{0x1b, 0x66}
}

// Console describes the console connected to the tarantool instance.
type Console struct {
input string

Expand All @@ -52,7 +57,7 @@ type Console struct {
livePrefix string
livePrefixFunc func() (string, bool)

connOpts *ConnOpts
connOpts *connector.ConnOpts
conn *connector.Conn

executor func(in string)
Expand All @@ -63,7 +68,8 @@ type Console struct {
prompt *prompt.Prompt
}

func NewConsole(connOpts *ConnOpts, title string) (*Console, error) {
// NewConsole creates a new console connected to the tarantool instance.
func NewConsole(connOpts *connector.ConnOpts, title string) (*Console, error) {
console := &Console{
title: title,
connOpts: connOpts,
Expand All @@ -72,60 +78,48 @@ func NewConsole(connOpts *ConnOpts, title string) (*Console, error) {

var err error

// load Tarantool console history from file
// Load Tarantool console history from file.
if err := loadHistory(console); err != nil {
log.Debugf("Failed to load Tarantool console history: %s", err)
}

// connect to specified address
console.conn, err = connector.Connect(connOpts.Address, connector.Opts{
Username: connOpts.Username,
Password: connOpts.Password,
})
// Connect to specified address.
console.conn, err = connector.Connect(connOpts.Address, connOpts.Username, connOpts.Password)
if err != nil {
return nil, fmt.Errorf("Failed to connect: %s", err)
}

// initialize user commands executor
// Initialize user commands executor.
console.executor = getExecutor(console)

// initialize commands completer
// Initialize commands completer.
console.completer = getCompleter(console)

// set title and prompt prefix
// <app-name>.<instance-name> for Cartridge application instances
// <host>:<port> otherwise
// Set title and prompt prefix.
setTitle(console)
setPrefix(console)

return console, nil
}

// Run starts console.
func (console *Console) Run() error {
var err error

fmt.Printf("connected to %s\n", console.title)

pipedInputIsFound, err := util.StdinHasUnreadData()
if err != nil {
return fmt.Errorf("Failed to check unread data from stdin: %s", err)
}

if pipedInputIsFound {
if !terminal.IsTerminal(syscall.Stdin) {
log.Debugf("Found piped input")
// e.g. `echo "box.info()" | cartridge enter router`
pipedInputScanner := bufio.NewScanner(os.Stdin)
for pipedInputScanner.Scan() {
line := pipedInputScanner.Text()
console.executor(line)
}
return nil
} else {
log.Infof("Connected to %s\n", console.title)
}

// get options for Prompt instance
// Get options for Prompt instance.
options := getPromptOptions(console)

// create Prompt instance
// Create Prompt instance.
console.prompt = prompt.New(
console.executor,
console.completer,
Expand All @@ -137,6 +131,7 @@ func (console *Console) Run() error {
return nil
}

// Close frees up resources used by the console.
func (console *Console) Close() {
if console.historyFile != nil {
console.historyFile.Close()
Expand All @@ -158,8 +153,8 @@ func loadHistory(console *Console) error {
return fmt.Errorf("Failed to read history from file: %s", err)
}

// open history file for appending
// see https://unix.stackexchange.com/questions/346062/concurrent-writing-to-a-log-file-from-many-processes
// Open history file for appending.
// See https://unix.stackexchange.com/questions/346062/concurrent-writing-to-a-log-file-from-many-processes
console.historyFile, err = os.OpenFile(
console.historyFilePath,
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
Expand Down Expand Up @@ -219,16 +214,14 @@ func getExecutor(console *Console) prompt.Executor {
}

func inputIsCompleted(input string, luaState *lua.LState) bool {
// see https://github.com/tarantool/tarantool/blob/b53cb2aeceedc39f356ceca30bd0087ee8de7c16/src/box/lua/console.lua#L575
// See https://github.com/tarantool/tarantool/blob/b53cb2aeceedc39f356ceca30bd0087ee8de7c16/src/box/lua/console.lua#L575
if _, err := luaState.LoadString(input); err == nil || !strings.Contains(err.Error(), "at EOF") {
// valid Lua code or a syntax error not due to
// an incomplete input
// Valid Lua code or a syntax error not due to an incomplete input.
return true
}

if _, err := luaState.LoadString(fmt.Sprintf("return %s", input)); err == nil {
// certain obscure inputs like '(42\n)' yield the
// same error as incomplete statement
// Certain obscure inputs like '(42\n)' yield the same error as incomplete statement.
return true
}

Expand Down Expand Up @@ -279,18 +272,7 @@ func getCompleter(console *Console) prompt.Completer {
func setTitle(console *Console) {
if console.title != "" {
return
}

req := connector.EvalReq(getTitleFuncBody)

var titlesSlice []string
if err := console.conn.ExecTyped(req, &titlesSlice); err != nil {
log.Debugf("Failed to get instance title: %s", err)
} else {
console.title = titlesSlice[0]
}

if console.title == "" {
console.title = console.connOpts.Address
}
}
Expand Down Expand Up @@ -324,15 +306,17 @@ func getPromptOptions(console *Console) []prompt.Option {
prompt.OptionCompletionWordSeparator(tarantoolWordSeparators),

prompt.OptionAddASCIICodeBind(
prompt.ASCIICodeBind{ // move to one word left
// Move to one word left.
prompt.ASCIICodeBind{
ASCIICode: ControlLeftBytes,
Fn: func(buf *prompt.Buffer) {
d := buf.Document()
wordLen := len([]rune(d.GetWordBeforeCursorWithSpace()))
buf.CursorLeft(wordLen)
},
},
prompt.ASCIICodeBind{ // move to one word right
// Move to one word right.
prompt.ASCIICodeBind{
ASCIICode: ControlRightBytes,
Fn: func(buf *prompt.Buffer) {
d := buf.Document()
Expand All @@ -341,9 +325,9 @@ func getPromptOptions(console *Console) []prompt.Option {
},
},
),

// Interrupt current unfinished expression.
prompt.OptionAddKeyBind(
prompt.KeyBind{ // Interrupt current unfinished expression
prompt.KeyBind{
Key: prompt.ControlC,
Fn: func(buf *prompt.Buffer) {
console.input = ""
Expand Down
11 changes: 0 additions & 11 deletions cli/connect/lua/get_title_func_body.lua

This file was deleted.

0 comments on commit e2053f0

Please sign in to comment.