Debian Codegraph @

internal/cmd/unused/unused.go

raw
1 package main
2
3 import (
4 "flag"
5 "fmt"
6 "log"
7 "os"
8
9 "golang.org/x/tools/go/packages"
10 "honnef.co/go/tools/go/loader"
11 "honnef.co/go/tools/unused"
12 )
13
14 // OPT(dh): we don't need full graph merging if we're not flagging exported objects. In that case, we can reuse the old
15 // list-based merging approach.
16
17 // OPT(dh): we can either merge graphs as we process packages, or we can merge them all in one go afterwards (then
18 // reloading them from cache). The first approach will likely lead to higher peak memory usage, but the latter may take
19 // more wall time to finish if we had spare CPU resources while processing packages.
20
21 func main() {
22 opts := unused.DefaultOptions
23 flag.BoolVar(&opts.FieldWritesAreUses, "field-writes-are-uses", opts.FieldWritesAreUses, "")
24 flag.BoolVar(&opts.PostStatementsAreReads, "post-statements-are-reads", opts.PostStatementsAreReads, "")
25 flag.BoolVar(&opts.ExportedIsUsed, "exported-is-used", opts.ExportedIsUsed, "")
26 flag.BoolVar(&opts.ExportedFieldsAreUsed, "exported-fields-are-used", opts.ExportedFieldsAreUsed, "")
27 flag.BoolVar(&opts.ParametersAreUsed, "parameters-are-used", opts.ParametersAreUsed, "")
28 flag.BoolVar(&opts.LocalVariablesAreUsed, "local-variables-are-used", opts.LocalVariablesAreUsed, "")
29 flag.BoolVar(&opts.GeneratedIsUsed, "generated-is-used", opts.GeneratedIsUsed, "")
30 flag.Parse()
31
32 // pprof.StartCPUProfile(os.Stdout)
33 // defer pprof.StopCPUProfile()
34
35 // XXX set cache key for this tool
36
37 cfg := &packages.Config{
38 Tests: true,
39 }
40 specs, err := loader.Graph(cfg, flag.Args()...)
41 if err != nil {
42 log.Fatal(err)
43 }
44
45 var sg unused.SerializedGraph
46
47 ourPkgs := map[string]struct{}{}
48
49 for _, spec := range specs {
50 if len(spec.Errors) != 0 {
51 // XXX priunt errors
52 continue
53 }
54 lpkg, _, err := loader.Load(spec, nil)
55 if err != nil {
56 continue
57 }
58 if len(lpkg.Errors) != 0 {
59 continue
60 }
61
62 // XXX get directives and generated
63 g := unused.Graph(lpkg.Fset, lpkg.Syntax, lpkg.Types, lpkg.TypesInfo, nil, nil, opts)
64 sg.Merge(g)
65 ourPkgs[spec.PkgPath] = struct{}{}
66 }
67
68 res := sg.Results()
69 for _, obj := range res.Unused {
70 // XXX format paths like staticcheck does
71 if _, ok := ourPkgs[obj.Path.PkgPath]; !ok {
72 continue
73 }
74 fmt.Printf("%s: %s %s is unused\n", obj.DisplayPosition, obj.Kind, obj.Name)
75 }
76
77 fmt.Fprintln(os.Stderr, sg.Dot())
78 }