...
1 package code
2
3 import (
4 "go/build"
5 "os"
6 "path/filepath"
7 "regexp"
8 "strings"
9 )
10
11
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
24
25
26
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
35
36
37
38
39
40
41 func QualifyPackagePath(importPath string) string {
42 wd, _ := os.Getwd()
43
44
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 }
62
View as plain text