github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/x/pkgx/pkgx_util.go (about) 1 package pkgx 2 3 import ( 4 "bytes" 5 "fmt" 6 "go/ast" 7 "go/format" 8 "go/token" 9 "path/filepath" 10 "strings" 11 12 "golang.org/x/tools/go/packages" 13 ) 14 15 func StringifyNode(fs *token.FileSet, n ast.Node) string { 16 if cg, ok := n.(*ast.CommentGroup); ok { 17 return StringifyCommentGroup(cg) 18 } 19 buf := bytes.NewBuffer(nil) 20 if err := format.Node(buf, fs, n); err != nil { 21 panic(err) 22 } 23 return buf.String() 24 } 25 26 func StringifyCommentGroup(cgs ...*ast.CommentGroup) string { 27 if len(cgs) == 0 { 28 return "" 29 } 30 comments := "" 31 for _, cg := range cgs { 32 for _, line := range strings.Split(cg.Text(), "\n") { 33 if strings.HasPrefix(line, "go:") { 34 continue 35 } 36 comments = comments + "\n" + line 37 } 38 } 39 return strings.TrimSpace(comments) 40 } 41 42 func Import(path string) string { 43 parts := strings.Split(path, "/vendor/") 44 return parts[len(parts)-1] 45 } 46 47 func ImportPathAndExpose(s string) (string, string) { 48 args := strings.Split(s, ".") 49 if _len := len(args); _len > 1 { 50 return Import(strings.Join(args[0:_len-1], ".")), args[_len-1] 51 } 52 return "", s 53 } 54 55 const ( 56 ModeLoadFiles = packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles 57 ) 58 59 func FindPkgInfoByPath(path string, modes ...packages.LoadMode) (*packages.Package, error) { 60 mode := ModeLoadFiles 61 if len(modes) > 0 { 62 for _, v := range modes { 63 mode |= v 64 } 65 } 66 pkgs, err := packages.Load(&packages.Config{Mode: ModeLoadFiles}, path) 67 if err != nil { 68 panic(err) 69 } 70 if len(pkgs) == 0 { 71 return nil, fmt.Errorf("package `%s` not found", path) 72 } 73 return pkgs[0], nil 74 } 75 76 func PkgIdByPath(path string, modes ...packages.LoadMode) (string, error) { 77 pkg, err := FindPkgInfoByPath(path, modes...) 78 if err != nil { 79 return "", err 80 } 81 return pkg.ID, nil 82 } 83 84 func PkgPathByPath(path string, modes ...packages.LoadMode) (string, error) { 85 pkg, err := FindPkgInfoByPath(path, modes...) 86 if err != nil { 87 return "", err 88 } 89 return filepath.Dir(pkg.GoFiles[0]), nil 90 }