llamachat/commands.go

59 lines
1.1 KiB
Go

package main
import (
"github.com/elk-language/go-prompt"
pstrings "github.com/elk-language/go-prompt/strings"
"os"
"strings"
)
type Action func(args []string)
type CommandArg struct {
Name string
Action Action
Help string
}
func command(name string, action Action) CommandArg {
return CommandArg{
Name: "/" + name,
Action: action,
}
}
func (arg CommandArg) withHelp(help string) CommandArg {
arg.Help = help
return arg
}
func Completer(d prompt.Document) ([]prompt.Suggest, pstrings.RuneNumber, pstrings.RuneNumber) {
endIndex := d.CurrentRuneIndex()
w := d.TextBeforeCursor()
startIndex := endIndex - pstrings.RuneCount([]byte(w))
if !strings.HasPrefix(w, "/") {
return nil, startIndex, endIndex
}
var s []prompt.Suggest
for _, cmd := range Commands {
if strings.HasPrefix(cmd.Name, w) {
s = append(s, prompt.Suggest{
Text: cmd.Name,
Description: cmd.Help,
})
}
}
return prompt.FilterHasPrefix(s, w, true), startIndex, endIndex
}
var Commands = []CommandArg{
command("quit", cmdQuit).withHelp("Quit the program"),
}
func cmdQuit(args []string) {
os.Exit(0)
}