This is an automated email from the ASF dual-hosted git repository. rohit pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git
commit 38972f240b0986d656cd55f38a4753ea4709c490 Author: Rohit Yadav <[email protected]> AuthorDate: Mon Oct 22 00:44:46 2018 +0530 cli: implement command line history support Signed-off-by: Rohit Yadav <[email protected]> --- cli/exec.go | 1 + cli/history.go | 32 ++++++++++++++++++++++++++++---- cli/prompt.go | 5 +---- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/cli/exec.go b/cli/exec.go index ec378cf..99bf996 100644 --- a/cli/exec.go +++ b/cli/exec.go @@ -29,6 +29,7 @@ import ( // ExecLine executes a line of command func ExecLine(line string) error { + writeHistory(line) args, err := shlex.Split(line) if err != nil { return err diff --git a/cli/history.go b/cli/history.go index 7e2ca3f..dd09553 100644 --- a/cli/history.go +++ b/cli/history.go @@ -18,13 +18,22 @@ package cli import ( "bufio" + "fmt" "os" ) -func readLines(path string) ([]string, error) { - file, err := os.Open(path) +func initHistory() { + if _, err := os.Stat(cfg.HistoryFile); os.IsNotExist(err) { + os.OpenFile(cfg.HistoryFile, os.O_RDONLY|os.O_CREATE, 0600) + } +} + +func readHistory() []string { + initHistory() + file, err := os.Open(cfg.HistoryFile) if err != nil { - return nil, err + fmt.Println("Failed to open history file:", err) + return nil } defer file.Close() @@ -33,5 +42,20 @@ func readLines(path string) ([]string, error) { for scanner.Scan() { lines = append(lines, scanner.Text()) } - return lines, scanner.Err() + if scanner.Err() != nil { + fmt.Println("Failed to read history:", scanner.Err()) + } + return lines +} + +func writeHistory(in string) { + file, err := os.OpenFile(cfg.HistoryFile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + fmt.Println("Failed to open history file:", err) + } + defer file.Close() + + if _, err = file.WriteString(in + "\n"); err != nil { + fmt.Println("Failed to write history:", err) + } } diff --git a/cli/prompt.go b/cli/prompt.go index c558730..540a927 100644 --- a/cli/prompt.go +++ b/cli/prompt.go @@ -36,9 +36,6 @@ func SetConfig(c *config.Config) { func ExecPrompt() { cfg.HasShell = true cfg.PrintHeader() - - lines, _ := readLines(cfg.HistoryFile) - shell := prompt.New( func(in string) { if err := ExecLine(in); err != nil { @@ -46,13 +43,13 @@ func ExecPrompt() { } }, completer, + prompt.OptionHistory(readHistory()), prompt.OptionTitle("cloudmonkey"), prompt.OptionPrefix(cfg.GetPrompt()), prompt.OptionLivePrefix(func() (string, bool) { return cfg.GetPrompt(), true }), prompt.OptionMaxSuggestion(5), - prompt.OptionHistory(lines), prompt.OptionPrefixTextColor(prompt.DefaultColor), prompt.OptionPreviewSuggestionTextColor(prompt.DarkBlue), prompt.OptionSelectedSuggestionTextColor(prompt.White),
