forked from andybalholm/redwood
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule.go
132 lines (124 loc) · 2.48 KB
/
rule.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"errors"
"fmt"
"strings"
)
// A rule is a URL fragment, URL regular expression, or content phrase
// that will be matched against a page in the process of determining its score.
type rule struct {
t ruleType
content string
}
type ruleType int
const (
defaultRule ruleType = iota
urlMatch
urlRegex
hostRegex
domainRegex
pathRegex
queryRegex
contentPhrase
imageHash
)
func (r rule) String() string {
switch r.t {
case urlMatch:
return r.content
case urlRegex, hostRegex, domainRegex, pathRegex, queryRegex:
suffix := ""
switch r.t {
case hostRegex:
suffix = "h"
case pathRegex:
suffix = "p"
case queryRegex:
suffix = "q"
case domainRegex:
suffix = "d"
}
return "/" + r.content + "/" + suffix
case contentPhrase:
return "<" + r.content + ">"
case imageHash:
return "%" + r.content
}
panic(fmt.Errorf("invalid rule type: %d", r.t))
}
// parseRule parses a rule from the beginning of s, returning the rule
// and any remaining unconsumed characters from s.
func parseRule(s string) (r rule, leftover string, err error) {
s = strings.TrimLeft(s, " \t\r\n\f")
if s == "" {
return rule{}, "", errors.New("blank rule")
}
switch s[0] {
case '/':
r.t = urlRegex
space := strings.Index(s, " ")
var slash int
if space == -1 {
slash = strings.LastIndex(s, "/")
} else {
slash = strings.LastIndex(s[:space], "/")
}
if slash == 0 {
return rule{}, s, errors.New("unmatched slash")
}
r.content = s[1:slash]
s = s[slash+1:]
if s != "" {
switch s[0] {
case 'h':
r.t = hostRegex
s = s[1:]
case 'p':
r.t = pathRegex
s = s[1:]
case 'q':
r.t = queryRegex
s = s[1:]
case 'd':
r.t = domainRegex
s = s[1:]
}
}
case '<':
r.t = contentPhrase
bracket := strings.LastIndex(s, ">")
if bracket == -1 {
return rule{}, s, errors.New("unmatched '<'")
}
r.content = wordString(s[1:bracket])
s = s[bracket+1:]
case '%':
r.t = imageHash
space := strings.Index(s, " ")
if space == -1 {
r.content = s[1:]
s = ""
} else {
r.content = s[1:space]
s = s[space:]
}
r.content = strings.ToLower(r.content)
default:
r.t = urlMatch
space := strings.Index(s, " ")
if space == -1 {
r.content = strings.ToLower(s)
s = ""
} else {
r.content = strings.ToLower(s[:space])
s = s[space:]
}
if r.content == "default" {
r.t = defaultRule
}
if strings.HasSuffix(r.content, "/") {
r.content = r.content[:len(r.content)-1]
}
}
return r, s, nil
}