github.com/suzuken/ghq@v0.7.5-0.20160607064937-214ded0f64ec/url.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  // Convert SCP-like URL to SSH URL(e.g. [user@]host.xz:path/to/repo.git/)
    11  // ref. http://git-scm.com/docs/git-fetch#_git_urls
    12  // (golang hasn't supported Perl-like negative look-behind match)
    13  var hasSchemePattern = regexp.MustCompile("^[^:]+://")
    14  var scpLikeUrlPattern = regexp.MustCompile("^([^@]+@)?([^:]+):/?(.+)$")
    15  
    16  func NewURL(ref string) (*url.URL, error) {
    17  	if !hasSchemePattern.MatchString(ref) && scpLikeUrlPattern.MatchString(ref) {
    18  		matched := scpLikeUrlPattern.FindStringSubmatch(ref)
    19  		user := matched[1]
    20  		host := matched[2]
    21  		path := matched[3]
    22  
    23  		ref = fmt.Sprintf("ssh://%s%s/%s", user, host, path)
    24  	}
    25  
    26  	url, err := url.Parse(ref)
    27  	if err != nil {
    28  		return url, err
    29  	}
    30  
    31  	if !url.IsAbs() {
    32  		if !strings.Contains(url.Path, "/") {
    33  			url.Path = url.Path + "/" + url.Path
    34  		}
    35  		url.Scheme = "https"
    36  		url.Host = "github.com"
    37  		if url.Path[0] != '/' {
    38  			url.Path = "/" + url.Path
    39  		}
    40  	}
    41  
    42  	return url, nil
    43  }
    44  
    45  func ConvertGitURLHTTPToSSH(url *url.URL) (*url.URL, error) {
    46  	sshURL := fmt.Sprintf("ssh://git@%s/%s", url.Host, url.Path)
    47  	return url.Parse(sshURL)
    48  }