github.com/echohead/hub@v2.2.1+incompatible/git/url.go (about)

     1  package git
     2  
     3  import (
     4  	"net/url"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  var (
    10  	cachedSSHConfig SSHConfig
    11  	protocolRe      = regexp.MustCompile("^[a-zA-Z_-]+://")
    12  )
    13  
    14  type URLParser struct {
    15  	SSHConfig SSHConfig
    16  }
    17  
    18  func (p *URLParser) Parse(rawURL string) (u *url.URL, err error) {
    19  	if !protocolRe.MatchString(rawURL) &&
    20  		strings.Contains(rawURL, ":") &&
    21  		// not a Windows path
    22  		!strings.Contains(rawURL, "\\") {
    23  		rawURL = "ssh://" + strings.Replace(rawURL, ":", "/", 1)
    24  	}
    25  
    26  	u, err = url.Parse(rawURL)
    27  	if err != nil {
    28  		return
    29  	}
    30  
    31  	if u.Scheme != "ssh" {
    32  		return
    33  	}
    34  
    35  	sshHost := p.SSHConfig[u.Host]
    36  	// ignore replacing host that fixes for limited network
    37  	// https://help.github.com/articles/using-ssh-over-the-https-port
    38  	ignoredHost := u.Host == "github.com" && sshHost == "ssh.github.com"
    39  	if !ignoredHost && sshHost != "" {
    40  		u.Host = sshHost
    41  	}
    42  
    43  	return
    44  }
    45  
    46  func ParseURL(rawURL string) (u *url.URL, err error) {
    47  	if cachedSSHConfig == nil {
    48  		cachedSSHConfig = newSSHConfigReader().Read()
    49  	}
    50  
    51  	p := &URLParser{cachedSSHConfig}
    52  
    53  	return p.Parse(rawURL)
    54  }