Debian Codegraph @

src/cmd/go/internal/modget/query.go

raw
1 // Copyright 2020 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 modget
6
7 import (
8 "fmt"
9 "path/filepath"
10 "regexp"
11 "strings"
12 "sync"
13
14 "cmd/go/internal/base"
15 "cmd/go/internal/gover"
16 "cmd/go/internal/modload"
17 "cmd/go/internal/search"
18 "cmd/go/internal/str"
19 "cmd/internal/pkgpattern"
20
21 "golang.org/x/mod/module"
22 )
23
24 // A query describes a command-line argument and the modules and/or packages
25 // to which that argument may resolve..
26 type query struct {
27 // raw is the original argument, to be printed in error messages.
28 raw string
29
30 // rawVersion is the portion of raw corresponding to version, if any
31 rawVersion string
32
33 // pattern is the part of the argument before "@" (or the whole argument
34 // if there is no "@"), which may match either packages (preferred) or
35 // modules (if no matching packages).
36 //
37 // The pattern may also be "-u", for the synthetic query representing the -u
38 // (“upgrade”)flag.
39 pattern string
40
41 // patternIsLocal indicates whether pattern is restricted to match only paths
42 // local to the main module, such as absolute filesystem paths or paths
43 // beginning with './'.
44 //
45 // A local pattern must resolve to one or more packages in the main module.
46 patternIsLocal bool
47
48 // version is the part of the argument after "@", or an implied
49 // "upgrade" or "patch" if there is no "@". version specifies the
50 // module version to get.
51 version string
52
53 // matchWildcard, if non-nil, reports whether pattern, which must be a
54 // wildcard (with the substring "..."), matches the given package or module
55 // path.
56 matchWildcard func(path string) bool
57
58 // canMatchWildcardInModule, if non-nil, reports whether the module with the given
59 // path could lexically contain a package matching pattern, which must be a
60 // wildcard.
61 canMatchWildcardInModule func(mPath string) bool
62
63 // conflict is the first query identified as incompatible with this one.
64 // conflict forces one or more of the modules matching this query to a
65 // version that does not match version.
66 conflict *query
67
68 // candidates is a list of sets of alternatives for a path that matches (or
69 // contains packages that match) the pattern. The query can be resolved by
70 // choosing exactly one alternative from each set in the list.
71 //
72 // A path-literal query results in only one set: the path itself, which
73 // may resolve to either a package path or a module path.
74 //
75 // A wildcard query results in one set for each matching module path, each
76 // module for which the matching version contains at least one matching
77 // package, and (if no other modules match) one candidate set for the pattern
78 // overall if no existing match is identified in the build list.
79 //
80 // A query for pattern "all" results in one set for each package transitively
81 // imported by the main module.
82 //
83 // The special query for the "-u" flag results in one set for each
84 // otherwise-unconstrained package that has available upgrades.
85 candidates []pathSet
86 candidatesMu sync.Mutex
87
88 // pathSeen ensures that only one pathSet is added to the query per
89 // unique path.
90 pathSeen sync.Map
91
92 // resolved contains the set of modules whose versions have been determined by
93 // this query, in the order in which they were determined.
94 //
95 // The resolver examines the candidate sets for each query, resolving one
96 // module per candidate set in a way that attempts to avoid obvious conflicts
97 // between the versions resolved by different queries.
98 resolved []module.Version
99
100 // matchesPackages is true if the resolved modules provide at least one
101 // package matching q.pattern.
102 matchesPackages bool
103 }
104
105 // A pathSet describes the possible options for resolving a specific path
106 // to a package and/or module.
107 type pathSet struct {
108 // path is a package (if "all" or "-u" or a non-wildcard) or module (if
109 // wildcard) path that could be resolved by adding any of the modules in this
110 // set. For a wildcard pattern that so far matches no packages, the path is
111 // the wildcard pattern itself.
112 //
113 // Each path must occur only once in a query's candidate sets, and the path is
114 // added implicitly to each pathSet returned to pathOnce.
115 path string
116
117 // pkgMods is a set of zero or more modules, each of which contains the
118 // package with the indicated path. Due to the requirement that imports be
119 // unambiguous, only one such module can be in the build list, and all others
120 // must be excluded.
121 pkgMods []module.Version
122
123 // mod is either the zero Version, or a module that does not contain any
124 // packages matching the query but for which the module path itself
125 // matches the query pattern.
126 //
127 // We track this module separately from pkgMods because, all else equal, we
128 // prefer to match a query to a package rather than just a module. Also,
129 // unlike the modules in pkgMods, this module does not inherently exclude
130 // any other module in pkgMods.
131 mod module.Version
132
133 err error
134 }
135
136 // errSet returns a pathSet containing the given error.
137 func errSet(err error) pathSet { return pathSet{err: err} }
138
139 // newQuery returns a new query parsed from the raw argument,
140 // which must be either path or path@version.
141 func newQuery(raw string) (*query, error) {
142 pattern, rawVers, found, err := modload.ParsePathVersion(raw)
143 if err != nil {
144 return nil, err
145 }
146 if found && (strings.Contains(rawVers, "@") || rawVers == "") {
147 return nil, fmt.Errorf("invalid module version syntax %q", raw)
148 }
149
150 // If no version suffix is specified, assume @upgrade.
151 // If -u=patch was specified, assume @patch instead.
152 version := rawVers
153 if version == "" {
154 if getU.version == "" {
155 version = "upgrade"
156 } else {
157 version = getU.version
158 }
159 }
160
161 q := &query{
162 raw: raw,
163 rawVersion: rawVers,
164 pattern: pattern,
165 patternIsLocal: filepath.IsAbs(pattern) || search.IsRelativePath(pattern),
166 version: version,
167 }
168 if strings.Contains(q.pattern, "...") {
169 q.matchWildcard = pkgpattern.MatchPattern(q.pattern)
170 q.canMatchWildcardInModule = pkgpattern.TreeCanMatchPattern(q.pattern)
171 }
172 if err := q.validate(); err != nil {
173 return q, err
174 }
175 return q, nil
176 }
177
178 // validate reports a non-nil error if q is not sensible and well-formed.
179 func (q *query) validate() error {
180 if q.patternIsLocal {
181 if q.rawVersion != "" {
182 return fmt.Errorf("can't request explicit version %q of path %q in main module", q.rawVersion, q.pattern)
183 }
184 return nil
185 }
186
187 if q.pattern == "all" {
188 // If there is no main module, "all" is not meaningful.
189 if !modload.HasModRoot() {
190 return fmt.Errorf(`cannot match "all": %v`, modload.ErrNoModRoot)
191 }
192 if !versionOkForMainModule(q.version) {
193 // TODO(bcmills): "all@none" seems like a totally reasonable way to
194 // request that we remove all module requirements, leaving only the main
195 // module and standard library. Perhaps we should implement that someday.
196 return &modload.QueryUpgradesAllError{
197 MainModules: modload.MainModules.Versions(),
198 Query: q.version,
199 }
200 }
201 }
202
203 if search.IsMetaPackage(q.pattern) && q.pattern != "all" {
204 if q.pattern != q.raw {
205 if q.pattern == "tool" {
206 return fmt.Errorf("can't request explicit version of \"tool\" pattern")
207 }
208 return fmt.Errorf("can't request explicit version of standard-library pattern %q", q.pattern)
209 }
210 }
211
212 return nil
213 }
214
215 // String returns the original argument from which q was parsed.
216 func (q *query) String() string { return q.raw }
217
218 // ResolvedString returns a string describing m as a resolved match for q.
219 func (q *query) ResolvedString(m module.Version) string {
220 if m.Path != q.pattern {
221 if m.Version != q.version {
222 return fmt.Sprintf("%v (matching %s@%s)", m, q.pattern, q.version)
223 }
224 return fmt.Sprintf("%v (matching %v)", m, q)
225 }
226 if m.Version != q.version {
227 return fmt.Sprintf("%s@%s (%s)", q.pattern, q.version, m.Version)
228 }
229 return q.String()
230 }
231
232 // isWildcard reports whether q is a pattern that can match multiple paths.
233 func (q *query) isWildcard() bool {
234 return q.matchWildcard != nil || (q.patternIsLocal && strings.Contains(q.pattern, "..."))
235 }
236
237 // matchesPath reports whether the given path matches q.pattern.
238 func (q *query) matchesPath(path string) bool {
239 if q.matchWildcard != nil && !gover.IsToolchain(path) {
240 return q.matchWildcard(path)
241 }
242 return path == q.pattern
243 }
244
245 // canMatchInModule reports whether the given module path can potentially
246 // contain q.pattern.
247 func (q *query) canMatchInModule(mPath string) bool {
248 if gover.IsToolchain(mPath) {
249 return false
250 }
251 if q.canMatchWildcardInModule != nil {
252 return q.canMatchWildcardInModule(mPath)
253 }
254 return str.HasPathPrefix(q.pattern, mPath)
255 }
256
257 // pathOnce invokes f to generate the pathSet for the given path,
258 // if one is still needed.
259 //
260 // Note that, unlike sync.Once, pathOnce does not guarantee that a concurrent
261 // call to f for the given path has completed on return.
262 //
263 // pathOnce is safe for concurrent use by multiple goroutines, but note that
264 // multiple concurrent calls will result in the sets being added in
265 // nondeterministic order.
266 func (q *query) pathOnce(path string, f func() pathSet) {
267 if _, dup := q.pathSeen.LoadOrStore(path, nil); dup {
268 return
269 }
270
271 cs := f()
272
273 if len(cs.pkgMods) > 0 || cs.mod != (module.Version{}) || cs.err != nil {
274 cs.path = path
275 q.candidatesMu.Lock()
276 q.candidates = append(q.candidates, cs)
277 q.candidatesMu.Unlock()
278 }
279 }
280
281 // reportError logs err concisely using base.Errorf.
282 func reportError(q *query, err error) {
283 errStr := err.Error()
284
285 // If err already mentions all of the relevant parts of q, just log err to
286 // reduce stutter. Otherwise, log both q and err.
287 //
288 // TODO(bcmills): Use errors.As to unpack these errors instead of parsing
289 // strings with regular expressions.
290
291 patternRE := regexp.MustCompile("(?m)(?:[ \t(\"`]|^)" + regexp.QuoteMeta(q.pattern) + "(?:[ @:;)\"`]|$)")
292 if patternRE.MatchString(errStr) {
293 if q.rawVersion == "" {
294 base.Errorf("go: %s", errStr)
295 return
296 }
297
298 versionRE := regexp.MustCompile("(?m)(?:[ @(\"`]|^)" + regexp.QuoteMeta(q.version) + "(?:[ :;)\"`]|$)")
299 if versionRE.MatchString(errStr) {
300 base.Errorf("go: %s", errStr)
301 return
302 }
303 }
304
305 if qs := q.String(); qs != "" {
306 base.Errorf("go: %s: %s", qs, errStr)
307 } else {
308 base.Errorf("go: %s", errStr)
309 }
310 }
311
312 func reportConflict(pq *query, m module.Version, conflict versionReason) {
313 if pq.conflict != nil {
314 // We've already reported a conflict for the proposed query.
315 // Don't report it again, even if it has other conflicts.
316 return
317 }
318 pq.conflict = conflict.reason
319
320 proposed := versionReason{
321 version: m.Version,
322 reason: pq,
323 }
324 if pq.isWildcard() && !conflict.reason.isWildcard() {
325 // Prefer to report the specific path first and the wildcard second.
326 proposed, conflict = conflict, proposed
327 }
328 reportError(pq, &conflictError{
329 mPath: m.Path,
330 proposed: proposed,
331 conflict: conflict,
332 })
333 }
334
335 type conflictError struct {
336 mPath string
337 proposed versionReason
338 conflict versionReason
339 }
340
341 func (e *conflictError) Error() string {
342 argStr := func(q *query, v string) string {
343 if v != q.version {
344 return fmt.Sprintf("%s@%s (%s)", q.pattern, q.version, v)
345 }
346 return q.String()
347 }
348
349 pq := e.proposed.reason
350 rq := e.conflict.reason
351 modDetail := ""
352 if e.mPath != pq.pattern {
353 modDetail = fmt.Sprintf("for module %s, ", e.mPath)
354 }
355
356 return fmt.Sprintf("%s%s conflicts with %s",
357 modDetail,
358 argStr(pq, e.proposed.version),
359 argStr(rq, e.conflict.version))
360 }
361
362 func versionOkForMainModule(version string) bool {
363 return version == "upgrade" || version == "patch"
364 }