Files
goreportcard/download/download.go
2021-11-23 19:24:08 +09:00

46 lines
1.1 KiB
Go

package download
import (
"errors"
"strings"
"golang.org/x/tools/go/vcs"
)
// Clean trims any URL parts, like the scheme or username, that might be present
// in a user-submitted URL
func Clean(path string) (string, error) {
importPath := trimUsername(trimScheme(path))
root, err := vcs.RepoRootForImportPath(importPath, true)
if err != nil {
return "", err
}
if root != nil && (root.Root == "" || root.Repo == "") {
return root.Root, errors.New("empty repo root")
}
return root.Root, err
}
// trimScheme removes a scheme (e.g. https://) from the URL for more
// convenient pasting from browsers.
func trimScheme(repo string) string {
schemeSep := "://"
schemeSepIdx := strings.Index(repo, schemeSep)
if schemeSepIdx > -1 {
return repo[schemeSepIdx+len(schemeSep):]
}
return repo
}
// trimUsername removes the username for a URL, if it is present
func trimUsername(repo string) string {
usernameSep := "@"
usernameSepIdx := strings.Index(repo, usernameSep)
if usernameSepIdx > -1 {
return repo[usernameSepIdx+len(usernameSep):]
}
return repo
}