1package code
2
3import (
4 "go/build"
5 "os"
6 "path/filepath"
7 "regexp"
8 "strings"
9)
10
11// take a string in the form github.com/package/blah.Type and split it into package and type
12func PkgAndType(name string) (string, string) {
13 parts := strings.Split(name, ".")
14 if len(parts) == 1 {
15 return "", name
16 }
17
18 return strings.Join(parts[:len(parts)-1], "."), parts[len(parts)-1]
19}
20
21var modsRegex = regexp.MustCompile(`^(\*|\[\])*`)
22
23// NormalizeVendor takes a qualified package path and turns it into normal one.
24// eg .
25// github.com/foo/vendor/github.com/99designs/gqlgen/graphql becomes
26// github.com/99designs/gqlgen/graphql
27func NormalizeVendor(pkg string) string {
28 modifiers := modsRegex.FindAllString(pkg, 1)[0]
29 pkg = strings.TrimPrefix(pkg, modifiers)
30 parts := strings.Split(pkg, "/vendor/")
31 return modifiers + parts[len(parts)-1]
32}
33
34// QualifyPackagePath takes an import and fully qualifies it with a vendor dir, if one is required.
35// eg .
36// github.com/99designs/gqlgen/graphql becomes
37// github.com/foo/vendor/github.com/99designs/gqlgen/graphql
38//
39// x/tools/packages only supports 'qualified package paths' so this will need to be done prior to calling it
40// See https://github.com/golang/go/issues/30289
41func QualifyPackagePath(importPath string) string {
42 wd, _ := os.Getwd()
43
44 pkg, err := build.Import(importPath, wd, 0)
45 if err != nil {
46 return importPath
47 }
48
49 return pkg.ImportPath
50}
51
52var invalidPackageNameChar = regexp.MustCompile(`[^\w]`)
53
54func SanitizePackageName(pkg string) string {
55 return invalidPackageNameChar.ReplaceAllLiteralString(filepath.Base(pkg), "_")
56}