package tool import ( "fmt" "os" "path/filepath" "strings" "golang.org/x/tools/go/packages" ) func main() { pwd, err := os.Getwd() if err != nil { fmt.Println("无法获取当前工作目录") panic(err) } sep := string(filepath.Separator) s := strings.Split(pwd, sep) var project string for i := len(s); i > 0; i-- { base := strings.Join(s[:i], sep) module := filepath.Join(base, "go.mod") _, err := os.Stat(module) if err == nil { project = module break } } if project == "" { panic("没有找到 go.mod ,请检查是否在 module 中调用程序") } project = filepath.Dir(project) fmt.Println("当前寻根目录 " + project) pkgs, err := packages.Load(&packages.Config{ Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedDeps, Tests: false, }, filepath.Join(project, "...")) if err != nil { fmt.Println("解析项目失败") panic(err) } for _, pkg := range pkgs { fmt.Println(pkg.Name) } }