Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/go/internal/modget

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

View as plain text