forked from go-git/go-git
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
90 lines (70 loc) · 1.82 KB
/
url.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
package config
import (
"errors"
"strings"
format "github.com/go-git/go-git/v5/plumbing/format/config"
)
var (
errURLEmptyInsteadOf = errors.New("url config: empty insteadOf")
)
// Url defines Url rewrite rules
type URL struct {
// Name new base url
Name string
// Any URL that starts with this value will be rewritten to start, instead, with <base>.
// When more than one insteadOf strings match a given URL, the longest match is used.
InsteadOf []string
// raw representation of the subsection, filled by marshal or unmarshal are
// called.
raw *format.Subsection
}
// Validate validates fields of branch
func (b *URL) Validate() error {
if len(b.InsteadOf) == 0 {
return errURLEmptyInsteadOf
}
return nil
}
const (
insteadOfKey = "insteadOf"
)
func (u *URL) unmarshal(s *format.Subsection) error {
u.raw = s
u.Name = s.Name
u.InsteadOf = u.raw.OptionAll(insteadOfKey)
return nil
}
func (u *URL) marshal() *format.Subsection {
if u.raw == nil {
u.raw = &format.Subsection{}
}
u.raw.Name = u.Name
u.raw.SetOption(insteadOfKey, u.InsteadOf...)
return u.raw
}
func findLongestInsteadOfMatch(remoteURL string, urls map[string]*URL) *URL {
var longestMatch *URL
var longestMatchLength int
for _, u := range urls {
for _, currentInsteadOf := range u.InsteadOf {
if !strings.HasPrefix(remoteURL, currentInsteadOf) {
continue
}
lengthCurrentInsteadOf := len(currentInsteadOf)
// according to spec if there is more than one match, take the longest
if longestMatch == nil || longestMatchLength < lengthCurrentInsteadOf {
longestMatch = u
longestMatchLength = lengthCurrentInsteadOf
}
}
}
return longestMatch
}
func (u *URL) ApplyInsteadOf(url string) string {
for _, j := range u.InsteadOf {
if strings.HasPrefix(url, j) {
return u.Name + url[len(j):]
}
}
return url
}