aboutsummaryrefslogtreecommitdiffstats
path: root/commands/compose/attach.go
blob: 99898d5d036a6e1560b563b07f95179374b40989 (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
package compose

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/logging"
	"git.sr.ht/~rjarry/aerc/widgets"
	"github.com/mitchellh/go-homedir"
)

type Attach struct{}

func init() {
	register(Attach{})
}

func (Attach) Aliases() []string {
	return []string{"attach"}
}

func (Attach) Complete(aerc *widgets.Aerc, args []string) []string {
	path := strings.Join(args, " ")
	return commands.CompletePath(path)
}

func (Attach) Execute(aerc *widgets.Aerc, args []string) error {
	if len(args) == 1 {
		return fmt.Errorf("Usage: :attach <path>")
	}

	path := strings.Join(args[1:], " ")
	path, err := homedir.Expand(path)
	if err != nil {
		logging.Errorf("failed to expand path '%s': %v", path, err)
		aerc.PushError(err.Error())
		return err
	}

	logging.Debugf("attaching %s", path)

	attachments, err := filepath.Glob(path)
	if err != nil && errors.Is(err, filepath.ErrBadPattern) {
		logging.Warnf("failed to parse as globbing pattern: %v", err)
		attachments = []string{path}
	}

	logging.Debugf("filenames: %v", attachments)

	composer, _ := aerc.SelectedTabContent().(*widgets.Composer)
	for _, attach := range attachments {
		logging.Debugf("attaching '%s'", attach)

		pathinfo, err := os.Stat(attach)
		if err != nil {
			logging.Errorf("failed to stat file: %v", err)
			aerc.PushError(err.Error())
			return err
		} else if pathinfo.IsDir() && len(attachments) == 1 {
			aerc.PushError("Attachment must be a file, not a directory")
			return nil
		}

		composer.AddAttachment(attach)
	}

	if len(attachments) == 1 {
		aerc.PushSuccess(fmt.Sprintf("Attached %s", path))
	} else {
		aerc.PushSuccess(fmt.Sprintf("Attached %d files", len(attachments)))
	}

	return nil
}