NormalizeGithubRemote validates and converts a Git remote to a normalized HTTPS Github URL ending in .git.
(remote string)
| 32 | |
| 33 | // NormalizeGithubRemote validates and converts a Git remote to a normalized HTTPS Github URL ending in .git. |
| 34 | func NormalizeGithubRemote(remote string) (string, error) { |
| 35 | ep, err := transport.NewEndpoint(remote) |
| 36 | if err != nil { |
| 37 | return "", err |
| 38 | } |
| 39 | |
| 40 | if ep.Host != "github.com" { |
| 41 | return "", fmt.Errorf("remote %q is not a valid github.com remote", remote) |
| 42 | } |
| 43 | |
| 44 | account, repo := path.Split(ep.Path) |
| 45 | account = strings.Trim(account, "/") |
| 46 | repo = strings.TrimSuffix(repo, ".git") |
| 47 | if account == "" || repo == "" || strings.Contains(account, "/") { |
| 48 | return "", fmt.Errorf("remote %q is not a valid github.com remote", remote) |
| 49 | } |
| 50 | |
| 51 | // The .git suffix is not always required (e.g. Github has redirects if its missing), so we add it for consistency. |
| 52 | if !strings.HasSuffix(ep.Path, ".git") { |
| 53 | ep.Path += ".git" |
| 54 | } |
| 55 | |
| 56 | githubRemote := &url.URL{ |
| 57 | Scheme: "https", |
| 58 | Host: ep.Host, |
| 59 | Path: ep.Path, |
| 60 | } |
| 61 | |
| 62 | return githubRemote.String(), nil |
| 63 | } |