Debian Codegraph @

commands/compose/detach.go

raw
1 package compose
2
3 import (
4 "fmt"
5 "path/filepath"
6
7 "git.sr.ht/~rjarry/aerc/app"
8 "git.sr.ht/~rjarry/aerc/commands"
9 "git.sr.ht/~rjarry/aerc/lib/log"
10 "github.com/pkg/errors"
11 )
12
13 type Detach struct {
14 Path string `opt:"path" required:"false" complete:"CompletePath" desc:"Attachment file path."`
15 }
16
17 func init() {
18 commands.Register(Detach{})
19 }
20
21 func (Detach) Description() string {
22 return "Detach the file with the given path from the composed email."
23 }
24
25 func (Detach) Context() commands.CommandContext {
26 return commands.COMPOSE_EDIT | commands.COMPOSE_REVIEW
27 }
28
29 func (Detach) Aliases() []string {
30 return []string{"detach"}
31 }
32
33 func (*Detach) CompletePath(arg string) []string {
34 composer, _ := app.SelectedTabContent().(*app.Composer)
35 return commands.FilterList(composer.GetAttachments(), arg, nil)
36 }
37
38 func (d Detach) Execute(args []string) error {
39 composer, _ := app.SelectedTabContent().(*app.Composer)
40
41 if d.Path == "" {
42 // if no attachment is specified, delete the first in the list
43 atts := composer.GetAttachments()
44 if len(atts) > 0 {
45 d.Path = atts[0]
46 } else {
47 return fmt.Errorf("No attachments to delete")
48 }
49 }
50
51 return d.removePath(d.Path)
52 }
53
54 func (d Detach) removePath(path string) error {
55 composer, _ := app.SelectedTabContent().(*app.Composer)
56
57 // If we don't get an error here, the path was not a pattern.
58 if err := composer.DeleteAttachment(path); err == nil {
59 log.Debugf("detaching '%s'", path)
60 app.PushSuccess(fmt.Sprintf("Detached %s", path))
61
62 return nil
63 }
64
65 currentAttachments := composer.GetAttachments()
66 detached := make([]string, 0, len(currentAttachments))
67 for _, a := range currentAttachments {
68 // Don't use filepath.Glob like :attach does. Not all files
69 // that match the glob are already attached to the message.
70 matches, err := filepath.Match(path, a)
71 if err != nil && errors.Is(err, filepath.ErrBadPattern) {
72 log.Warnf("failed to parse as globbing pattern: %v", err)
73 return err
74 }
75
76 if matches {
77 log.Debugf("detaching '%s'", a)
78 if err := composer.DeleteAttachment(a); err != nil {
79 return err
80 }
81
82 detached = append(detached, a)
83 }
84 }
85
86 if len(detached) == 1 {
87 app.PushSuccess(fmt.Sprintf("Detached %s", detached[0]))
88 } else {
89 app.PushSuccess(fmt.Sprintf("Detached %d files", len(detached)))
90 }
91
92 return nil
93 }