forked from x-motemen/ghq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl.go
151 lines (136 loc) · 3.94 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/Songmu/gitconfig"
"github.com/x-motemen/ghq/logger"
)
// 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("^[^:]+://")
scpLikeURLPattern = regexp.MustCompile("^([^@]+@)?([^:]+):(/?.+)$")
looksLikeAuthorityPattern = regexp.MustCompile(`[A-Za-z0-9]\.[A-Za-z]+(?::\d{1,5})?$`)
)
func newURL(ref string, ssh, forceMe bool) (*url.URL, error) {
// If argURL is a "./foo" or "../bar" form,
// find repository name trailing after github.com/USER/.
ref = filepath.ToSlash(ref)
parts := strings.Split(ref, "/")
if parts[0] == "." || parts[0] == ".." {
if wd, err := os.Getwd(); err == nil {
path := filepath.Clean(filepath.Join(wd, filepath.Join(parts...)))
var localRepoRoot string
roots, err := localRepositoryRoots(true)
if err != nil {
return nil, err
}
for _, r := range roots {
p := strings.TrimPrefix(path, r+string(filepath.Separator))
if p != path && (localRepoRoot == "" || len(p) < len(localRepoRoot)) {
localRepoRoot = filepath.ToSlash(p)
}
}
if localRepoRoot != "" {
// Guess it
logger.Log("resolved", fmt.Sprintf("relative %q to %q", ref, "https://"+localRepoRoot))
ref = "https://" + localRepoRoot
}
}
}
if !hasSchemePattern.MatchString(ref) {
if scpLikeURLPattern.MatchString(ref) {
matched := scpLikeURLPattern.FindStringSubmatch(ref)
user := matched[1]
host := matched[2]
path := matched[3]
// If the path is a relative path not beginning with a slash like
// `path/to/repo`, we might convert to like
// `ssh://[email protected]/~/path/to/repo` using tilde, but
// since GitHub doesn't support it, we treat relative and absolute
// paths the same way.
ref = fmt.Sprintf("ssh://%s%s/%s", user, host, strings.TrimPrefix(path, "/"))
} else {
// If ref is like "github.com/motemen/ghq" convert to "https://github.com/motemen/ghq"
paths := strings.Split(ref, "/")
if len(paths) > 1 && looksLikeAuthorityPattern.MatchString(paths[0]) {
ref = "https://" + ref
}
}
}
u, err := url.Parse(ref)
if err != nil {
return nil, err
}
if !u.IsAbs() {
if !strings.Contains(u.Path, "/") {
u.Path, err = fillUsernameToPath(u.Path, forceMe)
if err != nil {
return nil, err
}
}
u.Scheme = "https"
u.Host = "github.com"
if u.Path[0] != '/' {
u.Path = "/" + u.Path
}
}
if ssh {
// Assume Git repository if `-p` is given.
if u, err = convertGitURLHTTPToSSH(u); err != nil {
return nil, fmt.Errorf("Could not convert URL %q: %w", u, err)
}
}
return u, nil
}
func convertGitURLHTTPToSSH(u *url.URL) (*url.URL, error) {
user := "git"
if u.User != nil {
user = u.User.Username()
}
sshURL := fmt.Sprintf("ssh://%s@%s%s", user, u.Host, u.Path)
return u.Parse(sshURL)
}
func detectUserName() (string, error) {
user, err := gitconfig.Get("ghq.user")
if (err != nil && !gitconfig.IsNotFound(err)) || user != "" {
return user, err
}
user, err = gitconfig.GitHubUser("")
if (err != nil && !gitconfig.IsNotFound(err)) || user != "" {
return user, err
}
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 "", fmt.Errorf("failed to detect username. You can set ghq.user to your gitconfig")
}
return user, nil
}
func fillUsernameToPath(path string, forceMe bool) (string, error) {
if !forceMe {
completeUser, err := gitconfig.Bool("ghq.completeUser")
if err != nil && !gitconfig.IsNotFound(err) {
return path, err
}
if err == nil && !completeUser {
return path + "/" + path, nil
}
}
user, err := detectUserName()
if err != nil {
return path, err
}
return user + "/" + path, nil
}