aerc/commands/commands.go

51 lines
968 B
Go
Raw Normal View History

2019-03-11 01:15:24 +00:00
package commands
import (
"errors"
2019-03-11 01:23:22 +00:00
"github.com/google/shlex"
2019-03-11 01:15:24 +00:00
"git.sr.ht/~sircmpwn/aerc2/widgets"
)
2019-03-11 01:23:22 +00:00
type AercCommand func(aerc *widgets.Aerc, args []string) error
2019-03-11 01:15:24 +00:00
2019-03-21 20:30:23 +00:00
type Commands map[string]AercCommand
2019-03-11 01:15:24 +00:00
2019-03-21 20:30:23 +00: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 01:15:24 +00:00
}
2019-03-21 20:30:23 +00:00
func (cmds *Commands) ExecuteCommand(aerc *widgets.Aerc, cmd string) error {
2019-03-11 01:23:22 +00:00
args, err := shlex.Split(cmd)
if err != nil {
return err
}
if len(args) == 0 {
return errors.New("Expected a command.")
}
2019-03-21 20:30:23 +00:00
if fn, ok := cmds.dict()[args[0]]; ok {
2019-03-11 01:23:22 +00:00
return fn(aerc, args)
2019-03-11 01:15:24 +00:00
}
2019-03-21 20:30:23 +00:00
return NoSuchCommand(args[0])
2019-03-11 01:15:24 +00:00
}