aboutsummaryrefslogtreecommitdiffstats
path: root/commands/account/rmdir.go
blob: 3b109a678c12434923e9070617efdc55dbb616af (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package account

import (
	"errors"
	"time"

	"git.sr.ht/~sircmpwn/getopt"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/worker/types"
)

type RemoveDir struct{}

func init() {
	register(RemoveDir{})
}

func (RemoveDir) Aliases() []string {
	return []string{"rmdir"}
}

func (RemoveDir) Complete(args []string) []string {
	return nil
}

func (RemoveDir) Execute(args []string) error {
	acct := app.SelectedAccount()
	if acct == nil {
		return errors.New("No account selected")
	}

	force := false

	opts, optind, err := getopt.Getopts(args, "f")
	if err != nil {
		return err
	}
	for _, opt := range opts {
		if opt.Option == 'f' {
			force = true
		}
	}

	if len(args) != optind {
		return errors.New("Usage: rmdir [-f]")
	}

	// Check for any messages in the directory.
	if !acct.Messages().Empty() && !force {
		return errors.New("Refusing to remove non-empty directory; use -f")
	}

	curDir := acct.SelectedDirectory()
	var newDir string
	dirFound := false

	if oldDir, ok := history[acct.Name()]; ok {
		if oldDir != curDir {
			newDir = oldDir
			dirFound = true
		}
	}

	if !dirFound {
		for _, dir := range acct.Directories().List() {
			if dir != curDir {
				newDir = dir
				dirFound = true
				break
			}
		}
	}

	if !dirFound {
		return errors.New("No directory to move to afterwards!")
	}

	acct.Directories().Select(newDir)

	acct.Worker().PostAction(&types.RemoveDirectory{
		Directory: curDir,
		Quiet:     force,
	}, func(msg types.WorkerMessage) {
		switch msg := msg.(type) {
		case *types.Done:
			app.PushStatus("Directory removed.", 10*time.Second)
		case *types.Error:
			app.PushError(msg.Error.Error())
		case *types.Unsupported:
			app.PushError(":rmdir is not supported by the backend.")
		}
	})

	return nil
}