go__parsing_demo/04-walk_packages/walk_packages.go
Frédéric G. MARAND 3d784fdb6f
WIP
2023-04-04 11:06:18 +02:00

51 lines
1.8 KiB
Go

package main
import (
"flag"
"fmt"
"os"
"golang.org/x/tools/go/packages"
"gopkg.in/yaml.v3"
)
func main() {
flag.Parse()
// Many tools pass their command-line arguments (after any flags)
// uninterpreted to packages.Load so that it can interpret them
// according to the conventions of the underlying build system.
cfg := &packages.Config{
Mode: packages.NeedCompiledGoFiles | // CompiledGoFiles in the package, as absolute source paths
// packages.NeedDeps | // Make TypesInfo include imported types and resolve Imports beyond just names
packages.NeedEmbedFiles | // EmbedFiles as absolute paths. For embed.FS, all resolved files
packages.NeedEmbedPatterns | // EmbedPatterns as absolute paths. For embed.FS, the embed path
packages.NeedExportFile | // ExportFile: the compiled package, for use with ar or go tool nm
packages.NeedFiles | // GoFiles and OtherFiles as absolute paths
packages.NeedImports | // Imports, as a map[string]packages.Package. Use
packages.NeedModule | // Modules, as a packages.Module
packages.NeedName | // e.g. main
packages.NeedSyntax | // Syntax, a []*ast.File containing the parsed files in the package
packages.NeedTypes | // Types, Fset (the set of files in the compile result) and IllTyped (bool)
packages.NeedTypesInfo | // TypesInfo for all types in the compile result
packages.NeedTypesSizes, // TypesSizes: WordSize (8) and MaxAlign (8)
}
pkgs, err := packages.Load(cfg, flag.Args()...)
if err != nil {
fmt.Fprintf(os.Stderr, "load: %v\n", err)
os.Exit(1)
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1)
}
info := make(map[string][]string)
// Print the names of the source files
// for each package listed on the command line.
for _, pkg := range pkgs {
info[pkg.ID] = pkg.GoFiles
}
enc := yaml.NewEncoder(os.Stdout)
enc.SetIndent(2)
enc.Encode(info)
}