github.com/maeglindeveloper/gqlgen@v0.13.1-0.20210413081235-57808b12a0a0/internal/code/util.go (about) 1 package code 2 3 import ( 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 12 func 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 21 var 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 27 func 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 41 func QualifyPackagePath(importPath string) string { 42 wd, _ := os.Getwd() 43 44 // in go module mode, the import path doesn't need fixing 45 if _, ok := goModuleRoot(wd); ok { 46 return importPath 47 } 48 49 pkg, err := build.Import(importPath, wd, 0) 50 if err != nil { 51 return importPath 52 } 53 54 return pkg.ImportPath 55 } 56 57 var invalidPackageNameChar = regexp.MustCompile(`[^\w]`) 58 59 func SanitizePackageName(pkg string) string { 60 return invalidPackageNameChar.ReplaceAllLiteralString(filepath.Base(pkg), "_") 61 }