Debian Codegraph @

commands/patch/find.go

raw
1 package patch
2
3 import (
4 "errors"
5 "fmt"
6 "net/textproto"
7 "strings"
8
9 "git.sr.ht/~rjarry/aerc/app"
10 "git.sr.ht/~rjarry/aerc/commands"
11 "git.sr.ht/~rjarry/aerc/commands/account"
12 "git.sr.ht/~rjarry/aerc/lib/pama"
13 "git.sr.ht/~rjarry/aerc/lib/pama/models"
14 "git.sr.ht/~rjarry/go-opt/v2"
15 )
16
17 type Find struct {
18 Filter bool `opt:"-f" desc:"Filter message list instead of search."`
19 Commit []string `opt:"..." required:"true" complete:"Complete" desc:"Search for <commit-ish>."`
20 }
21
22 func init() {
23 register(Find{})
24 }
25
26 func (Find) Description() string {
27 return "Search for applied patches."
28 }
29
30 func (Find) Context() commands.CommandContext {
31 return commands.GLOBAL
32 }
33
34 func (Find) Aliases() []string {
35 return []string{"find"}
36 }
37
38 func (*Find) Complete(arg string) []string {
39 m := pama.New()
40 p, err := m.CurrentProject()
41 if err != nil {
42 return nil
43 }
44
45 options := make([]string, len(p.Commits))
46 for i, c := range p.Commits {
47 options[i] = fmt.Sprintf("%-6.6s %s", c.ID, c.Subject)
48 }
49
50 return commands.FilterList(options, arg, nil)
51 }
52
53 func (s Find) Execute(_ []string) error {
54 m := pama.New()
55 p, err := m.CurrentProject()
56 if err != nil {
57 return err
58 }
59
60 if len(s.Commit) == 0 {
61 return errors.New("missing commit hash")
62 }
63
64 lexed := opt.LexArgs(strings.TrimSpace(s.Commit[0]))
65
66 hash, err := lexed.ArgSafe(0)
67 if err != nil {
68 return err
69 }
70
71 if len(hash) < 4 {
72 return errors.New("Commit hash is too short.")
73 }
74
75 var c models.Commit
76 for _, commit := range p.Commits {
77 if strings.Contains(commit.ID, hash) {
78 c = commit
79 break
80 }
81 }
82 if c.ID == "" {
83 var err error
84 c, err = m.Find(hash, p)
85 if err != nil {
86 return err
87 }
88 }
89
90 // If Message-Id is provided, find it in store
91 if c.MessageId != "" {
92 if selectMessageId(c.MessageId) {
93 return nil
94 }
95 }
96
97 // Fallback to a search based on the subject line
98 args := []string{"search"}
99 if s.Filter {
100 args[0] = "filter"
101 }
102
103 headers := make(textproto.MIMEHeader)
104 args = append(args, fmt.Sprintf("-H Subject:%s", c.Subject))
105 headers.Add("Subject", c.Subject)
106
107 cmd := account.SearchFilter{
108 Headers: headers,
109 }
110
111 return cmd.Execute(args)
112 }
113
114 func selectMessageId(msgid string) bool {
115 acct := app.SelectedAccount()
116 if acct == nil {
117 return false
118 }
119 store := acct.Store()
120 if store == nil {
121 return false
122 }
123 for uid, msg := range store.Messages {
124 if msg == nil {
125 continue
126 }
127 if msg.RFC822Headers == nil {
128 continue
129 }
130 id, err := msg.RFC822Headers.MessageID()
131 if err != nil {
132 continue
133 }
134 if id == msgid {
135 store.Select(uid)
136 return true
137 }
138 }
139 return false
140 }