浏览代码

优化修改sshd模块客户端代码,使其交互更加友好

niujiuru 2 周之前
父节点
当前提交
20caf558ac
共有 1 个文件被更改,包括 24 次插入1 次删除
  1. 24 1
      sshd/client/client.go

+ 24 - 1
sshd/client/client.go

@@ -1,6 +1,7 @@
 package main
 
 import (
+	"bufio"
 	"context"
 	"encoding/json"
 	"errors"
@@ -98,10 +99,20 @@ func term(pingState *atomic.Bool) {
 	line.SetTabCompletionStyle(liner.TabCircular)
 
 	historyFile := "history.txt"
+	var history []string
+
 	if f, err := os.Open(historyFile); err == nil {
-		line.ReadHistory(f)
+		scanner := bufio.NewScanner(f)
+		for scanner.Scan() {
+			cmd := strings.TrimSpace(scanner.Text())
+			if cmd != "" {
+				history = append(history, cmd)
+				line.AppendHistory(cmd)
+			}
+		}
 		f.Close()
 	}
+
 	defer func() {
 		if f, err := os.Create(historyFile); err == nil {
 			line.WriteHistory(f)
@@ -109,6 +120,16 @@ func term(pingState *atomic.Bool) {
 		}
 	}()
 
+	line.SetCompleter(func(input string) []string { // 补全
+		var matches []string
+		for _, cmd := range history {
+			if strings.HasPrefix(cmd, input) {
+				matches = append(matches, cmd)
+			}
+		}
+		return matches
+	})
+
 	for {
 		if !pingState.Load() {
 			fmt.Printf("[%s] 目标设备连接丢失!!\n", MODULE_NAME)
@@ -142,6 +163,8 @@ func term(pingState *atomic.Bool) {
 
 		line.AppendHistory(input) ///// 保存用户输入的历史命令
 
+		history = append(history, input) ///// 本次也立刻生效
+
 		if input == "exit" || input == "quit" {
 			_, _ = coupler.quit()
 			break