mirror of
https://git.sr.ht/~rjarry/aerc
synced 2025-12-23 12:14:14 +01:00
Register all commands with the same function and store them in the same map. Use bit flags to determine in which contexts each command should be available. Remove duplicate commands now that the same command can be exposed in multiple contexts. Refactor API to allow executing commands from other commands without import cycles. Signed-off-by: Robin Jarry <robin@jarry.cc> Tested-by: Bence Ferdinandy <bence@ferdinandy.com> Tested-by: Johannes Thyssen Tishman <johannes@thyssentishman.com>
81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package patch
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"git.sr.ht/~rjarry/aerc/commands"
|
|
"git.sr.ht/~rjarry/go-opt"
|
|
)
|
|
|
|
var subCommands map[string]commands.Command
|
|
|
|
func register(cmd commands.Command) {
|
|
if subCommands == nil {
|
|
subCommands = make(map[string]commands.Command)
|
|
}
|
|
for _, alias := range cmd.Aliases() {
|
|
if subCommands[alias] != nil {
|
|
panic("duplicate sub command alias: " + alias)
|
|
}
|
|
subCommands[alias] = cmd
|
|
}
|
|
}
|
|
|
|
type Patch struct {
|
|
SubCmd commands.Command `opt:"command" action:"ParseSub" complete:"CompleteSubNames"`
|
|
Args string `opt:"..." required:"false" complete:"CompleteSubArgs"`
|
|
}
|
|
|
|
func init() {
|
|
commands.Register(Patch{})
|
|
}
|
|
|
|
func (Patch) Context() commands.CommandContext {
|
|
return commands.GLOBAL
|
|
}
|
|
|
|
func (Patch) Aliases() []string {
|
|
return []string{"patch"}
|
|
}
|
|
|
|
func (p *Patch) ParseSub(arg string) error {
|
|
cmd, ok := subCommands[arg]
|
|
if ok {
|
|
context := commands.CurrentContext()
|
|
if cmd.Context()&context != 0 {
|
|
p.SubCmd = cmd
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("%s unknown sub-command", arg)
|
|
}
|
|
|
|
func (*Patch) CompleteSubNames(arg string) []string {
|
|
context := commands.CurrentContext()
|
|
options := make([]string, 0, len(subCommands))
|
|
for alias, cmd := range subCommands {
|
|
if cmd.Context()&context != 0 {
|
|
options = append(options, alias)
|
|
}
|
|
}
|
|
return commands.FilterList(options, arg, commands.QuoteSpace)
|
|
}
|
|
|
|
func (p *Patch) CompleteSubArgs(arg string) []string {
|
|
if p.SubCmd == nil {
|
|
return nil
|
|
}
|
|
// prepend arbitrary string to arg to work with sub-commands
|
|
options, _ := commands.GetCompletions(p.SubCmd, opt.LexArgs("a "+arg))
|
|
return options
|
|
}
|
|
|
|
func (p Patch) Execute(args []string) error {
|
|
if p.SubCmd == nil {
|
|
return errors.New("no subcommand found")
|
|
}
|
|
a := opt.QuoteArgs(args[1:]...)
|
|
return commands.ExecuteCommand(p.SubCmd, a.String())
|
|
}
|