Debian Codegraph @

go/packages/internal/linecount/linecount.go

raw symbols SCIP
1 // Copyright 2025 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 linecount command shows the number of lines of code in a set of
6 // Go packages plus their dependencies. It serves as a working
7 // illustration of the [packages.Load] operation.
8 //
9 // Example: show gopls' total source line count, and its breakdown
10 // between gopls, x/tools, and the std go/* packages. (The balance
11 // comes from other std packages, other x/ repos, and external
12 // dependencies.)
13 //
14 // $ linecount -mode=total ./gopls
15 // 752124
16 // $ linecount -mode=total -module=golang.org/x/tools/gopls ./gopls
17 // 103519
18 // $ linecount -mode=total -module=golang.org/x/tools ./gopls
19 // 99504
20 // $ linecount -mode=total -prefix=go -module=std ./gopls
21 // 47502
22 //
23 // Example: show the top 5 modules contributing to gopls' source line count:
24 //
25 // $ linecount -mode=module ./gopls | head -n 5
26 // 440274 std
27 // 103519 golang.org/x/tools/gopls
28 // 99504 golang.org/x/tools
29 // 40220 honnef.co/go/tools
30 // 17707 golang.org/x/text
31 //
32 // Example: show the top 3 largest files in the gopls module:
33 //
34 // $ linecount -mode=file -module=golang.org/x/tools/gopls ./gopls | head -n 3
35 // 6841 gopls/internal/protocol/tsprotocol.go
36 // 3769 gopls/internal/golang/completion/completion.go
37 // 2202 gopls/internal/cache/snapshot.go
38 package main
39
40 import (
41 "bytes"
42 "cmp"
43 "flag"
44 "fmt"
45 "go/scanner"
46 "go/token"
47 "log"
48 "os"
49 "path"
50 "slices"
51 "strings"
52 "sync"
53
54 "golang.org/x/sync/errgroup"
55 "golang.org/x/tools/go/packages"
56 )
57
58 // TODO(adonovan): filters:
59 // - exclude generated files (-generated=false)
60 // - exclude non-CompiledGoFiles
61 // - include OtherFiles (asm, etc)
62 // - include tests (needs care to avoid double counting)
63
64 func usage() {
65 // See https://go.dev/issue/63659.
66 fmt.Fprintf(os.Stderr, "Usage: linecount [flags] packages...\n")
67 flag.PrintDefaults()
68 fmt.Fprintf(os.Stderr, `
69 Docs: go doc golang.org/x/tools/go/packages/internal/linecount
70 https://pkg.go.dev/golang.org/x/tools/go/packages/internal/linecount
71 `)
72 }
73
74 func main() {
75 // Parse command line.
76 log.SetPrefix("linecount: ")
77 log.SetFlags(0)
78 var (
79 mode = flag.String("mode", "file", "group lines by 'module', 'package', or 'file', or show only 'total'")
80 prefix = flag.String("prefix", "", "count files only in packages whose path has the specified prefix")
81 onlyModule = flag.String("module", "", "count files only in the specified module")
82 nonblank = flag.Bool("nonblank", false, "count only non-comment, non-blank lines")
83 )
84 flag.Usage = usage
85 flag.Parse()
86 if len(flag.Args()) == 0 {
87 usage()
88 os.Exit(1)
89 }
90
91 // Load packages.
92 cfg := &packages.Config{
93 Mode: packages.NeedName |
94 packages.NeedFiles |
95 packages.NeedImports |
96 packages.NeedDeps |
97 packages.NeedModule,
98 }
99 pkgs, err := packages.Load(cfg, flag.Args()...)
100 if err != nil {
101 log.Fatal(err)
102 }
103 if packages.PrintErrors(pkgs) > 0 {
104 os.Exit(1)
105 }
106
107 // Read files and count lines.
108 var (
109 mu sync.Mutex
110 byFile = make(map[string]int)
111 byPackage = make(map[string]int)
112 byModule = make(map[string]int)
113 )
114 var g errgroup.Group
115 g.SetLimit(20) // file system parallelism level
116 packages.Visit(pkgs, nil, func(p *packages.Package) {
117 pkgpath := p.PkgPath
118 module := "std"
119 if p.Module != nil {
120 module = p.Module.Path
121 }
122 if *prefix != "" && !within(pkgpath, path.Clean(*prefix)) {
123 return
124 }
125 if *onlyModule != "" && module != *onlyModule {
126 return
127 }
128 for _, f := range p.GoFiles {
129 g.Go(func() error {
130 data, err := os.ReadFile(f)
131 if err != nil {
132 return err
133 }
134
135 n := count(*nonblank, data)
136
137 mu.Lock()
138 byFile[f] = n
139 byPackage[pkgpath] += n
140 byModule[module] += n
141 mu.Unlock()
142
143 return nil
144 })
145 }
146 })
147 if err := g.Wait(); err != nil {
148 log.Fatal(err)
149 }
150
151 // Display the result.
152 switch *mode {
153 case "file", "package", "module":
154 var m map[string]int
155 switch *mode {
156 case "file":
157 m = byFile
158 case "package":
159 m = byPackage
160 case "module":
161 m = byModule
162 }
163 type item struct {
164 name string
165 count int
166 }
167 var items []item
168 for name, count := range m {
169 items = append(items, item{name, count})
170 }
171 slices.SortFunc(items, func(x, y item) int {
172 return -cmp.Compare(x.count, y.count)
173 })
174 for _, item := range items {
175 fmt.Printf("%d\t%s\n", item.count, item.name)
176 }
177
178 case "total":
179 total := 0
180 for _, n := range byFile {
181 total += n
182 }
183 fmt.Printf("%d\n", total)
184
185 default:
186 log.Fatalf("invalid -mode %q (want file, package, module, or total)", *mode)
187 }
188 }
189
190 func within(file, dir string) bool {
191 return file == dir ||
192 strings.HasPrefix(file, dir) && file[len(dir)] == os.PathSeparator
193 }
194
195 // count counts lines, or non-comment non-blank lines.
196 func count(nonblank bool, src []byte) int {
197 if nonblank {
198 // Count distinct lines containing tokens.
199 var (
200 fset = token.NewFileSet()
201 f = fset.AddFile("", fset.Base(), len(src))
202 prevLine = 0
203 count = 0
204 scan scanner.Scanner
205 )
206 scan.Init(f, src, nil, 0)
207 for {
208 pos, tok, _ := scan.Scan()
209 if tok == token.EOF {
210 break
211 }
212 // This may be slow because it binary
213 // searches the newline offset table.
214 line := f.PositionFor(pos, false).Line // ignore //line directives
215 if line > prevLine {
216 prevLine = line
217 count++
218 }
219 }
220 return count
221 }
222
223 // Count all lines.
224 return bytes.Count(src, []byte("\n"))
225 }