forked from x-motemen/ghq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
77 lines (68 loc) · 1.67 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
package main
import (
"fmt"
"net/url"
"os"
"regexp"
"runtime"
"strings"
)
// Convert SCP-like URL to SSH URL(e.g. [user@]host.xz:path/to/repo.git/)
// ref. http://git-scm.com/docs/git-fetch#_git_urls
// (golang hasn't supported Perl-like negative look-behind match)
var hasSchemePattern = regexp.MustCompile("^[^:]+://")
var scpLikeUrlPattern = regexp.MustCompile("^([^@]+@)?([^:]+):/?(.+)$")
func NewURL(ref string) (*url.URL, error) {
if !hasSchemePattern.MatchString(ref) && scpLikeUrlPattern.MatchString(ref) {
matched := scpLikeUrlPattern.FindStringSubmatch(ref)
user := matched[1]
host := matched[2]
path := matched[3]
ref = fmt.Sprintf("ssh://%s%s/%s", user, host, path)
}
url, err := url.Parse(ref)
if err != nil {
return url, err
}
if !url.IsAbs() {
if !strings.Contains(url.Path, "/") {
url.Path, err = fillUsernameToPath(url.Path)
if err != nil {
return url, err
}
}
url.Scheme = "https"
url.Host = "github.com"
if url.Path[0] != '/' {
url.Path = "/" + url.Path
}
}
return url, nil
}
func ConvertGitURLHTTPToSSH(url *url.URL) (*url.URL, error) {
sshURL := fmt.Sprintf("ssh://git@%s%s", url.Host, url.Path)
return url.Parse(sshURL)
}
func fillUsernameToPath(path string) (string, error) {
user, err := GitConfigSingle("ghq.user")
if err != nil {
return path, err
}
if user == "" {
user = os.Getenv("GITHUB_USER")
}
if user == "" {
switch runtime.GOOS {
case "windows":
user = os.Getenv("USERNAME")
default:
user = os.Getenv("USER")
}
}
if user == "" {
// Make the error if it does not match any pattern
return path, fmt.Errorf("set ghq.user to your gitconfig")
}
path = user + "/" + path
return path, nil
}