| 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 | "runtime/pprof" |
| 20 | "runtime/trace" |
| 21 | "sort" |
| 22 | "strings" |
| 23 | |
| 24 | "golang.org/x/tools/go/packages" |
| 25 | "golang.org/x/tools/go/types/typeutil" |
| 26 | "golang.org/x/tools/internal/drivertest" |
| 27 | ) |
| 28 | |
| 29 | func main() { |
| 30 | drivertest.RunIfChild() |
| 31 | |
| 32 | var ( |
| 33 | cpuprofile = flag.String("profile.cpu", "", "write CPU profile to this file") |
| 34 | memprofile = flag.String("profile.mem", "", "write memory profile to this file") |
| 35 | traceprofile = flag.String("profile.trace", "", "write trace log to this file") |
| 36 | ) |
| 37 | |
| 38 | var ( |
| 39 | deps = flag.Bool("deps", false, "show dependencies too") |
| 40 | test = flag.Bool("test", false, "include any tests implied by the patterns") |
| 41 | mode = flag.String("mode", "imports", "mode (one of files, imports, types, syntax, allsyntax)") |
| 42 | tags = flag.String("tags", "", "comma-separated list of extra build tags (see: go help buildconstraint)") |
| 43 | private = flag.Bool("private", false, "show non-exported declarations too (if -mode=syntax)") |
| 44 | printJSON = flag.Bool("json", false, "print package in JSON form") |
| 45 | driver = flag.Bool("driver", false, "use golist passthrough driver (for debugging driver issues)") |
| 46 | buildFlags stringListValue |
| 47 | ) |
| 48 | flag.Var(&buildFlags, "buildflag", "pass argument to underlying build system (may be repeated)") |
| 49 | |
| 50 | flag.Usage = func() { |
| 51 | fmt.Fprint(flag.CommandLine.Output(), `gopackages loads, parses, type-checks, and prints one or more Go packages. |
| 52 | |
| 53 | Usage: |
| 54 | gopackages [flags] package... |
| 55 | |
| 56 | Packages are specified using the notation of "go list", |
| 57 | or other underlying build system. |
| 58 | |
| 59 | The mode flag determines how much information is computed and printed |
| 60 | for the specified packages. In order of increasing computational cost, |
| 61 | the legal values are: |
| 62 | |
| 63 | -mode=files shows only the names of the packages' files. |
| 64 | -mode=imports also shows the imports. (This is the default.) |
| 65 | -mode=types loads the compiler's export data and displays the |
| 66 | type of each exported declaration. |
| 67 | -mode=syntax parses and type checks syntax trees for the initial |
| 68 | packages. (With the -private flag, the types of |
| 69 | non-exported declarations are shown too.) |
| 70 | Type information for dependencies is obtained from |
| 71 | compiler export data. |
| 72 | -mode=allsyntax is like -mode=syntax but applied to all dependencies. |
| 73 | |
| 74 | Flags: |
| 75 | `) |
| 76 | flag.PrintDefaults() |
| 77 | } |
| 78 | |
| 79 | flag.Parse() |
| 80 | if flag.NArg() == 0 { |
| 81 | flag.Usage() |
| 82 | os.Exit(2) |
| 83 | } |
| 84 | |
| 85 | if *cpuprofile != "" { |
| 86 | f, err := os.Create(*cpuprofile) |
| 87 | if err != nil { |
| 88 | log.Fatal(err) |
| 89 | } |
| 90 | pprof.StartCPUProfile(f) |
| 91 | defer pprof.StopCPUProfile() |
| 92 | } |
| 93 | |
| 94 | if *traceprofile != "" { |
| 95 | f, err := os.Create(*traceprofile) |
| 96 | if err != nil { |
| 97 | log.Fatal(err) |
| 98 | } |
| 99 | trace.Start(f) |
| 100 | defer trace.Stop() |
| 101 | } |
| 102 | |
| 103 | if *memprofile != "" { |
| 104 | defer func() { |
| 105 | f, err := os.Create(*memprofile) |
| 106 | if err != nil { |
| 107 | log.Fatal(err) |
| 108 | } |
| 109 | pprof.WriteHeapProfile(f) |
| 110 | f.Close() |
| 111 | }() |
| 112 | } |
| 113 | |
| 114 | if err := run(context.Background(), flag.Args(), *deps, *test, *mode, *tags, *private, *printJSON, *driver, buildFlags); err != nil { |
| 115 | fmt.Fprintf(os.Stderr, "gopackages: %v\n", err) |
| 116 | os.Exit(1) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | func run(ctx context.Context, args []string, deps, test bool, mode, tags string, private, printJSON, driver bool, buildFlags []string) error { |
| 121 | env := os.Environ() |
| 122 | if driver { |
| 123 | env = append(env, drivertest.Env(log.Default())...) |
| 124 | } |
| 125 | |
| 126 | // Load, parse, and type-check the packages named on the command line. |
| 127 | cfg := &packages.Config{ |
| 128 | Mode: packages.LoadSyntax, |
| 129 | Tests: test, |
| 130 | BuildFlags: append([]string{"-tags=" + tags}, buildFlags...), |
| 131 | Env: env, |
| 132 | Context: ctx, |
| 133 | } |
| 134 | |
| 135 | // -mode flag |
| 136 | switch strings.ToLower(mode) { |
| 137 | case "files": |
| 138 | cfg.Mode = packages.LoadFiles |
| 139 | case "imports": |
| 140 | cfg.Mode = packages.LoadImports |
| 141 | case "types": |
| 142 | cfg.Mode = packages.LoadTypes |
| 143 | case "syntax": |
| 144 | cfg.Mode = packages.LoadSyntax |
| 145 | case "allsyntax": |
| 146 | cfg.Mode = packages.LoadAllSyntax |
| 147 | default: |
| 148 | return fmt.Errorf("invalid mode: %s", mode) |
| 149 | } |
| 150 | cfg.Mode |= packages.NeedModule |
| 151 | |
| 152 | lpkgs, err := packages.Load(cfg, args...) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | |
| 157 | // -deps: print dependencies too. |
| 158 | if deps { |
| 159 | // We can't use packages.All because |
| 160 | // we need an ordered traversal. |
| 161 | var all []*packages.Package // postorder |
| 162 | seen := make(map[*packages.Package]bool) |
| 163 | var visit func(*packages.Package) |
| 164 | visit = func(lpkg *packages.Package) { |
| 165 | if !seen[lpkg] { |
| 166 | seen[lpkg] = true |
| 167 | |
| 168 | // visit imports |
| 169 | var importPaths []string |
| 170 | for path := range lpkg.Imports { |
| 171 | importPaths = append(importPaths, path) |
| 172 | } |
| 173 | sort.Strings(importPaths) // for determinism |
| 174 | for _, path := range importPaths { |
| 175 | visit(lpkg.Imports[path]) |
| 176 | } |
| 177 | |
| 178 | all = append(all, lpkg) |
| 179 | } |
| 180 | } |
| 181 | for _, lpkg := range lpkgs { |
| 182 | visit(lpkg) |
| 183 | } |
| 184 | lpkgs = all |
| 185 | } |
| 186 | |
| 187 | for _, lpkg := range lpkgs { |
| 188 | printPkg(lpkg, printJSON, private) |
| 189 | } |
| 190 | return nil |
| 191 | } |
| 192 | |
| 193 | func printPkg(lpkg *packages.Package, printJSON, private bool) { |
| 194 | if printJSON { |
| 195 | data, _ := json.MarshalIndent(lpkg, "", "\t") |
| 196 | os.Stdout.Write(data) |
| 197 | return |
| 198 | } |
| 199 | // title |
| 200 | var kind string |
| 201 | // TODO(matloob): If IsTest is added back print "test command" or |
| 202 | // "test package" for packages with IsTest == true. |
| 203 | if lpkg.Name == "main" { |
| 204 | kind += "command" |
| 205 | } else { |
| 206 | kind += "package" |
| 207 | } |
| 208 | fmt.Printf("Go %s %q:\n", kind, lpkg.ID) // unique ID |
| 209 | if mod := lpkg.Module; mod != nil { |
| 210 | fmt.Printf("\tmodule %s@%s\n", mod.Path, mod.Version) |
| 211 | } |
| 212 | fmt.Printf("\tpackage %s\n", lpkg.Name) |
| 213 | |
| 214 | // characterize type info |
| 215 | if lpkg.Types == nil { |
| 216 | fmt.Printf("\thas no exported type info\n") |
| 217 | } else if !lpkg.Types.Complete() { |
| 218 | fmt.Printf("\thas incomplete exported type info\n") |
| 219 | } else if len(lpkg.Syntax) == 0 { |
| 220 | fmt.Printf("\thas complete exported type info\n") |
| 221 | } else { |
| 222 | fmt.Printf("\thas complete exported type info and typed ASTs\n") |
| 223 | } |
| 224 | if lpkg.Types != nil && lpkg.IllTyped && len(lpkg.Errors) == 0 { |
| 225 | fmt.Printf("\thas an error among its dependencies\n") |
| 226 | } |
| 227 | |
| 228 | // source files |
| 229 | for _, src := range lpkg.GoFiles { |
| 230 | fmt.Printf("\tfile %s\n", src) |
| 231 | } |
| 232 | |
| 233 | // imports |
| 234 | var lines []string |
| 235 | for importPath, imp := range lpkg.Imports { |
| 236 | var line string |
| 237 | if imp.ID == importPath { |
| 238 | line = fmt.Sprintf("\timport %q", importPath) |
| 239 | } else { |
| 240 | line = fmt.Sprintf("\timport %q => %q", importPath, imp.ID) |
| 241 | } |
| 242 | lines = append(lines, line) |
| 243 | } |
| 244 | sort.Strings(lines) |
| 245 | for _, line := range lines { |
| 246 | fmt.Println(line) |
| 247 | } |
| 248 | |
| 249 | // errors |
| 250 | for _, err := range lpkg.Errors { |
| 251 | fmt.Printf("\t%s\n", err) |
| 252 | } |
| 253 | |
| 254 | // types of package members |
| 255 | if lpkg.Types != nil { |
| 256 | qual := types.RelativeTo(lpkg.Types) |
| 257 | scope := lpkg.Types.Scope() |
| 258 | for _, name := range scope.Names() { |
| 259 | obj := scope.Lookup(name) |
| 260 | if !obj.Exported() && !private { |
| 261 | continue // skip unexported names |
| 262 | } |
| 263 | |
| 264 | fmt.Printf("\t%s\n", types.ObjectString(obj, qual)) |
| 265 | if _, ok := obj.(*types.TypeName); ok { |
| 266 | for _, meth := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { |
| 267 | if !meth.Obj().Exported() && !private { |
| 268 | continue // skip unexported names |
| 269 | } |
| 270 | fmt.Printf("\t%s\n", types.SelectionString(meth, qual)) |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | fmt.Println() |
| 277 | } |
| 278 | |
| 279 | // stringListValue is a flag.Value that accumulates strings. |
| 280 | // e.g. --flag=one --flag=two would produce []string{"one", "two"}. |
| 281 | type stringListValue []string |
| 282 | |
| 283 | func (ss *stringListValue) Get() any { return []string(*ss) } |
| 284 | |
| 285 | func (ss *stringListValue) String() string { return fmt.Sprintf("%q", *ss) } |
| 286 | |
| 287 | func (ss *stringListValue) Set(s string) error { *ss = append(*ss, s); return nil } |