-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglob.go
More file actions
205 lines (193 loc) · 5.41 KB
/
Copy pathglob.go
File metadata and controls
205 lines (193 loc) · 5.41 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package patchright
import (
"net/url"
"regexp"
"strconv"
"strings"
)
var escapedChars = map[rune]bool{
'$': true,
'^': true,
'+': true,
'.': true,
'*': true,
'(': true,
')': true,
'|': true,
'\\': true,
'?': true,
'{': true,
'}': true,
'[': true,
']': true,
}
func globMustToRegex(glob string) *regexp.Regexp {
tokens := []string{"^"}
inGroup := false
// Iterate by rune (not byte) so multibyte UTF-8 characters survive intact,
// matching upstream which iterates UTF-16 code units.
runes := []rune(glob)
for i := 0; i < len(runes); i++ {
c := runes[i]
if c == '\\' && i+1 < len(runes) {
char := runes[i+1]
if _, ok := escapedChars[char]; ok {
tokens = append(tokens, "\\"+string(char))
} else {
tokens = append(tokens, string(char))
}
i++
} else if c == '*' {
charBefore := rune(0)
if i > 0 {
charBefore = runes[i-1]
}
starCount := 1
for i+1 < len(runes) && runes[i+1] == '*' {
starCount++
i++
}
if starCount > 1 {
charAfter := rune(0)
if i+1 < len(runes) {
charAfter = runes[i+1]
}
// Match either /..something../ or /.
if charAfter == '/' {
if charBefore == '/' {
tokens = append(tokens, "((.+/)|)")
} else {
tokens = append(tokens, "(.*/)")
}
i++
} else {
tokens = append(tokens, "(.*)")
}
} else {
tokens = append(tokens, "([^/]*)")
}
} else {
switch c {
case '{':
inGroup = true
tokens = append(tokens, "(")
case '}':
inGroup = false
tokens = append(tokens, ")")
case ',':
if inGroup {
tokens = append(tokens, "|")
} else {
tokens = append(tokens, "\\"+string(c))
}
default:
if _, ok := escapedChars[c]; ok {
tokens = append(tokens, "\\"+string(c))
} else {
tokens = append(tokens, string(c))
}
}
}
}
tokens = append(tokens, "$")
return regexp.MustCompile(strings.Join(tokens, ""))
}
func resolveGlobToRegex(baseURL *string, glob string, isWebSocketUrl bool) *regexp.Regexp {
if isWebSocketUrl {
baseURL = toWebSocketBaseURL(baseURL)
}
glob = resolveGlobBase(baseURL, glob)
return globMustToRegex(glob)
}
func resolveGlobBase(baseURL *string, match string) string {
if strings.HasPrefix(match, "*") {
return match
}
tokenMap := make(map[string]string)
mapToken := func(original string, replacement string) string {
if len(original) == 0 {
return ""
}
tokenMap[replacement] = original
return replacement
}
// Escaped `\\?` behaves the same as `?` in our glob patterns.
match = strings.ReplaceAll(match, `\\?`, "?")
// Special case about:/data:/chrome:/edge:/file: URLs as they are not relative to baseURL.
if strings.HasPrefix(match, "about:") || strings.HasPrefix(match, "data:") ||
strings.HasPrefix(match, "chrome:") || strings.HasPrefix(match, "edge:") ||
strings.HasPrefix(match, "file:") {
return match
}
// Glob symbols may be escaped in the URL and some of them such as ? affect resolution,
// so we replace them with safe components first.
relativePath := strings.Split(match, "/")
for i, token := range relativePath {
if token == "." || token == ".." || token == "" {
continue
}
// Handle special case of http*://, note that the new schema has to be
// a web schema so that slashes are properly inserted after domain.
if i == 0 && strings.HasSuffix(token, ":") {
// Replace any pattern with http:; preserve an explicit schema as-is as
// it may affect trailing slashes after the domain.
if strings.ContainsAny(token, "*{") {
relativePath[i] = mapToken(token, "http:")
}
} else {
questionIndex := strings.Index(token, "?")
if questionIndex == -1 {
relativePath[i] = mapToken(token, "$_"+strconv.Itoa(i)+"_$")
} else {
newPrefix := mapToken(token[:questionIndex], "$_"+strconv.Itoa(i)+"_$")
newSuffix := mapToken(token[questionIndex:], "?$_"+strconv.Itoa(i)+"_$")
relativePath[i] = newPrefix + newSuffix
}
}
}
resolved, origin := constructURLBasedOnBaseURL(baseURL, strings.Join(relativePath, "/"))
for token, original := range tokenMap {
// Scheme and domain are case-insensitive: when a token resolves inside the
// URL origin, restore it lowercased so a mixed-case host still matches the
// (always-lowercased) request URL. Matches upstream resolveBaseURL.
replacement := original
if origin != "" && strings.Contains(origin, token) {
replacement = strings.ToLower(original)
}
resolved = strings.Replace(resolved, token, replacement, 1)
}
return resolved
}
// constructURLBasedOnBaseURL resolves givenURL against baseURL (new URL(given,
// base) semantics) and also returns the resolved URL's origin (scheme://host[:port]),
// which is case-insensitive.
func constructURLBasedOnBaseURL(baseURL *string, givenURL string) (string, string) {
u, err := url.Parse(givenURL)
if err != nil {
return givenURL, ""
}
if baseURL != nil {
base, err := url.Parse(*baseURL)
if err != nil {
return givenURL, ""
}
u = base.ResolveReference(u)
}
if u.Path == "" { // In Node.js, new URL('http://localhost') returns 'http://localhost/'.
u.Path = "/"
}
origin := ""
if u.Scheme != "" && u.Host != "" {
origin = u.Scheme + "://" + u.Host
}
return u.String(), origin
}
func toWebSocketBaseURL(baseURL *string) *string {
if baseURL == nil {
return nil
}
// Allow http(s) baseURL to match ws(s) urls.
re := regexp.MustCompile(`(?m)^http(s?://)`)
wsBaseURL := re.ReplaceAllString(*baseURL, "ws$1")
return &wsBaseURL
}