Debian Codegraph @

completer/completer.go

raw
1 package completer
2
3 import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "net/mail"
10 "os/exec"
11 "regexp"
12 "strings"
13 "syscall"
14
15 "git.sr.ht/~rjarry/aerc/lib/format"
16 "git.sr.ht/~rjarry/aerc/lib/log"
17 "git.sr.ht/~rjarry/go-opt/v2"
18 )
19
20 // A Completer is used to autocomplete text inputs based on the configured
21 // completion commands.
22 type Completer struct {
23 // AddressBookCmd is the command to run for completing email addresses. This
24 // command must output one completion on each line with fields separated by a
25 // tab character. The first field must be the address, and the second field,
26 // if present, the contact name. Only the email address field is required.
27 // The name field is optional. Additional fields are ignored.
28 AddressBookCmd string
29
30 errHandler func(error)
31 }
32
33 // A CompleteFunc accepts a string to be completed and returns a slice of
34 // completions candidates with a prefix to prepend to the chosen candidate
35 type CompleteFunc func(context.Context, string) ([]opt.Completion, string)
36
37 // New creates a new Completer with the specified address book command.
38 func New(addressBookCmd string, errHandler func(error)) *Completer {
39 return &Completer{
40 AddressBookCmd: addressBookCmd,
41 errHandler: errHandler,
42 }
43 }
44
45 // ForHeader returns a CompleteFunc appropriate for the specified mail header. In
46 // the case of To, From, etc., the completer will get completions from the
47 // configured address book command. For other headers, a noop completer will be
48 // returned. If errors arise during completion, the errHandler will be called.
49 func (c *Completer) ForHeader(h string) CompleteFunc {
50 if isAddressHeader(h) {
51 if c.AddressBookCmd == "" {
52 return nil
53 }
54 // wrap completeAddress in an error handler
55 return func(ctx context.Context, s string) ([]opt.Completion, string) {
56 completions, prefix, err := c.completeAddress(ctx, s)
57 if err != nil {
58 c.handleErr(err)
59 return []opt.Completion{}, ""
60 }
61 return completions, prefix
62 }
63 }
64 return nil
65 }
66
67 // isAddressHeader determines whether the address completer should be used for
68 // header h.
69 func isAddressHeader(h string) bool {
70 switch strings.ToLower(h) {
71 case "to", "from", "cc", "bcc", "reply-to":
72 return true
73 }
74 return false
75 }
76
77 const maxCompletionLines = 100
78
79 var tooManyLines = fmt.Errorf("returned more than %d lines", maxCompletionLines)
80
81 // completeAddress uses the configured address book completion command to fetch
82 // completions for the specified string, returning a slice of completions and
83 // a prefix to be prepended to the selected completion, or an error.
84 func (c *Completer) completeAddress(ctx context.Context, s string) ([]opt.Completion, string, error) {
85 prefix, candidate := c.parseAddress(s)
86 cmd, err := c.getAddressCmd(ctx, candidate)
87 if err != nil {
88 return nil, "", err
89 }
90 stdout, err := cmd.StdoutPipe()
91 if err != nil {
92 return nil, "", fmt.Errorf("stdout: %w", err)
93 }
94 stderr, err := cmd.StderrPipe()
95 if err != nil {
96 return nil, "", fmt.Errorf("stderr: %w", err)
97 }
98 // reset the process group id to allow killing all its children
99 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
100 if err := cmd.Start(); err != nil {
101 return nil, "", fmt.Errorf("cmd start: %w", err)
102 }
103 // Wait returns an error if the exit status != 0, which some completion
104 // programs will do to signal no matches. We don't want to spam the user with
105 // spurious error messages, so we'll ignore any errors that arise at this
106 // point.
107 defer cmd.Wait() //nolint:errcheck // see above
108
109 completions, err := readCompletions(stdout)
110 if err != nil {
111 // make sure to kill the process *and* all its children
112 //nolint:errcheck // who cares?
113 syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
114 log.Warnf("command %s killed: %s", cmd, err)
115 }
116 if err != nil && !errors.Is(err, tooManyLines) {
117 buf, _ := io.ReadAll(stderr)
118 msg := strings.TrimSpace(string(buf))
119 if msg != "" {
120 msg = ": " + msg
121 }
122 return nil, "", fmt.Errorf("read completions%s: %w", msg, err)
123 }
124
125 return completions, prefix, nil
126 }
127
128 // parseAddress will break an address header into a prefix (containing
129 // the already valid addresses) and an input for completion
130 func (c *Completer) parseAddress(s string) (string, string) {
131 pattern := regexp.MustCompile(`^(.*),\s+([^,]*)$`)
132 matches := pattern.FindStringSubmatch(s)
133 if matches == nil {
134 return "", s
135 }
136 return matches[1] + ", ", matches[2]
137 }
138
139 // getAddressCmd constructs an exec.Cmd based on the configured command and
140 // specified query.
141 func (c *Completer) getAddressCmd(ctx context.Context, s string) (*exec.Cmd, error) {
142 if strings.TrimSpace(c.AddressBookCmd) == "" {
143 return nil, fmt.Errorf("no command configured")
144 }
145 queryCmd := strings.ReplaceAll(c.AddressBookCmd, "%s", s)
146 return exec.CommandContext(ctx, "sh", "-c", queryCmd), nil
147 }
148
149 // readCompletions reads a slice of completions from r line by line. Each line
150 // must consist of tab-delimited fields. Only the first field (the email
151 // address field) is required, the second field (the contact name) is optional,
152 // and subsequent fields are ignored.
153 func readCompletions(r io.Reader) ([]opt.Completion, error) {
154 buf := bufio.NewReader(r)
155 var completions []opt.Completion
156 for range maxCompletionLines {
157 line, err := buf.ReadString('\n')
158 if errors.Is(err, io.EOF) {
159 return completions, nil
160 } else if err != nil {
161 return nil, err
162 }
163 if strings.TrimSpace(line) == "" {
164 // skip empty lines
165 continue
166 }
167 parts := strings.SplitN(line, "\t", 3)
168 addr, err := mail.ParseAddress(strings.TrimSpace(parts[0]))
169 if err != nil {
170 log.Warnf("line %d: %#v: could not parse address: %v",
171 line, err)
172 continue
173 }
174 if len(parts) > 1 {
175 addr.Name = strings.TrimSpace(parts[1])
176 }
177 completions = append(completions, opt.Completion{
178 Value: format.AddressForHumans(addr),
179 })
180 }
181 return completions, tooManyLines
182 }
183
184 func (c *Completer) handleErr(err error) {
185 if c.errHandler != nil {
186 c.errHandler(err)
187 }
188 }