github.com/kazu/ghq@v0.8.1-0.20180818162325-dedd532b4440/url.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "net/url" 6 "os" 7 "regexp" 8 "runtime" 9 "strings" 10 ) 11 12 // Convert SCP-like URL to SSH URL(e.g. [user@]host.xz:path/to/repo.git/) 13 // ref. http://git-scm.com/docs/git-fetch#_git_urls 14 // (golang hasn't supported Perl-like negative look-behind match) 15 var hasSchemePattern = regexp.MustCompile("^[^:]+://") 16 var scpLikeUrlPattern = regexp.MustCompile("^([^@]+@)?([^:]+):/?(.+)$") 17 18 func NewURL(ref string) (*url.URL, error) { 19 if !hasSchemePattern.MatchString(ref) && scpLikeUrlPattern.MatchString(ref) { 20 matched := scpLikeUrlPattern.FindStringSubmatch(ref) 21 user := matched[1] 22 host := matched[2] 23 path := matched[3] 24 25 ref = fmt.Sprintf("ssh://%s%s/%s", user, host, path) 26 } 27 28 url, err := url.Parse(ref) 29 if err != nil { 30 return url, err 31 } 32 33 if !url.IsAbs() { 34 if !strings.Contains(url.Path, "/") { 35 url.Path, err = fillUsernameToPath(url.Path) 36 if err != nil { 37 return url, err 38 } 39 } 40 url.Scheme = "https" 41 url.Host = "github.com" 42 if url.Path[0] != '/' { 43 url.Path = "/" + url.Path 44 } 45 } 46 47 return url, nil 48 } 49 50 func ConvertGitURLHTTPToSSH(url *url.URL) (*url.URL, error) { 51 sshURL := fmt.Sprintf("ssh://git@%s%s", url.Host, url.Path) 52 return url.Parse(sshURL) 53 } 54 55 func fillUsernameToPath(path string) (string, error) { 56 user, err := GitConfigSingle("ghq.user") 57 if err != nil { 58 return path, err 59 } 60 if user == "" { 61 user = os.Getenv("GITHUB_USER") 62 } 63 if user == "" { 64 switch runtime.GOOS { 65 case "windows": 66 user = os.Getenv("USERNAME") 67 default: 68 user = os.Getenv("USER") 69 } 70 } 71 if user == "" { 72 // Make the error if it does not match any pattern 73 return path, fmt.Errorf("set ghq.user to your gitconfig") 74 } 75 path = user + "/" + path 76 return path, nil 77 }