2013-12-06 22:50:19 +04:00
|
|
|
package git
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/url"
|
|
|
|
"regexp"
|
2014-07-28 12:49:42 +04:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2014-11-03 19:26:52 +03:00
|
|
|
cachedSSHConfig SSHConfig
|
2016-01-21 17:26:55 +03:00
|
|
|
protocolRe = regexp.MustCompile("^[a-zA-Z_+-]+://")
|
2013-12-06 22:50:19 +04:00
|
|
|
)
|
|
|
|
|
2014-11-03 19:26:52 +03:00
|
|
|
type URLParser struct {
|
|
|
|
SSHConfig SSHConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *URLParser) Parse(rawURL string) (u *url.URL, err error) {
|
2014-11-21 06:36:32 +03:00
|
|
|
if !protocolRe.MatchString(rawURL) &&
|
|
|
|
strings.Contains(rawURL, ":") &&
|
|
|
|
// not a Windows path
|
|
|
|
!strings.Contains(rawURL, "\\") {
|
2014-11-03 19:26:52 +03:00
|
|
|
rawURL = "ssh://" + strings.Replace(rawURL, ":", "/", 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
u, err = url.Parse(rawURL)
|
|
|
|
if err != nil {
|
|
|
|
return
|
2014-07-28 12:49:42 +04:00
|
|
|
}
|
|
|
|
|
2016-01-21 17:26:55 +03:00
|
|
|
if u.Scheme == "git+ssh" {
|
|
|
|
u.Scheme = "ssh"
|
|
|
|
}
|
|
|
|
|
2014-11-21 06:36:32 +03:00
|
|
|
if u.Scheme != "ssh" {
|
2014-11-16 23:21:56 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-01-21 17:26:55 +03:00
|
|
|
if strings.HasPrefix(u.Path, "//") {
|
|
|
|
u.Path = strings.TrimPrefix(u.Path, "/")
|
|
|
|
}
|
|
|
|
|
|
|
|
if idx := strings.Index(u.Host, ":"); idx >= 0 {
|
|
|
|
u.Host = u.Host[0:idx]
|
|
|
|
}
|
|
|
|
|
2014-11-03 19:26:52 +03:00
|
|
|
sshHost := p.SSHConfig[u.Host]
|
|
|
|
// ignore replacing host that fixes for limited network
|
|
|
|
// https://help.github.com/articles/using-ssh-over-the-https-port
|
|
|
|
ignoredHost := u.Host == "github.com" && sshHost == "ssh.github.com"
|
|
|
|
if !ignoredHost && sshHost != "" {
|
|
|
|
u.Host = sshHost
|
2014-07-28 12:49:42 +04:00
|
|
|
}
|
2014-11-03 19:26:52 +03:00
|
|
|
|
2014-07-28 12:49:42 +04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-11-03 19:26:52 +03:00
|
|
|
func ParseURL(rawURL string) (u *url.URL, err error) {
|
|
|
|
if cachedSSHConfig == nil {
|
|
|
|
cachedSSHConfig = newSSHConfigReader().Read()
|
2013-12-06 22:50:19 +04:00
|
|
|
}
|
|
|
|
|
2014-11-03 19:26:52 +03:00
|
|
|
p := &URLParser{cachedSSHConfig}
|
|
|
|
|
|
|
|
return p.Parse(rawURL)
|
2013-12-06 22:50:19 +04:00
|
|
|
}
|