-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.go
271 lines (231 loc) · 6.75 KB
/
scan.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package mingo
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/bobg/errors"
"golang.org/x/tools/go/packages"
)
// Scanner scans a directory or set of packages to determine the lowest-numbered version of Go 1.x that can build them.
type Scanner struct {
Deps bool // include dependencies
Indirect bool // with Deps, include indirect dependencies
Verbose bool // be verbose
Tests bool // scan *_test.go files
Check bool // produce an error if the module declares a version in go.mod lower than the computed minimum
Strict bool // with Check, require the go.mod declaration to be equal to the computed minimum
HistDir string // find Go stdlib history in this directory (default: $GOROOT/api)
Result Result
h *history
depScanner depScanner
}
// Mode is the minimum mode needed when using [packages.Load] to scan packages.
const Mode = packages.NeedName | packages.NeedFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedModule
// VersionError is the error returned by [Scanner.ScanDir] or [Scanner.ScanPackages] when [Scanner.Check] is enabled.
type VersionError struct {
Computed Result
Declared int
}
func (e VersionError) Error() string {
return fmt.Sprintf("go.mod declares version 1.%d but computed minimum is 1.%d [%s]", e.Declared, e.Computed.Version(), e.Computed)
}
// LoadError is the error returned by [Scanner.ScanDir] or [Scanner.ScanPackages] when loading packages fails.
type LoadError struct {
Err error
Path string
}
func (e LoadError) Error() string {
return fmt.Sprintf("loading packages in %s: %s", e.Path, e.Err)
}
func (e LoadError) Unwrap() error {
return e.Err
}
// ScanDir scans the module in a directory to determine the lowest-numbered version of Go 1.x that can build it.
func (s *Scanner) ScanDir(dir string) (Result, error) {
if err := s.ensureHistory(); err != nil {
return nil, err
}
conf := &packages.Config{
Mode: Mode,
Dir: dir,
Tests: s.Tests,
}
pkgs, err := packages.Load(conf, "./...")
if err != nil {
return nil, errors.Wrap(err, "loading packages")
}
return s.ScanPackages(pkgs)
}
// ScanPackages scans the given packages to determine the lowest-numbered version of Go 1.x that can build them.
// The packages must all be in the same module.
// When using [packages.Load] to load the packages,
// the value for [packages.Config.Mode] must be at least [Mode].
func (s *Scanner) ScanPackages(pkgs []*packages.Package) (Result, error) {
if err := s.ensureHistory(); err != nil {
return nil, err
}
s.Result = intResult(0)
// Check for loading errors.
var err error
for _, pkg := range pkgs {
for _, e := range pkg.Errors {
err = errors.Join(err, LoadError{Err: e, Path: pkg.PkgPath})
}
}
if err != nil {
return nil, errors.Wrap(err, "loading package(s)")
}
for i, pkg := range pkgs {
if pkg.Module == nil {
return nil, fmt.Errorf("package %s has no module", pkg.PkgPath)
}
if i > 0 && pkg.Module.Path != pkgs[0].Module.Path {
return nil, fmt.Errorf("multiple modules: %s and %s", pkgs[0].Module.Path, pkg.Module.Path)
}
if err := s.scanPackage(pkg); err != nil {
return nil, errors.Wrapf(err, "scanning package %s", pkg.PkgPath)
}
if s.isMax() {
break
}
}
if s.Deps && len(pkgs) > 0 && pkgs[0].Module != nil {
if err := s.scanDeps(pkgs[0].Module.GoMod); err != nil {
return nil, errors.Wrap(err, "scanning dependencies")
}
}
if s.Check && len(pkgs) > 0 {
var declared int
parts := strings.SplitN(pkgs[0].Module.GoVersion, ".", 3)
if len(parts) < 2 {
return nil, fmt.Errorf("go.mod has invalid go version %s", pkgs[0].Module.GoVersion)
}
declared, err := strconv.Atoi(parts[1])
if err != nil {
return nil, fmt.Errorf("go.mod has invalid go version %s", pkgs[0].Module.GoVersion)
}
if s.Strict {
if s.Result.Version() != declared {
return nil, VersionError{
Computed: s.Result,
Declared: declared,
}
}
} else {
if s.Result.Version() > declared {
return nil, VersionError{
Computed: s.Result,
Declared: declared,
}
}
}
}
return s.Result, nil
}
func (s *Scanner) reset() {
s.Result = intResult(0)
}
func (s *Scanner) scanPackage(pkg *packages.Package) error {
return s.scanPackageHelper(pkg.PkgPath, pkg.Fset, pkg.TypesInfo, pkg.Syntax)
}
func (s *Scanner) scanPackageHelper(pkgpath string, fset *token.FileSet, info *types.Info, files []*ast.File) error {
p := pkgScanner{
s: s,
pkgpath: pkgpath,
fset: fset,
info: info,
}
for _, file := range files {
filename := p.fset.Position(file.Pos()).Filename
isInCache, err := isCacheFile(filename)
if err != nil {
return errors.Wrapf(err, "checking whether %s is in GOCACHE", filename)
}
if isInCache {
continue
}
if isMax, err := p.file(file); err != nil || isMax {
return errors.Wrapf(err, "scanning file %s", filename)
}
}
return nil
}
func (s *Scanner) lookup(pkgpath, name, typ string) int {
return s.h.lookup(pkgpath, name, typ)
}
func (s *Scanner) verbosef(format string, args ...any) {
if !s.Verbose {
return
}
fmt.Fprintf(os.Stderr, format, args...)
if !strings.HasSuffix(format, "\n") {
fmt.Fprintln(os.Stderr)
}
}
func (s *Scanner) result(r Result) bool {
if r.Version() > s.Result.Version() {
s.Result = r
s.verbosef("%s", r)
}
return s.isMax()
}
var goverRegex = regexp.MustCompile(`^go(\d+)\.(\d+)`)
func (s *Scanner) ensureHistory() error {
if s.h != nil {
return nil
}
h, err := readHist(s.HistDir)
if err != nil {
return err
}
s.h = h
gover := runtime.Version()
m := goverRegex.FindStringSubmatch(gover)
if len(m) == 0 {
return nil
}
major, err := strconv.Atoi(m[1])
if err != nil {
return errors.Wrapf(err, "parsing major version from runtime version %s", gover)
}
if major != 1 {
return fmt.Errorf("unexpected Go major version %d", major)
}
minor, err := strconv.Atoi(m[2])
if err != nil {
return errors.Wrapf(err, "parsing minor version from runtime version %s", gover)
}
if minor != s.h.max {
return fmt.Errorf("runtime Go version 1.%d does not match history max 1.%d (reading from %s)", minor, s.h.max, s.HistDir)
}
return nil
}
// Prereq: e.ensureHistory has been called.
func (s *Scanner) isMax() bool {
return s.Result.Version() >= s.h.max
}
func isCacheFile(filename string) (bool, error) {
cacheDir := os.Getenv("GOCACHE")
if cacheDir == "" {
var err error
cacheDir, err = os.UserCacheDir()
if err != nil {
return false, errors.Wrap(err, "getting user cache directory")
}
if cacheDir == "" {
return false, nil
}
}
rel, err := filepath.Rel(cacheDir, filename)
if err != nil {
return false, errors.Wrapf(err, "computing relative path from %s to %s", cacheDir, filename)
}
return !strings.HasPrefix(rel, "../"), nil
}