2019-03-11 02:15:24 +01:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
2019-03-11 02:23:22 +01:00
|
|
|
"github.com/google/shlex"
|
|
|
|
|
2019-05-18 02:57:10 +02:00
|
|
|
"git.sr.ht/~sircmpwn/aerc/widgets"
|
2019-03-11 02:15:24 +01:00
|
|
|
)
|
|
|
|
|
2019-03-11 02:23:22 +01:00
|
|
|
type AercCommand func(aerc *widgets.Aerc, args []string) error
|
2019-03-11 02:15:24 +01:00
|
|
|
|
2019-03-21 21:30:23 +01:00
|
|
|
type Commands map[string]AercCommand
|
2019-03-11 02:15:24 +01:00
|
|
|
|
2019-03-21 21:30:23 +01:00
|
|
|
func NewCommands() *Commands {
|
|
|
|
cmds := Commands(make(map[string]AercCommand))
|
|
|
|
return &cmds
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cmds *Commands) dict() map[string]AercCommand {
|
|
|
|
return map[string]AercCommand(*cmds)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cmds *Commands) Register(name string, cmd AercCommand) {
|
|
|
|
cmds.dict()[name] = cmd
|
|
|
|
}
|
|
|
|
|
|
|
|
type NoSuchCommand string
|
|
|
|
|
|
|
|
func (err NoSuchCommand) Error() string {
|
|
|
|
return "Unknown command " + string(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
type CommandSource interface {
|
|
|
|
Commands() *Commands
|
2019-03-11 02:15:24 +01:00
|
|
|
}
|
|
|
|
|
2019-03-21 21:30:23 +01:00
|
|
|
func (cmds *Commands) ExecuteCommand(aerc *widgets.Aerc, cmd string) error {
|
2019-03-11 02:23:22 +01:00
|
|
|
args, err := shlex.Split(cmd)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(args) == 0 {
|
|
|
|
return errors.New("Expected a command.")
|
|
|
|
}
|
2019-03-21 21:30:23 +01:00
|
|
|
if fn, ok := cmds.dict()[args[0]]; ok {
|
2019-03-11 02:23:22 +01:00
|
|
|
return fn(aerc, args)
|
2019-03-11 02:15:24 +01:00
|
|
|
}
|
2019-03-21 21:30:23 +01:00
|
|
|
return NoSuchCommand(args[0])
|
2019-03-11 02:15:24 +01:00
|
|
|
}
|