Debian Codegraph @

gopls/internal/cmd/stats.go

raw symbols SCIP
1 // Copyright 2023 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 package cmd
6
7 import (
8 "context"
9 "encoding/json"
10 "flag"
11 "fmt"
12 "go/token"
13 "io/fs"
14 "os"
15 "path/filepath"
16 "reflect"
17 "runtime"
18 "strings"
19 "time"
20
21 "golang.org/x/tools/gopls/internal/filecache"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/protocol/command"
24 "golang.org/x/tools/gopls/internal/settings"
25 "golang.org/x/tools/gopls/internal/util/bug"
26 versionpkg "golang.org/x/tools/gopls/internal/version"
27 "golang.org/x/tools/internal/event"
28 )
29
30 type stats struct {
31 app *Application
32
33 Anon bool `flag:"anon" help:"hide any fields that may contain user names, file names, or source code"`
34 }
35
36 func (s *stats) Name() string { return "stats" }
37 func (r *stats) Parent() string { return r.app.Name() }
38 func (s *stats) Usage() string { return "" }
39 func (s *stats) ShortHelp() string { return "print workspace statistics" }
40
41 func (s *stats) DetailedHelp(f *flag.FlagSet) {
42 fmt.Fprint(f.Output(), `
43 Load the workspace for the current directory, and output a JSON summary of
44 workspace information relevant to performance. As a side effect, this command
45 populates the gopls file cache for the current workspace.
46
47 By default, this command may include output that refers to the location or
48 content of user code. When the -anon flag is set, fields that may refer to user
49 code are hidden.
50
51 Example:
52 $ gopls stats -anon
53 `)
54 printFlagDefaults(f)
55 }
56
57 func (s *stats) Run(ctx context.Context, args ...string) error {
58 if s.app.Remote != "" {
59 // stats does not work with -remote.
60 // Other sessions on the daemon may interfere with results.
61 // Additionally, the type assertions in below only work if progress
62 // notifications bypass jsonrpc2 serialization.
63 return fmt.Errorf("the stats subcommand does not work with -remote")
64 }
65
66 if !s.app.Verbose {
67 event.SetExporter(nil) // don't log errors to stderr
68 }
69
70 stats := GoplsStats{
71 GOOS: runtime.GOOS,
72 GOARCH: runtime.GOARCH,
73 GOPLSCACHE: os.Getenv("GOPLSCACHE"),
74 GoVersion: runtime.Version(),
75 GoplsVersion: versionpkg.Version(),
76 GOPACKAGESDRIVER: os.Getenv("GOPACKAGESDRIVER"),
77 }
78
79 opts := s.app.options
80 s.app.options = func(o *settings.Options) {
81 if opts != nil {
82 opts(o)
83 }
84 o.VerboseWorkDoneProgress = true
85 }
86
87 // do executes a timed section of the stats command.
88 do := func(name string, f func() error) (time.Duration, error) {
89 start := time.Now()
90 fmt.Fprintf(os.Stderr, "%-30s", name+"...")
91 if err := f(); err != nil {
92 return time.Since(start), err
93 }
94 d := time.Since(start)
95 fmt.Fprintf(os.Stderr, "done (%v)\n", d)
96 return d, nil
97 }
98
99 var cli *client
100 iwlDuration, err := do("Initializing workspace", func() (err error) {
101 cli, _, err = s.app.connect(ctx)
102 if err != nil {
103 return err
104 }
105 select {
106 case <-cli.iwlDone:
107 case <-ctx.Done():
108 return ctx.Err()
109 }
110 return nil
111 })
112 if err != nil {
113 return err
114 }
115 defer cli.terminate(ctx)
116
117 stats.InitialWorkspaceLoadDuration = fmt.Sprint(iwlDuration)
118
119 // Gather bug reports produced by any process using
120 // this executable and persisted in the cache.
121 do("Gathering bug reports", func() error {
122 stats.CacheDir, stats.BugReports = filecache.BugReports()
123 if stats.BugReports == nil {
124 stats.BugReports = []bug.Bug{} // non-nil for JSON
125 }
126 return nil
127 })
128
129 if _, err := do("Querying memstats", func() error {
130 memStats, err := executeCommand(ctx, cli.server, &protocol.Command{
131 Command: command.MemStats.String(),
132 })
133 if err != nil {
134 return err
135 }
136 stats.MemStats = memStats.(command.MemStatsResult)
137 return nil
138 }); err != nil {
139 return err
140 }
141
142 if _, err := do("Querying workspace stats", func() error {
143 wsStats, err := executeCommand(ctx, cli.server, &protocol.Command{
144 Command: command.WorkspaceStats.String(),
145 })
146 if err != nil {
147 return err
148 }
149 stats.WorkspaceStats = wsStats.(command.WorkspaceStatsResult)
150 return nil
151 }); err != nil {
152 return err
153 }
154
155 if _, err := do("Collecting directory info", func() error {
156 var err error
157 stats.DirStats, err = findDirStats()
158 if err != nil {
159 return err
160 }
161 return nil
162 }); err != nil {
163 return err
164 }
165
166 // Filter JSON output to fields that are consistent with s.Anon.
167 okFields := make(map[string]any)
168 {
169 v := reflect.ValueOf(stats)
170 t := v.Type()
171 for i := 0; i < t.NumField(); i++ {
172 f := t.Field(i)
173 if !token.IsExported(f.Name) {
174 continue
175 }
176 vf := v.FieldByName(f.Name)
177 if s.Anon && f.Tag.Get("anon") != "ok" && !vf.IsZero() {
178 // Fields that can be served with -anon must be explicitly marked as OK.
179 // But, if it's zero value, it's ok to print.
180 continue
181 }
182 okFields[f.Name] = vf.Interface()
183 }
184 }
185 data, err := json.MarshalIndent(okFields, "", " ")
186 if err != nil {
187 return err
188 }
189
190 os.Stdout.Write(data)
191 fmt.Println()
192 return nil
193 }
194
195 // GoplsStats holds information extracted from a gopls session in the current
196 // workspace.
197 //
198 // Fields that should be printed with the -anon flag should be explicitly
199 // marked as `anon:"ok"`. Only fields that cannot refer to user files or code
200 // should be marked as such.
201 type GoplsStats struct {
202 GOOS, GOARCH string `anon:"ok"`
203 GOPLSCACHE string
204 GoVersion string `anon:"ok"`
205 GoplsVersion string `anon:"ok"`
206 GOPACKAGESDRIVER string
207 InitialWorkspaceLoadDuration string `anon:"ok"` // in time.Duration string form
208 CacheDir string
209 BugReports []bug.Bug
210 MemStats command.MemStatsResult `anon:"ok"`
211 WorkspaceStats command.WorkspaceStatsResult `anon:"ok"`
212 DirStats dirStats `anon:"ok"`
213 }
214
215 type dirStats struct {
216 Files int
217 TestdataFiles int
218 GoFiles int
219 ModFiles int
220 Dirs int
221 }
222
223 // findDirStats collects information about the current directory and its
224 // subdirectories.
225 func findDirStats() (dirStats, error) {
226 var ds dirStats
227 err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
228 if err != nil {
229 return err
230 }
231 if d.IsDir() {
232 ds.Dirs++
233 } else {
234 ds.Files++
235 slashed := filepath.ToSlash(path)
236 switch {
237 case strings.Contains(slashed, "/testdata/") || strings.HasPrefix(slashed, "testdata/"):
238 ds.TestdataFiles++
239 case strings.HasSuffix(path, ".go"):
240 ds.GoFiles++
241 case strings.HasSuffix(path, ".mod"):
242 ds.ModFiles++
243 }
244 }
245 return nil
246 })
247 return ds, err
248 }