Handle SCP-like URL only if it has no scheme

This commit is contained in:
Kentaro Kuribayashi 2014-06-02 17:09:13 +09:00
parent 4956392c47
commit ed5f948c57
2 changed files with 23 additions and 8 deletions

16
url.go
View file

@ -6,12 +6,20 @@ import (
"regexp"
)
var pattern = regexp.MustCompile("^([^@]+)@([^:]+):(.+)$")
// 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 pattern.MatchString(ref) {
matched := pattern.FindStringSubmatch(ref)
ref = fmt.Sprintf("ssh://%s@%s/%s", matched[1], matched[2], matched[3])
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)
}
return url.Parse(ref)

View file

@ -1,20 +1,27 @@
package main
import (
"testing"
. "github.com/onsi/gomega"
"testing"
)
func TestNewURL(t *testing.T) {
RegisterTestingT(t)
// Does nothing whent the URL has scheme part
httpsUrl, err := NewURL("https://github.com/motemen/pusheen-explorer")
Expect(httpsUrl.String()).To(Equal("https://github.com/motemen/pusheen-explorer"))
Expect(httpsUrl.Host).To(Equal("github.com"))
Expect(err).To(BeNil())
sshUrl, err := NewURL("git@github.com:motemen/pusheen-explorer.git")
Expect(sshUrl.String()).To(Equal("ssh://git@github.com/motemen/pusheen-explorer.git"))
Expect(sshUrl.Host).To(Equal("github.com"))
// Convert SCP-like URL to SSH URL
scpUrl, err := NewURL("git@github.com:motemen/pusheen-explorer.git")
Expect(scpUrl.String()).To(Equal("ssh://git@github.com/motemen/pusheen-explorer.git"))
Expect(scpUrl.Host).To(Equal("github.com"))
Expect(err).To(BeNil())
scpUrlWithoutUser, err := NewURL("github.com:motemen/pusheen-explorer.git")
Expect(scpUrlWithoutUser.String()).To(Equal("ssh://github.com/motemen/pusheen-explorer.git"))
Expect(scpUrlWithoutUser.Host).To(Equal("github.com"))
Expect(err).To(BeNil())
}