-
Notifications
You must be signed in to change notification settings - Fork 7
/
hook.go
73 lines (58 loc) · 1.21 KB
/
hook.go
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
package main
import (
"fmt"
"net/mail"
"strings"
)
type Hooks []*Hook
func (hs Hooks) Find(addr string) (*Hook, bool) {
addr, err := normalizeAddress(addr)
if err != nil {
return nil, false
}
for _, hook := range hs {
if hook.includesAddr(addr) {
return hook, true
}
}
return nil, false
}
type Hook struct {
Emails []string `yaml:"emails"`
Hook string `yaml:"hook"`
}
func (h *Hook) includesAddr(addr string) bool {
for _, email := range h.Emails {
if addr == email {
return true
}
if strings.HasPrefix(email, "@") && strings.HasSuffix(addr, email) {
return true
}
if email == "@" {
return true
}
}
return false
}
func normalizeAddress(addr string) (string, error) {
email, err := mail.ParseAddress(addr)
if err != nil {
return "", err
}
local, domain, err := splitAddress(email.Address)
if err != nil {
return "", err
}
if parts := strings.SplitN(local, "+", 2); len(parts) > 1 {
local = parts[0]
}
return fmt.Sprintf("%s@%s", local, domain), nil
}
func splitAddress(addr string) (string, string, error) {
parts := strings.SplitN(addr, "@", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("Invalid address: %s", addr)
}
return parts[0], parts[1], nil
}