walk_packages.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "golang.org/x/tools/go/packages"
  7. "gopkg.in/yaml.v3"
  8. )
  9. func main() {
  10. flag.Parse()
  11. // Many tools pass their command-line arguments (after any flags)
  12. // uninterpreted to packages.Load so that it can interpret them
  13. // according to the conventions of the underlying build system.
  14. cfg := &packages.Config{
  15. Mode: packages.NeedCompiledGoFiles | // CompiledGoFiles in the package, as absolute source paths
  16. // packages.NeedDeps | // Make TypesInfo include imported types and resolve Imports beyond just names
  17. packages.NeedEmbedFiles | // EmbedFiles as absolute paths. For embed.FS, all resolved files
  18. packages.NeedEmbedPatterns | // EmbedPatterns as absolute paths. For embed.FS, the embed path
  19. packages.NeedExportFile | // ExportFile: the compiled package, for use with ar or go tool nm
  20. packages.NeedFiles | // GoFiles and OtherFiles as absolute paths
  21. packages.NeedImports | // Imports, as a map[string]packages.Package. Use
  22. packages.NeedModule | // Modules, as a packages.Module
  23. packages.NeedName | // e.g. main
  24. packages.NeedSyntax | // Syntax, a []*ast.File containing the parsed files in the package
  25. packages.NeedTypes | // Types, Fset (the set of files in the compile result) and IllTyped (bool)
  26. packages.NeedTypesInfo | // TypesInfo for all types in the compile result
  27. packages.NeedTypesSizes, // TypesSizes: WordSize (8) and MaxAlign (8)
  28. }
  29. pkgs, err := packages.Load(cfg, flag.Args()...)
  30. if err != nil {
  31. fmt.Fprintf(os.Stderr, "load: %v\n", err)
  32. os.Exit(1)
  33. }
  34. if packages.PrintErrors(pkgs) > 0 {
  35. os.Exit(1)
  36. }
  37. info := make(map[string][]string)
  38. // Print the names of the source files
  39. // for each package listed on the command line.
  40. for _, pkg := range pkgs {
  41. info[pkg.ID] = pkg.GoFiles
  42. }
  43. enc := yaml.NewEncoder(os.Stdout)
  44. enc.SetIndent(2)
  45. enc.Encode(info)
  46. }