forked from golang/tools
/
main.go
251 lines (222 loc) · 6.06 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The gopackages command is a diagnostic tool that demonstrates
// how to use golang.org/x/tools/go/packages to load, parse,
// type-check, and print one or more Go packages.
// Its precise output is unspecified and may change.
package main
import (
"encoding/json"
"flag"
"fmt"
"go/types"
"log"
"os"
"runtime"
"runtime/pprof"
"runtime/trace"
"sort"
"strings"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
)
// flags
var (
depsFlag = flag.Bool("deps", false, "show dependencies too")
testFlag = flag.Bool("test", false, "include any tests implied by the patterns")
mode = flag.String("mode", "imports", "mode (one of files, imports, types, syntax, allsyntax)")
private = flag.Bool("private", false, "show non-exported declarations too")
printJSON = flag.Bool("json", false, "print package in JSON form")
cpuprofile = flag.String("cpuprofile", "", "write CPU profile to this file")
memprofile = flag.String("memprofile", "", "write memory profile to this file")
traceFlag = flag.String("trace", "", "write trace log to this file")
)
func usage() {
fmt.Fprintln(os.Stderr, `Usage: gopackages [-deps] [-cgo] [-mode=...] [-private] package...
The gopackages command loads, parses, type-checks,
and prints one or more Go packages.
Packages are specified using the notation of "go list",
or other underlying build system.
Flags:`)
flag.PrintDefaults()
}
func main() {
log.SetPrefix("gopackages: ")
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
if len(flag.Args()) == 0 {
usage()
os.Exit(1)
}
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal(err)
}
// NB: profile won't be written in case of error.
defer pprof.StopCPUProfile()
}
if *traceFlag != "" {
f, err := os.Create(*traceFlag)
if err != nil {
log.Fatal(err)
}
if err := trace.Start(f); err != nil {
log.Fatal(err)
}
// NB: trace log won't be written in case of error.
defer func() {
trace.Stop()
log.Printf("To view the trace, run:\n$ go tool trace view %s", *traceFlag)
}()
}
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal(err)
}
// NB: memprofile won't be written in case of error.
defer func() {
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatalf("Writing memory profile: %v", err)
}
f.Close()
}()
}
// Load, parse, and type-check the packages named on the command line.
cfg := &packages.Config{
Mode: packages.LoadSyntax,
Error: func(error) {}, // we'll take responsibility for printing errors
Tests: *testFlag,
}
// -mode flag
switch strings.ToLower(*mode) {
case "files":
cfg.Mode = packages.LoadFiles
case "imports":
cfg.Mode = packages.LoadImports
case "types":
cfg.Mode = packages.LoadTypes
case "syntax":
cfg.Mode = packages.LoadSyntax
case "allsyntax":
cfg.Mode = packages.LoadAllSyntax
default:
log.Fatalf("invalid mode: %s", *mode)
}
lpkgs, err := packages.Load(cfg, flag.Args()...)
if err != nil {
log.Fatal(err)
}
// -deps: print dependencies too.
if *depsFlag {
// We can't use packages.All because
// we need an ordered traversal.
var all []*packages.Package // postorder
seen := make(map[*packages.Package]bool)
var visit func(*packages.Package)
visit = func(lpkg *packages.Package) {
if !seen[lpkg] {
seen[lpkg] = true
// visit imports
var importPaths []string
for path := range lpkg.Imports {
importPaths = append(importPaths, path)
}
sort.Strings(importPaths) // for determinism
for _, path := range importPaths {
visit(lpkg.Imports[path])
}
all = append(all, lpkg)
}
}
for _, lpkg := range lpkgs {
visit(lpkg)
}
lpkgs = all
}
for _, lpkg := range lpkgs {
print(lpkg)
}
}
func print(lpkg *packages.Package) {
if *printJSON {
data, _ := json.MarshalIndent(lpkg, "", "\t")
os.Stdout.Write(data)
return
}
// title
var kind string
// TODO(matloob): If IsTest is added back print "test command" or
// "test package" for packages with IsTest == true.
if lpkg.Name == "main" {
kind += "command"
} else {
kind += "package"
}
fmt.Printf("Go %s %q:\n", kind, lpkg.ID) // unique ID
fmt.Printf("\tpackage %s\n", lpkg.Name)
// characterize type info
if lpkg.Types == nil {
fmt.Printf("\thas no exported type info\n")
} else if !lpkg.Types.Complete() {
fmt.Printf("\thas incomplete exported type info\n")
} else if len(lpkg.Syntax) == 0 {
fmt.Printf("\thas complete exported type info\n")
} else {
fmt.Printf("\thas complete exported type info and typed ASTs\n")
}
if lpkg.Types != nil && lpkg.IllTyped && len(lpkg.Errors) == 0 {
fmt.Printf("\thas an error among its dependencies\n")
}
// source files
for _, src := range lpkg.GoFiles {
fmt.Printf("\tfile %s\n", src)
}
// imports
var lines []string
for importPath, imp := range lpkg.Imports {
var line string
if imp.ID == importPath {
line = fmt.Sprintf("\timport %q", importPath)
} else {
line = fmt.Sprintf("\timport %q => %q", importPath, imp.ID)
}
lines = append(lines, line)
}
sort.Strings(lines)
for _, line := range lines {
fmt.Println(line)
}
// errors
for _, err := range lpkg.Errors {
fmt.Printf("\t%s\n", err)
}
// package members (TypeCheck or WholeProgram mode)
if lpkg.Types != nil {
qual := types.RelativeTo(lpkg.Types)
scope := lpkg.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() && !*private {
continue // skip unexported names
}
fmt.Printf("\t%s\n", types.ObjectString(obj, qual))
if _, ok := obj.(*types.TypeName); ok {
for _, meth := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
if !meth.Obj().Exported() && !*private {
continue // skip unexported names
}
fmt.Printf("\t%s\n", types.SelectionString(meth, qual))
}
}
}
}
fmt.Println()
}