-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
98 lines (77 loc) · 2.15 KB
/
util.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
91
92
93
94
95
96
97
98
package generator
import (
"fmt"
"net/url"
"path/filepath"
"regexp"
"strings"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
const (
TIDTypeRepo = "REPO"
TIDTypeFile = "FILE"
TIDTypeAlias = "ALIAS"
TIDTypeUnknown = "UNKNOWN"
)
var (
scpLikeUrlRegExp = regexp.MustCompile("^(ssh://)?(?:(?P<user>[^@]+)(?:@))?(?P<host>[^:|/|.]+[.][^:|/|.]+)+(?::|/)+(?P<path>.+)$")
isHttpSchemeRegExp = regexp.MustCompile("^(http|https)://")
isFileSchemeRegExp = regexp.MustCompile("^[.|" + string(filepath.Separator) + "]|(file)://")
)
func TypeForTemplateID(templateID string) string {
if IsRepoURL(templateID) {
return TIDTypeRepo
}
if IsFilePath(templateID) {
return TIDTypeFile
}
return TIDTypeAlias
}
func AuthMethodForURL(url string) transport.AuthMethod {
var am transport.AuthMethod
if IsSSH(url) {
// 1:scheme, 2:user, 3:host, 4:path
m := scpLikeUrlRegExp.FindStringSubmatch(url)
a, err := ssh.NewSSHAgentAuth(m[2])
if err == nil {
am = a
}
}
return am
}
func FilepathFromURL(u string) (string, error) {
var err error
var fpath string
var pu *url.URL
if !IsRepoURL(u) {
return fpath, fmt.Errorf("invalid url %s", u)
}
if isHttpSchemeRegExp.MatchString(u) {
pu, err = url.Parse(u)
if err == nil {
fpath = pu.Hostname() + pu.Path
}
} else if IsSSH(u) {
// 1:scheme, 2:user, 3:host, 4:path
m := scpLikeUrlRegExp.FindStringSubmatch(u)
fpath = m[3] + "/" + m[4]
}
if strings.HasSuffix(fpath, ".git") {
fpath = strings.TrimSuffix(fpath, ".git")
}
fpath = filepath.FromSlash(fpath)
return fpath, err
}
func IsRepoURL(templateID string) bool {
return !isFileSchemeRegExp.MatchString(templateID) && (isHttpSchemeRegExp.MatchString(templateID) || scpLikeUrlRegExp.MatchString(templateID))
}
func IsSSH(templateID string) bool {
return !isFileSchemeRegExp.MatchString(templateID) && !isHttpSchemeRegExp.MatchString(templateID) && scpLikeUrlRegExp.MatchString(templateID)
}
func IsFilePath(templateID string) bool {
return isFileSchemeRegExp.MatchString(templateID)
}
func IsAlias(templateID string) bool {
return !IsFilePath(templateID) && !IsRepoURL(templateID)
}