cli: implement command line history support
Signed-off-by: Rohit Yadav <rohit@apache.org>
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 @@
// 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 @@
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 @@
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 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 @@
}
},
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),