Debian Codegraph @

config/url_config.go

raw symbols SCIP
1 package config
2
3 import (
4 "fmt"
5 "net/url"
6 "regexp"
7 "strings"
8 )
9
10 type URLConfig struct {
11 git Environment
12 }
13
14 func NewURLConfig(git Environment) *URLConfig {
15 if git == nil {
16 git = EnvironmentOf(make(mapFetcher))
17 }
18
19 return &URLConfig{
20 git: git,
21 }
22 }
23
24 // Get retrieves a `http.{url}.{key}` for the given key and urls, following the
25 // rules in https://git-scm.com/docs/git-config#Documentation/git-config.txt-httplturlgt.
26 // The value for `http.{key}` is returned as a fallback if no config keys are
27 // set for the given urls.
28 func (c *URLConfig) Get(prefix, rawurl, key string) (string, bool) {
29 if c == nil {
30 return "", false
31 }
32
33 key = strings.ToLower(key)
34 prefix = strings.ToLower(prefix)
35 if v := c.getAll(prefix, rawurl, key); len(v) > 0 {
36 return v[len(v)-1], true
37 }
38 return c.git.Get(strings.Join([]string{prefix, key}, "."))
39 }
40
41 func (c *URLConfig) GetAll(prefix, rawurl, key string) []string {
42 if c == nil {
43 return nil
44 }
45
46 key = strings.ToLower(key)
47 prefix = strings.ToLower(prefix)
48 if v := c.getAll(prefix, rawurl, key); len(v) > 0 {
49 return v
50 }
51 return c.git.GetAll(strings.Join([]string{prefix, key}, "."))
52 }
53
54 func (c *URLConfig) Bool(prefix, rawurl, key string, def bool) bool {
55 s, _ := c.Get(prefix, rawurl, key)
56 return Bool(s, def)
57 }
58
59 func (c *URLConfig) getAll(prefix, rawurl, key string) []string {
60 type urlMatch struct {
61 key string // The full configuration key
62 hostScore int // A score indicating the strength of the host match
63 pathScore int // A score indicating the strength of the path match
64 userMatch int // Whether we matched on a username. 1 for yes, else 0
65 }
66
67 searchURL, err := url.Parse(rawurl)
68 if err != nil {
69 return nil
70 }
71
72 config := c.git.All()
73
74 re := regexp.MustCompile(fmt.Sprintf(`\A%s\.(\S+)\.%s\z`, prefix, key))
75
76 bestMatch := urlMatch{
77 key: "",
78 hostScore: 0,
79 pathScore: 0,
80 userMatch: 0,
81 }
82
83 for k := range config {
84 // Ensure we're examining the correct type of key and parse out the URL
85 matches := re.FindStringSubmatch(k)
86 if matches == nil {
87 continue
88 }
89 configURL, err := url.Parse(matches[1])
90 if err != nil {
91 continue
92 }
93
94 match := urlMatch{
95 key: k,
96 }
97
98 // Rule #1: Scheme must match exactly
99 if searchURL.Scheme != configURL.Scheme {
100 continue
101 }
102
103 // Rule #2: Hosts must match exactly, or through wildcards. More exact
104 // matches should take priority over wildcard matches
105 match.hostScore = compareHosts(searchURL.Hostname(), configURL.Hostname())
106
107 if match.hostScore == 0 {
108 continue
109 }
110
111 if match.hostScore < bestMatch.hostScore {
112 continue
113 }
114
115 // Rule #3: Port Number must match exactly
116 if portForURL(searchURL) != portForURL(configURL) {
117 continue
118 }
119
120 // Rule #4: Configured path must match exactly, or as a prefix of
121 // slash-delimited path elements
122 match.pathScore = comparePaths(searchURL.Path, configURL.Path)
123
124 if match.pathScore == 0 {
125 continue
126 }
127
128 // Rule #5: Username must match exactly if present in the config.
129 // If not present, config matches on any username but with lower
130 // priority than an exact username match.
131 if configURL.User != nil {
132 if searchURL.User == nil {
133 continue
134 }
135
136 if searchURL.User.Username() != configURL.User.Username() {
137 continue
138 }
139
140 match.userMatch = 1
141 }
142
143 // Now combine our various scores to determine if we have found a best
144 // match. Host score > path score > user score
145 if match.hostScore > bestMatch.hostScore {
146 bestMatch = match
147 continue
148 }
149
150 if match.pathScore > bestMatch.pathScore {
151 bestMatch = match
152 continue
153 }
154
155 if match.pathScore == bestMatch.pathScore && match.userMatch > bestMatch.userMatch {
156 bestMatch = match
157 continue
158 }
159 }
160
161 if bestMatch.key == "" {
162 return nil
163 }
164
165 return c.git.GetAll(bestMatch.key)
166 }
167
168 func portForURL(u *url.URL) string {
169 port := u.Port()
170 if port != "" {
171 return port
172 }
173 switch u.Scheme {
174 case "http":
175 return "80"
176 case "https":
177 return "443"
178 case "ssh":
179 return "22"
180 default:
181 return ""
182 }
183 }
184
185 // compareHosts compares a hostname with a configuration hostname to determine
186 // a match. It returns an integer indicating the strength of the match, or 0 if
187 // the two hostnames did not match.
188 func compareHosts(searchHostname, configHostname string) int {
189 searchHost := strings.Split(searchHostname, ".")
190 configHost := strings.Split(configHostname, ".")
191
192 if len(searchHost) != len(configHost) {
193 return 0
194 }
195
196 score := len(searchHost) + 1
197
198 for i, subdomain := range searchHost {
199 if configHost[i] == "*" {
200 score--
201 continue
202 }
203
204 if subdomain != configHost[i] {
205 return 0
206 }
207 }
208
209 return score
210 }
211
212 // comparePaths compares a path with a configuration path to determine a match.
213 // It returns an integer indicating the strength of the match, or 0 if the two
214 // paths did not match.
215 func comparePaths(rawSearchPath, rawConfigPath string) int {
216 f := func(c rune) bool {
217 return c == '/'
218 }
219 searchPath := strings.FieldsFunc(rawSearchPath, f)
220 configPath := strings.FieldsFunc(rawConfigPath, f)
221
222 if len(searchPath) < len(configPath) {
223 return 0
224 }
225
226 // Start with a base score of 1, so we return something above 0 for a
227 // zero-length path
228 score := 1
229
230 for i, element := range configPath {
231 searchElement := searchPath[i]
232
233 if element == searchElement {
234 score += 2
235 continue
236 }
237
238 if isDefaultLFSUrl(searchElement, searchPath, i+1) {
239 if searchElement[0:len(searchElement)-4] == element {
240 // Since we matched without the `.git` prefix, only add one
241 // point to the score instead of 2
242 score++
243 continue
244 }
245 }
246
247 return 0
248 }
249
250 return score
251 }
252
253 func (c *URLConfig) hostsAndPaths(rawurl string) (hosts, paths []string) {
254 u, err := url.Parse(rawurl)
255 if err != nil {
256 return nil, nil
257 }
258
259 return c.hosts(u), c.paths(u.Path)
260 }
261
262 func (c *URLConfig) hosts(u *url.URL) []string {
263 hosts := make([]string, 0, 1)
264
265 if u.User != nil {
266 hosts = append(hosts, fmt.Sprintf("%s://%s@%s", u.Scheme, u.User.Username(), u.Host))
267 }
268 hosts = append(hosts, fmt.Sprintf("%s://%s", u.Scheme, u.Host))
269
270 return hosts
271 }
272
273 func (c *URLConfig) paths(path string) []string {
274 pLen := len(path)
275 if pLen <= 2 {
276 return nil
277 }
278
279 end := pLen
280 if strings.HasSuffix(path, slash) {
281 end--
282 }
283 return strings.Split(path[1:end], slash)
284 }
285
286 const (
287 gitExt = ".git"
288 infoPart = "info"
289 lfsPart = "lfs"
290 slash = "/"
291 )
292
293 func isDefaultLFSUrl(path string, parts []string, index int) bool {
294 if len(path) < 5 {
295 return false // shorter than ".git"
296 }
297
298 if !strings.HasSuffix(path, gitExt) {
299 return false
300 }
301
302 if index > len(parts)-2 {
303 return false
304 }
305
306 return parts[index] == infoPart && parts[index+1] == lfsPart
307 }