gpt4 book ai didi

go - 为 CLI 应用程序实现自动完成

转载 作者:IT王子 更新时间:2023-10-29 02:22:25 29 4
gpt4 key购买 nike

我正在考虑用 Go 编写 CLI 应用程序。

要求之一是自动完成。不是命令本身,而是可能的选项。

假设我想使用 CLI 添加一个新条目。每个条目都可以有一个类别。这些类别在 slice 中可用。我现在想要做的是让用户在输入 add 时能够在可用类别中切换。

我知道像 https://github.com/chzyer/readline 这样的库和 https://github.com/spf13/cobra但找不到他们是否或如何支持这一点。

最佳答案

感谢@ain 和@JimB 为我指明了正确的方向。

基于 https://github.com/chzyer/readline/tree/master/example/readline-demo 中提供的示例我能够实现所需的功能。

以下代码必须执行主要命令newEntrynewCategory。如果用户键入 newEntry 然后按 TAB,他可以从可用类别中进行选择。 newCategory 命令允许添加一个新的自定义类别,该类别在下次执行 newEntry 时立即可用。

package main

import (
"io"
"log"
"strconv"
"strings"

"github.com/chzyer/readline"
)

// completer defines which commands the user can use
var completer = readline.NewPrefixCompleter()

// categories holding the initial default categories. The user can add categories.
var categories = []string{"Category A", "Category B", "Category C"}

var l *readline.Instance

func main() {

// Initialize config
config := readline.Config{
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
AutoComplete: completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",

HistorySearchFold: true,
}

var err error
// Create instance
l, err = readline.NewEx(&config)
if err != nil {
panic(err)
}
defer l.Close()

// Initial initialization of the completer
updateCompleter(categories)

log.SetOutput(l.Stderr())
// This loop watches for user input and process it
for {
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}

line = strings.TrimSpace(line)
// Checking which command the user typed
switch {
// Add new category
case strings.HasPrefix(line, "newCategory"):
// Remove the "newCategory " prefix (including space)
if len(line) <= 12 {
log.Println("newCategory <NameOfCategory>")
break
}
// Append everything that comes behind the command as the name of the new category
categories = append(categories, line[12:])
// Update the completer to make the new category available in the cmd
updateCompleter(categories)
// Program is closed when user types "exit"
case line == "exit":
goto exit
// Log all commands we don't know
default:
log.Println("Unknown command:", strconv.Quote(line))
}
}
exit:
}

// updateCompleter is updates the completer allowing to add new command during runtime. The completer is recreated
// and the configuration of the instance update.
func updateCompleter(categories []string) {

var items []readline.PrefixCompleterInterface

for _, category := range categories {
items = append(items, readline.PcItem(category))
}

completer = readline.NewPrefixCompleter(
readline.PcItem("newEntry",
items...,
),
readline.PcItem("newCategory"),
)

l.Config.AutoComplete = completer
}

关于go - 为 CLI 应用程序实现自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895260/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com