Debian Codegraph @

config/url.go

raw
1 package config
2
3 import (
4 "errors"
5 "strings"
6
7 format "github.com/go-git/go-git/v5/plumbing/format/config"
8 )
9
10 var (
11 errURLEmptyInsteadOf = errors.New("url config: empty insteadOf")
12 )
13
14 // Url defines Url rewrite rules
15 type URL struct {
16 // Name new base url
17 Name string
18 // Any URL that starts with this value will be rewritten to start, instead, with <base>.
19 // When more than one insteadOf strings match a given URL, the longest match is used.
20 InsteadOf string
21
22 // raw representation of the subsection, filled by marshal or unmarshal are
23 // called.
24 raw *format.Subsection
25 }
26
27 // Validate validates fields of branch
28 func (b *URL) Validate() error {
29 if b.InsteadOf == "" {
30 return errURLEmptyInsteadOf
31 }
32
33 return nil
34 }
35
36 const (
37 insteadOfKey = "insteadOf"
38 )
39
40 func (u *URL) unmarshal(s *format.Subsection) error {
41 u.raw = s
42
43 u.Name = s.Name
44 u.InsteadOf = u.raw.Option(insteadOfKey)
45 return nil
46 }
47
48 func (u *URL) marshal() *format.Subsection {
49 if u.raw == nil {
50 u.raw = &format.Subsection{}
51 }
52
53 u.raw.Name = u.Name
54 u.raw.SetOption(insteadOfKey, u.InsteadOf)
55
56 return u.raw
57 }
58
59 func findLongestInsteadOfMatch(remoteURL string, urls map[string]*URL) *URL {
60 var longestMatch *URL
61 for _, u := range urls {
62 if !strings.HasPrefix(remoteURL, u.InsteadOf) {
63 continue
64 }
65
66 // according to spec if there is more than one match, take the logest
67 if longestMatch == nil || len(longestMatch.InsteadOf) < len(u.InsteadOf) {
68 longestMatch = u
69 }
70 }
71
72 return longestMatch
73 }
74
75 func (u *URL) ApplyInsteadOf(url string) string {
76 if !strings.HasPrefix(url, u.InsteadOf) {
77 return url
78 }
79
80 return u.Name + url[len(u.InsteadOf):]
81 }