| 1 | // Copyright 2018 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // The gopackages command is a diagnostic tool that demonstrates |
| 6 | // how to use golang.org/x/tools/go/packages to load, parse, |
| 7 | // type-check, and print one or more Go packages. |
| 8 | // Its precise output is unspecified and may change. |
| 9 | package main |
| 10 | |
| 11 | import ( |
| 12 | "context" |
| 13 | "encoding/json" |
| 14 | "flag" |
| 15 | "fmt" |
| 16 | "go/types" |
| 17 | "log" |
| 18 | "os" |
| 19 | "sort" |
| 20 | "strings" |
| 21 | |
| 22 | "golang.org/x/tools/go/packages" |
| 23 | "golang.org/x/tools/go/types/typeutil" |
| 24 | "golang.org/x/tools/internal/drivertest" |
| 25 | "golang.org/x/tools/internal/tool" |
| 26 | ) |
| 27 | |
| 28 | func main() { |
| 29 | drivertest.RunIfChild() |
| 30 | tool.Main(context.Background(), &application{Mode: "imports"}, os.Args[1:]) |
| 31 | } |
| 32 | |
| 33 | type application struct { |
| 34 | // Embed the basic profiling flags supported by the tool package |
| 35 | tool.Profile |
| 36 | |
| 37 | Deps bool `flag:"deps" help:"show dependencies too"` |
| 38 | Test bool `flag:"test" help:"include any tests implied by the patterns"` |
| 39 | Mode string `flag:"mode" help:"mode (one of files, imports, types, syntax, allsyntax)"` |
| 40 | Tags string `flag:"tags" help:"comma-separated list of extra build tags (see: go help buildconstraint)"` |
| 41 | Private bool `flag:"private" help:"show non-exported declarations too (if -mode=syntax)"` |
| 42 | PrintJSON bool `flag:"json" help:"print package in JSON form"` |
| 43 | BuildFlags stringListValue `flag:"buildflag" help:"pass argument to underlying build system (may be repeated)"` |
| 44 | Driver bool `flag:"driver" help:"use golist passthrough driver (for debugging driver issues)"` |
| 45 | } |
| 46 | |
| 47 | // Name implements tool.Application returning the binary name. |
| 48 | func (app *application) Name() string { return "gopackages" } |
| 49 | |
| 50 | // Usage implements tool.Application returning empty extra argument usage. |
| 51 | func (app *application) Usage() string { return "package..." } |
| 52 | |
| 53 | // ShortHelp implements tool.Application returning the main binary help. |
| 54 | func (app *application) ShortHelp() string { |
| 55 | return "gopackages loads, parses, type-checks, and prints one or more Go packages." |
| 56 | } |
| 57 | |
| 58 | // DetailedHelp implements tool.Application returning the main binary help. |
| 59 | func (app *application) DetailedHelp(f *flag.FlagSet) { |
| 60 | fmt.Fprint(f.Output(), ` |
| 61 | Packages are specified using the notation of "go list", |
| 62 | or other underlying build system. |
| 63 | |
| 64 | The mode flag determines how much information is computed and printed |
| 65 | for the specified packages. In order of increasing computational cost, |
| 66 | the legal values are: |
| 67 | |
| 68 | -mode=files shows only the names of the packages' files. |
| 69 | -mode=imports also shows the imports. (This is the default.) |
| 70 | -mode=types loads the compiler's export data and displays the |
| 71 | type of each exported declaration. |
| 72 | -mode=syntax parses and type checks syntax trees for the initial |
| 73 | packages. (With the -private flag, the types of |
| 74 | non-exported declarations are shown too.) |
| 75 | Type information for dependencies is obtained from |
| 76 | compiler export data. |
| 77 | -mode=allsyntax is like -mode=syntax but applied to all dependencies. |
| 78 | |
| 79 | Flags: |
| 80 | `) |
| 81 | f.PrintDefaults() |
| 82 | } |
| 83 | |
| 84 | // Run takes the args after flag processing and performs the specified query. |
| 85 | func (app *application) Run(ctx context.Context, args ...string) error { |
| 86 | if len(args) == 0 { |
| 87 | return tool.CommandLineErrorf("not enough arguments") |
| 88 | } |
| 89 | |
| 90 | env := os.Environ() |
| 91 | if app.Driver { |
| 92 | env = append(env, drivertest.Env(log.Default())...) |
| 93 | } |
| 94 | |
| 95 | // Load, parse, and type-check the packages named on the command line. |
| 96 | cfg := &packages.Config{ |
| 97 | Mode: packages.LoadSyntax, |
| 98 | Tests: app.Test, |
| 99 | BuildFlags: append([]string{"-tags=" + app.Tags}, app.BuildFlags...), |
| 100 | Env: env, |
| 101 | } |
| 102 | |
| 103 | // -mode flag |
| 104 | switch strings.ToLower(app.Mode) { |
| 105 | case "files": |
| 106 | cfg.Mode = packages.LoadFiles |
| 107 | case "imports": |
| 108 | cfg.Mode = packages.LoadImports |
| 109 | case "types": |
| 110 | cfg.Mode = packages.LoadTypes |
| 111 | case "syntax": |
| 112 | cfg.Mode = packages.LoadSyntax |
| 113 | case "allsyntax": |
| 114 | cfg.Mode = packages.LoadAllSyntax |
| 115 | default: |
| 116 | return tool.CommandLineErrorf("invalid mode: %s", app.Mode) |
| 117 | } |
| 118 | cfg.Mode |= packages.NeedModule |
| 119 | |
| 120 | lpkgs, err := packages.Load(cfg, args...) |
| 121 | if err != nil { |
| 122 | return err |
| 123 | } |
| 124 | |
| 125 | // -deps: print dependencies too. |
| 126 | if app.Deps { |
| 127 | // We can't use packages.All because |
| 128 | // we need an ordered traversal. |
| 129 | var all []*packages.Package // postorder |
| 130 | seen := make(map[*packages.Package]bool) |
| 131 | var visit func(*packages.Package) |
| 132 | visit = func(lpkg *packages.Package) { |
| 133 | if !seen[lpkg] { |
| 134 | seen[lpkg] = true |
| 135 | |
| 136 | // visit imports |
| 137 | var importPaths []string |
| 138 | for path := range lpkg.Imports { |
| 139 | importPaths = append(importPaths, path) |
| 140 | } |
| 141 | sort.Strings(importPaths) // for determinism |
| 142 | for _, path := range importPaths { |
| 143 | visit(lpkg.Imports[path]) |
| 144 | } |
| 145 | |
| 146 | all = append(all, lpkg) |
| 147 | } |
| 148 | } |
| 149 | for _, lpkg := range lpkgs { |
| 150 | visit(lpkg) |
| 151 | } |
| 152 | lpkgs = all |
| 153 | } |
| 154 | |
| 155 | for _, lpkg := range lpkgs { |
| 156 | app.print(lpkg) |
| 157 | } |
| 158 | return nil |
| 159 | } |
| 160 | |
| 161 | func (app *application) print(lpkg *packages.Package) { |
| 162 | if app.PrintJSON { |
| 163 | data, _ := json.MarshalIndent(lpkg, "", "\t") |
| 164 | os.Stdout.Write(data) |
| 165 | return |
| 166 | } |
| 167 | // title |
| 168 | var kind string |
| 169 | // TODO(matloob): If IsTest is added back print "test command" or |
| 170 | // "test package" for packages with IsTest == true. |
| 171 | if lpkg.Name == "main" { |
| 172 | kind += "command" |
| 173 | } else { |
| 174 | kind += "package" |
| 175 | } |
| 176 | fmt.Printf("Go %s %q:\n", kind, lpkg.ID) // unique ID |
| 177 | if mod := lpkg.Module; mod != nil { |
| 178 | fmt.Printf("\tmodule %s@%s\n", mod.Path, mod.Version) |
| 179 | } |
| 180 | fmt.Printf("\tpackage %s\n", lpkg.Name) |
| 181 | |
| 182 | // characterize type info |
| 183 | if lpkg.Types == nil { |
| 184 | fmt.Printf("\thas no exported type info\n") |
| 185 | } else if !lpkg.Types.Complete() { |
| 186 | fmt.Printf("\thas incomplete exported type info\n") |
| 187 | } else if len(lpkg.Syntax) == 0 { |
| 188 | fmt.Printf("\thas complete exported type info\n") |
| 189 | } else { |
| 190 | fmt.Printf("\thas complete exported type info and typed ASTs\n") |
| 191 | } |
| 192 | if lpkg.Types != nil && lpkg.IllTyped && len(lpkg.Errors) == 0 { |
| 193 | fmt.Printf("\thas an error among its dependencies\n") |
| 194 | } |
| 195 | |
| 196 | // source files |
| 197 | for _, src := range lpkg.GoFiles { |
| 198 | fmt.Printf("\tfile %s\n", src) |
| 199 | } |
| 200 | |
| 201 | // imports |
| 202 | var lines []string |
| 203 | for importPath, imp := range lpkg.Imports { |
| 204 | var line string |
| 205 | if imp.ID == importPath { |
| 206 | line = fmt.Sprintf("\timport %q", importPath) |
| 207 | } else { |
| 208 | line = fmt.Sprintf("\timport %q => %q", importPath, imp.ID) |
| 209 | } |
| 210 | lines = append(lines, line) |
| 211 | } |
| 212 | sort.Strings(lines) |
| 213 | for _, line := range lines { |
| 214 | fmt.Println(line) |
| 215 | } |
| 216 | |
| 217 | // errors |
| 218 | for _, err := range lpkg.Errors { |
| 219 | fmt.Printf("\t%s\n", err) |
| 220 | } |
| 221 | |
| 222 | // types of package members |
| 223 | if lpkg.Types != nil { |
| 224 | qual := types.RelativeTo(lpkg.Types) |
| 225 | scope := lpkg.Types.Scope() |
| 226 | for _, name := range scope.Names() { |
| 227 | obj := scope.Lookup(name) |
| 228 | if !obj.Exported() && !app.Private { |
| 229 | continue // skip unexported names |
| 230 | } |
| 231 | |
| 232 | fmt.Printf("\t%s\n", types.ObjectString(obj, qual)) |
| 233 | if _, ok := obj.(*types.TypeName); ok { |
| 234 | for _, meth := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { |
| 235 | if !meth.Obj().Exported() && !app.Private { |
| 236 | continue // skip unexported names |
| 237 | } |
| 238 | fmt.Printf("\t%s\n", types.SelectionString(meth, qual)) |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | fmt.Println() |
| 245 | } |
| 246 | |
| 247 | // stringListValue is a flag.Value that accumulates strings. |
| 248 | // e.g. --flag=one --flag=two would produce []string{"one", "two"}. |
| 249 | type stringListValue []string |
| 250 | |
| 251 | func (ss *stringListValue) Get() any { return []string(*ss) } |
| 252 | |
| 253 | func (ss *stringListValue) String() string { return fmt.Sprintf("%q", *ss) } |
| 254 | |
| 255 | func (ss *stringListValue) Set(s string) error { *ss = append(*ss, s); return nil } |