| 1 |
package patch |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"reflect" |
| 7 |
"slices" |
| 8 |
|
| 9 |
"git.sr.ht/~rjarry/aerc/commands" |
| 10 |
"git.sr.ht/~rjarry/go-opt/v2" |
| 11 |
) |
| 12 |
|
| 13 |
var subCommands map[string]commands.Command |
| 14 |
|
| 15 |
func register(cmd commands.Command) { |
| 16 |
if subCommands == nil { |
| 17 |
subCommands = make(map[string]commands.Command) |
| 18 |
} |
| 19 |
for _, alias := range cmd.Aliases() { |
| 20 |
if subCommands[alias] != nil { |
| 21 |
panic("duplicate sub command alias: " + alias) |
| 22 |
} |
| 23 |
subCommands[alias] = cmd |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
type Patch struct { |
| 28 |
SubCmd commands.Command `opt:":cmd:" action:"ParseSub" complete:"CompleteSubNames"` |
| 29 |
} |
| 30 |
|
| 31 |
func init() { |
| 32 |
commands.Register(Patch{}) |
| 33 |
} |
| 34 |
|
| 35 |
func (Patch) Description() string { |
| 36 |
return "Local patch management commands." |
| 37 |
} |
| 38 |
|
| 39 |
func (Patch) Context() commands.CommandContext { |
| 40 |
return commands.GLOBAL |
| 41 |
} |
| 42 |
|
| 43 |
func (Patch) Aliases() []string { |
| 44 |
return []string{"patch"} |
| 45 |
} |
| 46 |
|
| 47 |
func (p *Patch) ParseSub(arg string) error { |
| 48 |
cmd, ok := subCommands[arg] |
| 49 |
if ok { |
| 50 |
context := commands.CurrentContext() |
| 51 |
if cmd.Context()&context != 0 { |
| 52 |
// copy zeroed struct |
| 53 |
clone := reflect.New(reflect.TypeOf(cmd)).Interface() |
| 54 |
p.SubCmd = clone.(commands.Command) |
| 55 |
return nil |
| 56 |
} |
| 57 |
} |
| 58 |
return fmt.Errorf("%s unknown sub-command", arg) |
| 59 |
} |
| 60 |
|
| 61 |
func (*Patch) CompleteSubNames(arg string) []string { |
| 62 |
context := commands.CurrentContext() |
| 63 |
options := make([]string, 0, len(subCommands)) |
| 64 |
for alias, cmd := range subCommands { |
| 65 |
if cmd.Context()&context != 0 { |
| 66 |
options = append(options, alias+"\n"+cmd.Description()) |
| 67 |
} |
| 68 |
} |
| 69 |
slices.Sort(options) |
| 70 |
return commands.FilterList(options, arg, nil) |
| 71 |
} |
| 72 |
|
| 73 |
func (p *Patch) CompleteSubArgs(arg string) []string { |
| 74 |
if p.SubCmd == nil { |
| 75 |
return nil |
| 76 |
} |
| 77 |
// prepend arbitrary string to arg to work with sub-commands |
| 78 |
options, _ := commands.GetCompletions(p.SubCmd, opt.LexArgs("a "+arg)) |
| 79 |
completions := make([]string, 0, len(options)) |
| 80 |
for _, o := range options { |
| 81 |
completions = append(completions, o.Value) |
| 82 |
} |
| 83 |
return completions |
| 84 |
} |
| 85 |
|
| 86 |
func (p Patch) Execute(args []string) error { |
| 87 |
if p.SubCmd == nil { |
| 88 |
return errors.New("no subcommand found") |
| 89 |
} |
| 90 |
return p.SubCmd.Execute(args) |
| 91 |
} |