aboutsummaryrefslogtreecommitdiffstats
path: root/commands/compose/switch.go
blob: 2b6aadb5cfeaffda5e3d4e6987317e835f200cfc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package compose

import (
	"errors"
	"fmt"

	"git.sr.ht/~rjarry/aerc/widgets"
	"git.sr.ht/~sircmpwn/getopt"
)

type AccountSwitcher interface {
	SwitchAccount(*widgets.AccountView) error
}

type SwitchAccount struct{}

func init() {
	register(SwitchAccount{})
}

func (SwitchAccount) Aliases() []string {
	return []string{"switch-account"}
}

func (SwitchAccount) Complete(aerc *widgets.Aerc, args []string) []string {
	return aerc.AccountNames()
}

func (SwitchAccount) Execute(aerc *widgets.Aerc, args []string) error {
	opts, optind, err := getopt.Getopts(args, "np")
	if err != nil {
		return err
	}
	var next, prev bool
	for _, opt := range opts {
		switch opt.Option {
		case 'n':
			next = true
			prev = false
		case 'p':
			next = false
			prev = true
		}
	}
	posargs := args[optind:]
	// NOT ((prev || next) XOR (len(posargs) == 1))
	if (prev || next) == (len(posargs) == 1) {
		name := ""
		if acct := aerc.SelectedAccount(); acct != nil {
			name = fmt.Sprintf("Current account: %s. ", acct.Name())
		}
		return errors.New(name + "Usage: switch-account [-np] <account-name>")
	}

	switcher, ok := aerc.SelectedTabContent().(AccountSwitcher)
	if !ok {
		return errors.New("this tab cannot switch accounts")
	}

	var acct *widgets.AccountView

	switch {
	case prev:
		acct, err = aerc.PrevAccount()
	case next:
		acct, err = aerc.NextAccount()
	default:
		acct, err = aerc.Account(posargs[0])
	}
	if err != nil {
		return err
	}
	if err = switcher.SwitchAccount(acct); err != nil {
		return err
	}
	acct.UpdateStatus()

	return nil
}