-
Notifications
You must be signed in to change notification settings - Fork 114
/
git_uri.go
82 lines (71 loc) · 1.69 KB
/
git_uri.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
package inrepo
import (
"strings"
"github.com/jenkins-x/lighthouse/pkg/filebrowser"
"github.com/jenkins-x/go-scm/scm"
"github.com/pkg/errors"
)
// GitURI the output of parsing Git URIs
type GitURI struct {
Server string
Owner string
Repository string
Path string
SHA string
}
// ParseGitURI parses git source URIs or returns nil if its not a valid URI
//
// handles strings of the form "owner/repository(/path)@sha"
func ParseGitURI(text string) (*GitURI, error) {
idx := strings.Index(text, "@")
if idx < 0 {
return nil, nil
}
sha := text[idx+1:]
if sha == "" {
return nil, errors.Errorf("missing version, branch or sha after the '@' character in the git URI %s", text)
}
names := text[0:idx]
parts := strings.SplitN(names, "/", 3)
path := ""
switch len(parts) {
case 0, 1:
return nil, errors.Errorf("expecting format 'owner/repository(/path)@sha' but got git URI %s", text)
case 3:
path = parts[2]
}
owner := parts[0]
server := filebrowser.GitHub
serverOwner := strings.SplitN(owner, ":", 2)
if len(serverOwner) > 1 {
server = serverOwner[0]
owner = serverOwner[1]
}
return &GitURI{
Server: server,
Owner: owner,
Repository: parts[1],
Path: path,
SHA: sha,
}, nil
}
// String returns the string representation of the git URI
func (u *GitURI) String() string {
path := scm.Join(u.Owner, u.Repository)
if u.Path != "" {
if !strings.HasPrefix(u.Path, "/") {
path += "/"
}
path += u.Path
}
path = strings.TrimSuffix(path, "/")
sha := u.SHA
if sha == "" {
sha = "head"
}
prefix := ""
if u.Server != "" && u.Server != filebrowser.GitHub {
prefix = u.Server + ":"
}
return prefix + path + "@" + sha
}