Source file src/cmd/go/internal/modfetch/coderepo.go

     1  // Copyright 2018 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 modfetch
     6  
     7  import (
     8  	"archive/zip"
     9  	"bytes"
    10  	"context"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"io/fs"
    15  	"os"
    16  	"path"
    17  	"path/filepath"
    18  	"sort"
    19  	"strings"
    20  	"time"
    21  
    22  	"cmd/go/internal/gover"
    23  	"cmd/go/internal/modfetch/codehost"
    24  
    25  	"golang.org/x/mod/modfile"
    26  	"golang.org/x/mod/module"
    27  	"golang.org/x/mod/semver"
    28  	modzip "golang.org/x/mod/zip"
    29  )
    30  
    31  // A codeRepo implements modfetch.Repo using an underlying codehost.Repo.
    32  type codeRepo struct {
    33  	modPath string
    34  
    35  	// code is the repository containing this module.
    36  	code codehost.Repo
    37  	// codeRoot is the import path at the root of code.
    38  	codeRoot string
    39  	// codeDir is the directory (relative to root) at which we expect to find the module.
    40  	// If pathMajor is non-empty and codeRoot is not the full modPath,
    41  	// then we look in both codeDir and codeDir/pathMajor[1:].
    42  	codeDir string
    43  
    44  	// pathMajor is the suffix of modPath that indicates its major version,
    45  	// or the empty string if modPath is at major version 0 or 1.
    46  	//
    47  	// pathMajor is typically of the form "/vN", but possibly ".vN", or
    48  	// ".vN-unstable" for modules resolved using gopkg.in.
    49  	pathMajor string
    50  	// pathPrefix is the prefix of modPath that excludes pathMajor.
    51  	// It is used only for logging.
    52  	pathPrefix string
    53  
    54  	// pseudoMajor is the major version prefix to require when generating
    55  	// pseudo-versions for this module, derived from the module path. pseudoMajor
    56  	// is empty if the module path does not include a version suffix (that is,
    57  	// accepts either v0 or v1).
    58  	pseudoMajor string
    59  }
    60  
    61  // newCodeRepo returns a Repo that reads the source code for the module with the
    62  // given path, from the repo stored in code.
    63  // codeRoot gives the import path corresponding to the root of the repository,
    64  // and subdir gives the subdirectory within the repo containing the module.
    65  // If subdir is empty, the module is at the root of the repo.
    66  func newCodeRepo(code codehost.Repo, codeRoot, subdir, path string) (Repo, error) {
    67  	if !hasPathPrefix(path, codeRoot) {
    68  		return nil, fmt.Errorf("mismatched repo: found %s for %s", codeRoot, path)
    69  	}
    70  	pathPrefix, pathMajor, ok := module.SplitPathVersion(path)
    71  	if !ok {
    72  		return nil, fmt.Errorf("invalid module path %q", path)
    73  	}
    74  	if codeRoot == path {
    75  		pathPrefix = path
    76  	}
    77  	pseudoMajor := module.PathMajorPrefix(pathMajor)
    78  
    79  	// Compute codeDir = bar, the subdirectory within the repo
    80  	// corresponding to the module root.
    81  	//
    82  	// At this point we might have:
    83  	//	path = github.com/rsc/foo/bar/v2
    84  	//	codeRoot = github.com/rsc/foo
    85  	//	pathPrefix = github.com/rsc/foo/bar
    86  	//	pathMajor = /v2
    87  	//	pseudoMajor = v2
    88  	//
    89  	// which gives
    90  	//	codeDir = bar
    91  	//
    92  	// We know that pathPrefix is a prefix of path, and codeRoot is a prefix of
    93  	// path, but codeRoot may or may not be a prefix of pathPrefix, because
    94  	// codeRoot may be the entire path (in which case codeDir should be empty).
    95  	// That occurs in two situations.
    96  	//
    97  	// One is when a go-import meta tag resolves the complete module path,
    98  	// including the pathMajor suffix:
    99  	//	path = nanomsg.org/go/mangos/v2
   100  	//	codeRoot = nanomsg.org/go/mangos/v2
   101  	//	pathPrefix = nanomsg.org/go/mangos
   102  	//	pathMajor = /v2
   103  	//	pseudoMajor = v2
   104  	//
   105  	// The other is similar: for gopkg.in only, the major version is encoded
   106  	// with a dot rather than a slash, and thus can't be in a subdirectory.
   107  	//	path = gopkg.in/yaml.v2
   108  	//	codeRoot = gopkg.in/yaml.v2
   109  	//	pathPrefix = gopkg.in/yaml
   110  	//	pathMajor = .v2
   111  	//	pseudoMajor = v2
   112  	//
   113  	// Starting in 1.25, subdir may be passed in by the go-import meta tag.
   114  	// So it may be the case that:
   115  	//	path = github.com/rsc/foo/v2
   116  	//	codeRoot = github.com/rsc/foo
   117  	//	subdir = bar/subdir
   118  	//	pathPrefix = github.com/rsc/foo
   119  	//	pathMajor = /v2
   120  	//	pseudoMajor = v2
   121  	// which means that codeDir = bar/subdir
   122  
   123  	codeDir := ""
   124  	if codeRoot != path {
   125  		if !hasPathPrefix(pathPrefix, codeRoot) {
   126  			return nil, fmt.Errorf("repository rooted at %s cannot contain module %s", codeRoot, path)
   127  		}
   128  		codeDir = strings.Trim(pathPrefix[len(codeRoot):], "/")
   129  	}
   130  	if subdir != "" {
   131  		codeDir = filepath.ToSlash(filepath.Join(codeDir, subdir))
   132  	}
   133  
   134  	r := &codeRepo{
   135  		modPath:     path,
   136  		code:        code,
   137  		codeRoot:    codeRoot,
   138  		codeDir:     codeDir,
   139  		pathPrefix:  pathPrefix,
   140  		pathMajor:   pathMajor,
   141  		pseudoMajor: pseudoMajor,
   142  	}
   143  
   144  	return r, nil
   145  }
   146  
   147  func (r *codeRepo) ModulePath() string {
   148  	return r.modPath
   149  }
   150  
   151  func (r *codeRepo) CheckReuse(ctx context.Context, old *codehost.Origin) error {
   152  	return r.code.CheckReuse(ctx, old, r.codeDir)
   153  }
   154  
   155  func (r *codeRepo) Versions(ctx context.Context, prefix string) (*Versions, error) {
   156  	// Special case: gopkg.in/macaroon-bakery.v2-unstable
   157  	// does not use the v2 tags (those are for macaroon-bakery.v2).
   158  	// It has no possible tags at all.
   159  	if strings.HasPrefix(r.modPath, "gopkg.in/") && strings.HasSuffix(r.modPath, "-unstable") {
   160  		return &Versions{}, nil
   161  	}
   162  
   163  	p := prefix
   164  	if r.codeDir != "" {
   165  		p = r.codeDir + "/" + p
   166  	}
   167  	tags, err := r.code.Tags(ctx, p)
   168  	if err != nil {
   169  		return nil, &module.ModuleError{
   170  			Path: r.modPath,
   171  			Err:  err,
   172  		}
   173  	}
   174  	if tags.Origin != nil {
   175  		tags.Origin.Subdir = r.codeDir
   176  	}
   177  
   178  	var list, incompatible []string
   179  	for _, tag := range tags.List {
   180  		if !strings.HasPrefix(tag.Name, p) {
   181  			continue
   182  		}
   183  		v := tag.Name
   184  		if r.codeDir != "" {
   185  			v = v[len(r.codeDir)+1:]
   186  		}
   187  		// Note: ./codehost/codehost.go's isOriginTag knows about these conditions too.
   188  		// If these are relaxed, isOriginTag will need to be relaxed as well.
   189  		if v == "" || v != semver.Canonical(v) {
   190  			// Ignore non-canonical tags: Stat rewrites those to canonical
   191  			// pseudo-versions. Note that we compare against semver.Canonical here
   192  			// instead of module.CanonicalVersion: revToRev strips "+incompatible"
   193  			// suffixes before looking up tags, so a tag like "v2.0.0+incompatible"
   194  			// would not resolve at all. (The Go version string "v2.0.0+incompatible"
   195  			// refers to the "v2.0.0" version tag, which we handle below.)
   196  			continue
   197  		}
   198  		if module.IsPseudoVersion(v) {
   199  			// Ignore tags that look like pseudo-versions: Stat rewrites those
   200  			// unambiguously to the underlying commit, and tagToVersion drops them.
   201  			continue
   202  		}
   203  
   204  		if err := module.CheckPathMajor(v, r.pathMajor); err != nil {
   205  			if r.codeDir == "" && r.pathMajor == "" && semver.Major(v) > "v1" {
   206  				incompatible = append(incompatible, v)
   207  			}
   208  			continue
   209  		}
   210  
   211  		list = append(list, v)
   212  	}
   213  	semver.Sort(list)
   214  	semver.Sort(incompatible)
   215  
   216  	return r.appendIncompatibleVersions(ctx, tags.Origin, list, incompatible)
   217  }
   218  
   219  // appendIncompatibleVersions appends "+incompatible" versions to list if
   220  // appropriate, returning the final list.
   221  //
   222  // The incompatible list contains candidate versions without the '+incompatible'
   223  // prefix.
   224  //
   225  // Both list and incompatible must be sorted in semantic order.
   226  func (r *codeRepo) appendIncompatibleVersions(ctx context.Context, origin *codehost.Origin, list, incompatible []string) (*Versions, error) {
   227  	versions := &Versions{
   228  		Origin: origin,
   229  		List:   list,
   230  	}
   231  	if len(incompatible) == 0 || r.pathMajor != "" {
   232  		// No +incompatible versions are possible, so no need to check them.
   233  		return versions, nil
   234  	}
   235  
   236  	versionHasGoMod := func(v string) (bool, error) {
   237  		_, err := r.code.ReadFile(ctx, v, "go.mod", codehost.MaxGoMod)
   238  		if err == nil {
   239  			return true, nil
   240  		}
   241  		if !os.IsNotExist(err) {
   242  			return false, &module.ModuleError{
   243  				Path: r.modPath,
   244  				Err:  err,
   245  			}
   246  		}
   247  		return false, nil
   248  	}
   249  
   250  	if len(list) > 0 {
   251  		ok, err := versionHasGoMod(list[len(list)-1])
   252  		if err != nil {
   253  			return nil, err
   254  		}
   255  		if ok {
   256  			// The latest compatible version has a go.mod file, so assume that all
   257  			// subsequent versions do as well, and do not include any +incompatible
   258  			// versions. Even if we are wrong, the author clearly intends module
   259  			// consumers to be on the v0/v1 line instead of a higher +incompatible
   260  			// version. (See https://golang.org/issue/34189.)
   261  			//
   262  			// We know of at least two examples where this behavior is desired
   263  			// (github.com/russross/blackfriday@v2.0.0 and
   264  			// github.com/libp2p/go-libp2p@v6.0.23), and (as of 2019-10-29) have no
   265  			// concrete examples for which it is undesired.
   266  			return versions, nil
   267  		}
   268  	}
   269  
   270  	var (
   271  		lastMajor         string
   272  		lastMajorHasGoMod bool
   273  	)
   274  	for i, v := range incompatible {
   275  		major := semver.Major(v)
   276  
   277  		if major != lastMajor {
   278  			rem := incompatible[i:]
   279  			j := sort.Search(len(rem), func(j int) bool {
   280  				return semver.Major(rem[j]) != major
   281  			})
   282  			latestAtMajor := rem[j-1]
   283  
   284  			var err error
   285  			lastMajor = major
   286  			lastMajorHasGoMod, err = versionHasGoMod(latestAtMajor)
   287  			if err != nil {
   288  				return nil, err
   289  			}
   290  		}
   291  
   292  		if lastMajorHasGoMod {
   293  			// The latest release of this major version has a go.mod file, so it is
   294  			// not allowed as +incompatible. It would be confusing to include some
   295  			// minor versions of this major version as +incompatible but require
   296  			// semantic import versioning for others, so drop all +incompatible
   297  			// versions for this major version.
   298  			//
   299  			// If we're wrong about a minor version in the middle, users will still be
   300  			// able to 'go get' specific tags for that version explicitly — they just
   301  			// won't appear in 'go list' or as the results for queries with inequality
   302  			// bounds.
   303  			continue
   304  		}
   305  		versions.List = append(versions.List, v+"+incompatible")
   306  	}
   307  
   308  	return versions, nil
   309  }
   310  
   311  func (r *codeRepo) Stat(ctx context.Context, rev string) (*RevInfo, error) {
   312  	if rev == "latest" {
   313  		return r.Latest(ctx)
   314  	}
   315  	codeRev := r.revToRev(rev)
   316  	info, err := r.code.Stat(ctx, codeRev)
   317  	if err != nil {
   318  		// Note: info may be non-nil to supply Origin for caching error.
   319  		var revInfo *RevInfo
   320  		if info != nil {
   321  			revInfo = &RevInfo{
   322  				Origin:  info.Origin,
   323  				Version: rev,
   324  			}
   325  		}
   326  		return revInfo, &module.ModuleError{
   327  			Path: r.modPath,
   328  			Err: &module.InvalidVersionError{
   329  				Version: rev,
   330  				Err:     err,
   331  			},
   332  		}
   333  	}
   334  	return r.convert(ctx, info, rev)
   335  }
   336  
   337  func (r *codeRepo) Latest(ctx context.Context) (*RevInfo, error) {
   338  	info, err := r.code.Latest(ctx)
   339  	if err != nil {
   340  		if info != nil {
   341  			return &RevInfo{Origin: info.Origin}, err
   342  		}
   343  		return nil, err
   344  	}
   345  	return r.convert(ctx, info, "")
   346  }
   347  
   348  // convert converts a version as reported by the code host to a version as
   349  // interpreted by the module system.
   350  //
   351  // If statVers is a valid module version, it is used for the Version field.
   352  // Otherwise, the Version is derived from the passed-in info and recent tags.
   353  func (r *codeRepo) convert(ctx context.Context, info *codehost.RevInfo, statVers string) (revInfo *RevInfo, err error) {
   354  	defer func() {
   355  		if info.Origin == nil {
   356  			return
   357  		}
   358  		if revInfo == nil {
   359  			revInfo = new(RevInfo)
   360  		} else if revInfo.Origin != nil {
   361  			panic("internal error: RevInfo Origin unexpectedly already populated")
   362  		}
   363  
   364  		origin := *info.Origin
   365  		revInfo.Origin = &origin
   366  		origin.Subdir = r.codeDir
   367  
   368  		v := revInfo.Version
   369  		if module.IsPseudoVersion(v) && (v != statVers || !strings.HasPrefix(v, "v0.0.0-")) {
   370  			// Add tags that are relevant to pseudo-version calculation to origin.
   371  			prefix := r.codeDir
   372  			if prefix != "" {
   373  				prefix += "/"
   374  			}
   375  			if r.pathMajor != "" { // "/v2" or "/.v2"
   376  				prefix += r.pathMajor[1:] + "." // += "v2."
   377  			}
   378  			tags, tagsErr := r.code.Tags(ctx, prefix)
   379  			if tagsErr != nil {
   380  				revInfo.Origin = nil
   381  				if err == nil {
   382  					err = tagsErr
   383  				}
   384  			} else {
   385  				origin.TagPrefix = tags.Origin.TagPrefix
   386  				origin.TagSum = tags.Origin.TagSum
   387  			}
   388  		}
   389  	}()
   390  
   391  	// If this is a plain tag (no dir/ prefix)
   392  	// and the module path is unversioned,
   393  	// and if the underlying file tree has no go.mod,
   394  	// then allow using the tag with a +incompatible suffix.
   395  	//
   396  	// (If the version is +incompatible, then the go.mod file must not exist:
   397  	// +incompatible is not an ongoing opt-out from semantic import versioning.)
   398  	incompatibleOk := map[string]bool{}
   399  	canUseIncompatible := func(v string) bool {
   400  		if r.codeDir != "" || r.pathMajor != "" {
   401  			// A non-empty codeDir indicates a module within a subdirectory,
   402  			// which necessarily has a go.mod file indicating the module boundary.
   403  			// A non-empty pathMajor indicates a module path with a major-version
   404  			// suffix, which must match.
   405  			return false
   406  		}
   407  
   408  		ok, seen := incompatibleOk[""]
   409  		if !seen {
   410  			_, errGoMod := r.code.ReadFile(ctx, info.Name, "go.mod", codehost.MaxGoMod)
   411  			ok = (errGoMod != nil)
   412  			incompatibleOk[""] = ok
   413  		}
   414  		if !ok {
   415  			// A go.mod file exists at the repo root.
   416  			return false
   417  		}
   418  
   419  		// Per https://go.dev/issue/51324, previous versions of the 'go' command
   420  		// didn't always check for go.mod files in subdirectories, so if the user
   421  		// requests a +incompatible version explicitly, we should continue to allow
   422  		// it. Otherwise, if vN/go.mod exists, expect that release tags for that
   423  		// major version are intended for the vN module.
   424  		if v != "" && !strings.HasSuffix(statVers, "+incompatible") {
   425  			major := semver.Major(v)
   426  			ok, seen = incompatibleOk[major]
   427  			if !seen {
   428  				_, errGoModSub := r.code.ReadFile(ctx, info.Name, path.Join(major, "go.mod"), codehost.MaxGoMod)
   429  				ok = (errGoModSub != nil)
   430  				incompatibleOk[major] = ok
   431  			}
   432  			if !ok {
   433  				return false
   434  			}
   435  		}
   436  
   437  		return true
   438  	}
   439  
   440  	// checkCanonical verifies that the canonical version v is compatible with the
   441  	// module path represented by r, adding a "+incompatible" suffix if needed.
   442  	//
   443  	// If statVers is also canonical, checkCanonical also verifies that v is
   444  	// either statVers or statVers with the added "+incompatible" suffix.
   445  	checkCanonical := func(v string) (*RevInfo, error) {
   446  		// If r.codeDir is non-empty, then the go.mod file must exist: the module
   447  		// author — not the module consumer, — gets to decide how to carve up the repo
   448  		// into modules.
   449  		//
   450  		// Conversely, if the go.mod file exists, the module author — not the module
   451  		// consumer — gets to determine the module's path
   452  		//
   453  		// r.findDir verifies both of these conditions. Execute it now so that
   454  		// r.Stat will correctly return a notExistError if the go.mod location or
   455  		// declared module path doesn't match.
   456  		_, _, _, err := r.findDir(ctx, v)
   457  		if err != nil {
   458  			// TODO: It would be nice to return an error like "not a module".
   459  			// Right now we return "missing go.mod", which is a little confusing.
   460  			return nil, &module.ModuleError{
   461  				Path: r.modPath,
   462  				Err: &module.InvalidVersionError{
   463  					Version: v,
   464  					Err:     notExistError{err: err},
   465  				},
   466  			}
   467  		}
   468  
   469  		invalidf := func(format string, args ...any) error {
   470  			return &module.ModuleError{
   471  				Path: r.modPath,
   472  				Err: &module.InvalidVersionError{
   473  					Version: v,
   474  					Err:     fmt.Errorf(format, args...),
   475  				},
   476  			}
   477  		}
   478  
   479  		// Add the +incompatible suffix if needed or requested explicitly, and
   480  		// verify that its presence or absence is appropriate for this version
   481  		// (which depends on whether it has an explicit go.mod file).
   482  
   483  		if v == strings.TrimSuffix(statVers, "+incompatible") {
   484  			v = statVers
   485  		}
   486  		base := strings.TrimSuffix(v, "+incompatible")
   487  		var errIncompatible error
   488  		if !module.MatchPathMajor(base, r.pathMajor) {
   489  			if canUseIncompatible(base) {
   490  				v = base + "+incompatible"
   491  			} else {
   492  				if r.pathMajor != "" {
   493  					errIncompatible = invalidf("module path includes a major version suffix, so major version must match")
   494  				} else {
   495  					errIncompatible = invalidf("module contains a go.mod file, so module path must match major version (%q)", path.Join(r.pathPrefix, semver.Major(v)))
   496  				}
   497  			}
   498  		} else if strings.HasSuffix(v, "+incompatible") {
   499  			errIncompatible = invalidf("+incompatible suffix not allowed: major version %s is compatible", semver.Major(v))
   500  		}
   501  
   502  		if statVers != "" && statVers == module.CanonicalVersion(statVers) {
   503  			// Since the caller-requested version is canonical, it would be very
   504  			// confusing to resolve it to anything but itself, possibly with a
   505  			// "+incompatible" suffix. Error out explicitly.
   506  			if statBase := strings.TrimSuffix(statVers, "+incompatible"); statBase != base {
   507  				return nil, &module.ModuleError{
   508  					Path: r.modPath,
   509  					Err: &module.InvalidVersionError{
   510  						Version: statVers,
   511  						Err:     fmt.Errorf("resolves to version %v (%s is not a tag)", v, statBase),
   512  					},
   513  				}
   514  			}
   515  		}
   516  
   517  		if errIncompatible != nil {
   518  			return nil, errIncompatible
   519  		}
   520  
   521  		return &RevInfo{
   522  			Name:    info.Name,
   523  			Short:   info.Short,
   524  			Time:    info.Time,
   525  			Version: v,
   526  		}, nil
   527  	}
   528  
   529  	// Determine version.
   530  
   531  	if module.IsPseudoVersion(statVers) {
   532  		// Validate the go.mod location and major version before
   533  		// we check for an ancestor tagged with the pseudo-version base.
   534  		//
   535  		// We can rule out an invalid subdirectory or major version with only
   536  		// shallow commit information, but checking the pseudo-version base may
   537  		// require downloading a (potentially more expensive) full history.
   538  		revInfo, err = checkCanonical(statVers)
   539  		if err != nil {
   540  			return revInfo, err
   541  		}
   542  		if err := r.validatePseudoVersion(ctx, info, statVers); err != nil {
   543  			return nil, err
   544  		}
   545  		return revInfo, nil
   546  	}
   547  
   548  	// statVers is not a pseudo-version, so we need to either resolve it to a
   549  	// canonical version or verify that it is already a canonical tag
   550  	// (not a branch).
   551  
   552  	// Derive or verify a version from a code repo tag.
   553  	// Tag must have a prefix matching codeDir.
   554  	tagPrefix := ""
   555  	if r.codeDir != "" {
   556  		tagPrefix = r.codeDir + "/"
   557  	}
   558  
   559  	isRetracted, err := r.retractedVersions(ctx)
   560  	if err != nil {
   561  		isRetracted = func(string) bool { return false }
   562  	}
   563  
   564  	// tagToVersion returns the version obtained by trimming tagPrefix from tag.
   565  	// If the tag is invalid, retracted, or a pseudo-version, tagToVersion returns
   566  	// an empty version.
   567  	tagToVersion := func(tag string) (v string, tagIsCanonical bool) {
   568  		if !strings.HasPrefix(tag, tagPrefix) {
   569  			return "", false
   570  		}
   571  		trimmed := tag[len(tagPrefix):]
   572  		// Tags that look like pseudo-versions would be confusing. Ignore them.
   573  		if module.IsPseudoVersion(tag) {
   574  			return "", false
   575  		}
   576  
   577  		v = semver.Canonical(trimmed) // Not module.Canonical: we don't want to pick up an explicit "+incompatible" suffix from the tag.
   578  		if v == "" || !strings.HasPrefix(trimmed, v) {
   579  			return "", false // Invalid or incomplete version (just vX or vX.Y).
   580  		}
   581  		if v == trimmed {
   582  			tagIsCanonical = true
   583  		}
   584  		return v, tagIsCanonical
   585  	}
   586  
   587  	// If the VCS gave us a valid version, use that.
   588  	if v, tagIsCanonical := tagToVersion(info.Version); tagIsCanonical {
   589  		if info, err := checkCanonical(v); err == nil {
   590  			return info, err
   591  		}
   592  	}
   593  
   594  	// Look through the tags on the revision for either a usable canonical version
   595  	// or an appropriate base for a pseudo-version.
   596  	var (
   597  		highestCanonical string
   598  		pseudoBase       string
   599  	)
   600  	for _, pathTag := range info.Tags {
   601  		v, tagIsCanonical := tagToVersion(pathTag)
   602  		if statVers != "" && semver.Compare(v, statVers) == 0 {
   603  			// The tag is equivalent to the version requested by the user.
   604  			if tagIsCanonical {
   605  				// This tag is the canonical form of the requested version,
   606  				// not some other form with extra build metadata.
   607  				// Use this tag so that the resolved version will match exactly.
   608  				// (If it isn't actually allowed, we'll error out in checkCanonical.)
   609  				return checkCanonical(v)
   610  			} else {
   611  				// The user explicitly requested something equivalent to this tag. We
   612  				// can't use the version from the tag directly: since the tag is not
   613  				// canonical, it could be ambiguous. For example, tags v0.0.1+a and
   614  				// v0.0.1+b might both exist and refer to different revisions.
   615  				//
   616  				// The tag is otherwise valid for the module, so we can at least use it as
   617  				// the base of an unambiguous pseudo-version.
   618  				//
   619  				// If multiple tags match, tagToVersion will canonicalize them to the same
   620  				// base version.
   621  				pseudoBase = v
   622  			}
   623  		}
   624  		// Save the highest non-retracted canonical tag for the revision.
   625  		// If we don't find a better match, we'll use it as the canonical version.
   626  		if tagIsCanonical && semver.Compare(highestCanonical, v) < 0 && !isRetracted(v) {
   627  			if module.MatchPathMajor(v, r.pathMajor) || canUseIncompatible(v) {
   628  				highestCanonical = v
   629  			}
   630  		}
   631  	}
   632  
   633  	// If we found a valid canonical tag for the revision, return it.
   634  	// Even if we found a good pseudo-version base, a canonical version is better.
   635  	if highestCanonical != "" {
   636  		return checkCanonical(highestCanonical)
   637  	}
   638  
   639  	// Find the highest tagged version in the revision's history, subject to
   640  	// major version and +incompatible constraints. Use that version as the
   641  	// pseudo-version base so that the pseudo-version sorts higher. Ignore
   642  	// retracted versions.
   643  	tagAllowed := func(tag string) bool {
   644  		v, _ := tagToVersion(tag)
   645  		if v == "" {
   646  			return false
   647  		}
   648  		if !module.MatchPathMajor(v, r.pathMajor) && !canUseIncompatible(v) {
   649  			return false
   650  		}
   651  		return !isRetracted(v)
   652  	}
   653  	if pseudoBase == "" {
   654  		tag, err := r.code.RecentTag(ctx, info.Name, tagPrefix, tagAllowed)
   655  		if err != nil && !errors.Is(err, errors.ErrUnsupported) {
   656  			return nil, err
   657  		}
   658  		if tag != "" {
   659  			pseudoBase, _ = tagToVersion(tag)
   660  		}
   661  	}
   662  
   663  	return checkCanonical(module.PseudoVersion(r.pseudoMajor, pseudoBase, info.Time, info.Short))
   664  }
   665  
   666  // validatePseudoVersion checks that version has a major version compatible with
   667  // r.modPath and encodes a base version and commit metadata that agrees with
   668  // info.
   669  //
   670  // Note that verifying a nontrivial base version in particular may be somewhat
   671  // expensive: in order to do so, r.code.DescendsFrom will need to fetch at least
   672  // enough of the commit history to find a path between version and its base.
   673  // Fortunately, many pseudo-versions — such as those for untagged repositories —
   674  // have trivial bases!
   675  func (r *codeRepo) validatePseudoVersion(ctx context.Context, info *codehost.RevInfo, version string) (err error) {
   676  	defer func() {
   677  		if err != nil {
   678  			if _, ok := err.(*module.ModuleError); !ok {
   679  				if _, ok := err.(*module.InvalidVersionError); !ok {
   680  					err = &module.InvalidVersionError{Version: version, Pseudo: true, Err: err}
   681  				}
   682  				err = &module.ModuleError{Path: r.modPath, Err: err}
   683  			}
   684  		}
   685  	}()
   686  
   687  	rev, err := module.PseudoVersionRev(version)
   688  	if err != nil {
   689  		return err
   690  	}
   691  	if rev != info.Short {
   692  		switch {
   693  		case strings.HasPrefix(rev, info.Short):
   694  			return fmt.Errorf("revision is longer than canonical (expected %s)", info.Short)
   695  		case strings.HasPrefix(info.Short, rev):
   696  			return fmt.Errorf("revision is shorter than canonical (expected %s)", info.Short)
   697  		default:
   698  			return fmt.Errorf("does not match short name of revision (expected %s)", info.Short)
   699  		}
   700  	}
   701  
   702  	t, err := module.PseudoVersionTime(version)
   703  	if err != nil {
   704  		return err
   705  	}
   706  	if !t.Equal(info.Time.Truncate(time.Second)) {
   707  		return fmt.Errorf("does not match version-control timestamp (expected %s)", info.Time.UTC().Format(module.PseudoVersionTimestampFormat))
   708  	}
   709  
   710  	tagPrefix := ""
   711  	if r.codeDir != "" {
   712  		tagPrefix = r.codeDir + "/"
   713  	}
   714  
   715  	// A pseudo-version should have a precedence just above its parent revisions,
   716  	// and no higher. Otherwise, it would be possible for library authors to "pin"
   717  	// dependency versions (and bypass the usual minimum version selection) by
   718  	// naming an extremely high pseudo-version rather than an accurate one.
   719  	//
   720  	// Moreover, if we allow a pseudo-version to use any arbitrary pre-release
   721  	// tag, we end up with infinitely many possible names for each commit. Each
   722  	// name consumes resources in the module cache and proxies, so we want to
   723  	// restrict them to a finite set under control of the module author.
   724  	//
   725  	// We address both of these issues by requiring the tag upon which the
   726  	// pseudo-version is based to refer to some ancestor of the revision. We
   727  	// prefer the highest such tag when constructing a new pseudo-version, but do
   728  	// not enforce that property when resolving existing pseudo-versions: we don't
   729  	// know when the parent tags were added, and the highest-tagged parent may not
   730  	// have existed when the pseudo-version was first resolved.
   731  	base, err := module.PseudoVersionBase(strings.TrimSuffix(version, "+incompatible"))
   732  	if err != nil {
   733  		return err
   734  	}
   735  	if base == "" {
   736  		if r.pseudoMajor == "" && semver.Major(version) == "v1" {
   737  			return fmt.Errorf("major version without preceding tag must be v0, not v1")
   738  		}
   739  		return nil
   740  	} else {
   741  		for _, tag := range info.Tags {
   742  			versionOnly := strings.TrimPrefix(tag, tagPrefix)
   743  			if versionOnly == base {
   744  				// The base version is canonical, so if the version from the tag is
   745  				// literally equal (not just equivalent), then the tag is canonical too.
   746  				//
   747  				// We allow pseudo-versions to be derived from non-canonical tags on the
   748  				// same commit, so that tags like "v1.1.0+some-metadata" resolve as
   749  				// close as possible to the canonical version ("v1.1.0") while still
   750  				// enforcing a total ordering ("v1.1.1-0.[…]" with a unique suffix).
   751  				//
   752  				// However, canonical tags already have a total ordering, so there is no
   753  				// reason not to use the canonical tag directly, and we know that the
   754  				// canonical tag must already exist because the pseudo-version is
   755  				// derived from it. In that case, referring to the revision by a
   756  				// pseudo-version derived from its own canonical tag is just confusing.
   757  				return fmt.Errorf("tag (%s) found on revision %s is already canonical, so should not be replaced with a pseudo-version derived from that tag", tag, rev)
   758  			}
   759  		}
   760  	}
   761  
   762  	tags, err := r.code.Tags(ctx, tagPrefix+base)
   763  	if err != nil {
   764  		return err
   765  	}
   766  
   767  	var lastTag string // Prefer to log some real tag rather than a canonically-equivalent base.
   768  	ancestorFound := false
   769  	for _, tag := range tags.List {
   770  		versionOnly := strings.TrimPrefix(tag.Name, tagPrefix)
   771  		if semver.Compare(versionOnly, base) == 0 {
   772  			lastTag = tag.Name
   773  			ancestorFound, err = r.code.DescendsFrom(ctx, info.Name, tag.Name)
   774  			if ancestorFound {
   775  				break
   776  			}
   777  		}
   778  	}
   779  
   780  	if lastTag == "" {
   781  		return fmt.Errorf("preceding tag (%s) not found", base)
   782  	}
   783  
   784  	if !ancestorFound {
   785  		if err != nil {
   786  			return err
   787  		}
   788  		rev, err := module.PseudoVersionRev(version)
   789  		if err != nil {
   790  			return fmt.Errorf("not a descendent of preceding tag (%s)", lastTag)
   791  		}
   792  		return fmt.Errorf("revision %s is not a descendent of preceding tag (%s)", rev, lastTag)
   793  	}
   794  	return nil
   795  }
   796  
   797  func (r *codeRepo) revToRev(rev string) string {
   798  	if semver.IsValid(rev) {
   799  		if module.IsPseudoVersion(rev) {
   800  			r, _ := module.PseudoVersionRev(rev)
   801  			return r
   802  		}
   803  		if semver.Build(rev) == "+incompatible" {
   804  			rev = rev[:len(rev)-len("+incompatible")]
   805  		}
   806  		if r.codeDir == "" {
   807  			return rev
   808  		}
   809  		return r.codeDir + "/" + rev
   810  	}
   811  	return rev
   812  }
   813  
   814  func (r *codeRepo) versionToRev(version string) (rev string, err error) {
   815  	if !semver.IsValid(version) {
   816  		return "", &module.ModuleError{
   817  			Path: r.modPath,
   818  			Err: &module.InvalidVersionError{
   819  				Version: version,
   820  				Err:     errors.New("syntax error"),
   821  			},
   822  		}
   823  	}
   824  	return r.revToRev(version), nil
   825  }
   826  
   827  // findDir locates the directory within the repo containing the module.
   828  //
   829  // If r.pathMajor is non-empty, this can be either r.codeDir or — if a go.mod
   830  // file exists — r.codeDir/r.pathMajor[1:].
   831  func (r *codeRepo) findDir(ctx context.Context, version string) (rev, dir string, gomod []byte, err error) {
   832  	rev, err = r.versionToRev(version)
   833  	if err != nil {
   834  		return "", "", nil, err
   835  	}
   836  
   837  	// Load info about go.mod but delay consideration
   838  	// (except I/O error) until we rule out v2/go.mod.
   839  	file1 := path.Join(r.codeDir, "go.mod")
   840  	gomod1, err1 := r.code.ReadFile(ctx, rev, file1, codehost.MaxGoMod)
   841  	if err1 != nil && !os.IsNotExist(err1) {
   842  		return "", "", nil, fmt.Errorf("reading %s/%s at revision %s: %v", r.codeRoot, file1, rev, err1)
   843  	}
   844  	mpath1 := modfile.ModulePath(gomod1)
   845  	found1 := err1 == nil && (isMajor(mpath1, r.pathMajor) || r.canReplaceMismatchedVersionDueToBug(mpath1))
   846  
   847  	var file2 string
   848  	if r.pathMajor != "" && r.codeRoot != r.modPath && !strings.HasPrefix(r.pathMajor, ".") {
   849  		// Suppose pathMajor is "/v2".
   850  		// Either go.mod should claim v2 and v2/go.mod should not exist,
   851  		// or v2/go.mod should exist and claim v2. Not both.
   852  		// Note that we don't check the full path, just the major suffix,
   853  		// because of replacement modules. This might be a fork of
   854  		// the real module, found at a different path, usable only in
   855  		// a replace directive.
   856  		dir2 := path.Join(r.codeDir, r.pathMajor[1:])
   857  		file2 = path.Join(dir2, "go.mod")
   858  		gomod2, err2 := r.code.ReadFile(ctx, rev, file2, codehost.MaxGoMod)
   859  		if err2 != nil && !os.IsNotExist(err2) {
   860  			return "", "", nil, fmt.Errorf("reading %s/%s at revision %s: %v", r.codeRoot, file2, rev, err2)
   861  		}
   862  		mpath2 := modfile.ModulePath(gomod2)
   863  		found2 := err2 == nil && isMajor(mpath2, r.pathMajor)
   864  
   865  		if found1 && found2 {
   866  			return "", "", nil, fmt.Errorf("%s/%s and ...%s/go.mod both have ...%s module paths at revision %s", r.pathPrefix, file1, r.pathMajor, r.pathMajor, rev)
   867  		}
   868  		if found2 {
   869  			return rev, dir2, gomod2, nil
   870  		}
   871  		if err2 == nil {
   872  			if mpath2 == "" {
   873  				return "", "", nil, fmt.Errorf("%s/%s is missing module path at revision %s", r.codeRoot, file2, rev)
   874  			}
   875  			return "", "", nil, fmt.Errorf("%s/%s has non-...%s module path %q at revision %s", r.codeRoot, file2, r.pathMajor, mpath2, rev)
   876  		}
   877  	}
   878  
   879  	// Not v2/go.mod, so it's either go.mod or nothing. Which is it?
   880  	if found1 {
   881  		// Explicit go.mod with matching major version ok.
   882  		return rev, r.codeDir, gomod1, nil
   883  	}
   884  	if err1 == nil {
   885  		// Explicit go.mod with non-matching major version disallowed.
   886  		suffix := ""
   887  		if file2 != "" {
   888  			suffix = fmt.Sprintf(" (and ...%s/go.mod does not exist)", r.pathMajor)
   889  		}
   890  		if mpath1 == "" {
   891  			return "", "", nil, fmt.Errorf("%s is missing module path%s at revision %s", file1, suffix, rev)
   892  		}
   893  		if r.pathMajor != "" { // ".v1", ".v2" for gopkg.in
   894  			return "", "", nil, fmt.Errorf("%s has non-...%s module path %q%s at revision %s", file1, r.pathMajor, mpath1, suffix, rev)
   895  		}
   896  		if _, _, ok := module.SplitPathVersion(mpath1); !ok {
   897  			return "", "", nil, fmt.Errorf("%s has malformed module path %q%s at revision %s", file1, mpath1, suffix, rev)
   898  		}
   899  		return "", "", nil, fmt.Errorf("%s has post-%s module path %q%s at revision %s", file1, semver.Major(version), mpath1, suffix, rev)
   900  	}
   901  
   902  	if r.codeDir == "" && (r.pathMajor == "" || strings.HasPrefix(r.pathMajor, ".")) {
   903  		// Implicit go.mod at root of repo OK for v0/v1 and for gopkg.in.
   904  		return rev, "", nil, nil
   905  	}
   906  
   907  	// Implicit go.mod below root of repo or at v2+ disallowed.
   908  	// Be clear about possibility of using either location for v2+.
   909  	if file2 != "" {
   910  		return "", "", nil, fmt.Errorf("missing %s/go.mod and ...%s/go.mod at revision %s", r.pathPrefix, r.pathMajor, rev)
   911  	}
   912  	return "", "", nil, fmt.Errorf("missing %s/go.mod at revision %s", r.pathPrefix, rev)
   913  }
   914  
   915  // isMajor reports whether the versions allowed for mpath are compatible with
   916  // the major version(s) implied by pathMajor, or false if mpath has an invalid
   917  // version suffix.
   918  func isMajor(mpath, pathMajor string) bool {
   919  	if mpath == "" {
   920  		// If we don't have a path, we don't know what version(s) it is compatible with.
   921  		return false
   922  	}
   923  	_, mpathMajor, ok := module.SplitPathVersion(mpath)
   924  	if !ok {
   925  		// An invalid module path is not compatible with any version.
   926  		return false
   927  	}
   928  	if pathMajor == "" {
   929  		// All of the valid versions for a gopkg.in module that requires major
   930  		// version v0 or v1 are compatible with the "v0 or v1" implied by an empty
   931  		// pathMajor.
   932  		switch module.PathMajorPrefix(mpathMajor) {
   933  		case "", "v0", "v1":
   934  			return true
   935  		default:
   936  			return false
   937  		}
   938  	}
   939  	if mpathMajor == "" {
   940  		// Even if pathMajor is ".v0" or ".v1", we can't be sure that a module
   941  		// without a suffix is tagged appropriately. Besides, we don't expect clones
   942  		// of non-gopkg.in modules to have gopkg.in paths, so a non-empty,
   943  		// non-gopkg.in mpath is probably the wrong module for any such pathMajor
   944  		// anyway.
   945  		return false
   946  	}
   947  	// If both pathMajor and mpathMajor are non-empty, then we only care that they
   948  	// have the same major-version validation rules. A clone fetched via a /v2
   949  	// path might replace a module with path gopkg.in/foo.v2-unstable, and that's
   950  	// ok.
   951  	return pathMajor[1:] == mpathMajor[1:]
   952  }
   953  
   954  // canReplaceMismatchedVersionDueToBug reports whether versions of r
   955  // could replace versions of mpath with otherwise-mismatched major versions
   956  // due to a historical bug in the Go command (golang.org/issue/34254).
   957  func (r *codeRepo) canReplaceMismatchedVersionDueToBug(mpath string) bool {
   958  	// The bug caused us to erroneously accept unversioned paths as replacements
   959  	// for versioned gopkg.in paths.
   960  	unversioned := r.pathMajor == ""
   961  	replacingGopkgIn := strings.HasPrefix(mpath, "gopkg.in/")
   962  	return unversioned && replacingGopkgIn
   963  }
   964  
   965  func (r *codeRepo) GoMod(ctx context.Context, version string) (data []byte, err error) {
   966  	if version != module.CanonicalVersion(version) {
   967  		return nil, fmt.Errorf("version %s is not canonical", version)
   968  	}
   969  
   970  	if module.IsPseudoVersion(version) {
   971  		// findDir ignores the metadata encoded in a pseudo-version,
   972  		// only using the revision at the end.
   973  		// Invoke Stat to verify the metadata explicitly so we don't return
   974  		// a bogus file for an invalid version.
   975  		_, err := r.Stat(ctx, version)
   976  		if err != nil {
   977  			return nil, err
   978  		}
   979  	}
   980  
   981  	rev, dir, gomod, err := r.findDir(ctx, version)
   982  	if err != nil {
   983  		return nil, err
   984  	}
   985  	if gomod != nil {
   986  		return gomod, nil
   987  	}
   988  	data, err = r.code.ReadFile(ctx, rev, path.Join(dir, "go.mod"), codehost.MaxGoMod)
   989  	if err != nil {
   990  		if os.IsNotExist(err) {
   991  			return LegacyGoMod(r.modPath), nil
   992  		}
   993  		return nil, err
   994  	}
   995  	return data, nil
   996  }
   997  
   998  // LegacyGoMod generates a fake go.mod file for a module that doesn't have one.
   999  // The go.mod file contains a module directive and nothing else: no go version,
  1000  // no requirements.
  1001  //
  1002  // We used to try to build a go.mod reflecting pre-existing
  1003  // package management metadata files, but the conversion
  1004  // was inherently imperfect (because those files don't have
  1005  // exactly the same semantics as go.mod) and, when done
  1006  // for dependencies in the middle of a build, impossible to
  1007  // correct. So we stopped.
  1008  func LegacyGoMod(modPath string) []byte {
  1009  	return fmt.Appendf(nil, "module %s\n", modfile.AutoQuote(modPath))
  1010  }
  1011  
  1012  func (r *codeRepo) modPrefix(rev string) string {
  1013  	return r.modPath + "@" + rev
  1014  }
  1015  
  1016  func (r *codeRepo) retractedVersions(ctx context.Context) (func(string) bool, error) {
  1017  	vs, err := r.Versions(ctx, "")
  1018  	if err != nil {
  1019  		return nil, err
  1020  	}
  1021  	versions := vs.List
  1022  
  1023  	for i, v := range versions {
  1024  		if strings.HasSuffix(v, "+incompatible") {
  1025  			// We're looking for the latest release tag that may list retractions in a
  1026  			// go.mod file. +incompatible versions necessarily do not, and they start
  1027  			// at major version 2 — which is higher than any version that could
  1028  			// validly contain a go.mod file.
  1029  			versions = versions[:i]
  1030  			break
  1031  		}
  1032  	}
  1033  	if len(versions) == 0 {
  1034  		return func(string) bool { return false }, nil
  1035  	}
  1036  
  1037  	var highest string
  1038  	for i := len(versions) - 1; i >= 0; i-- {
  1039  		v := versions[i]
  1040  		if semver.Prerelease(v) == "" {
  1041  			highest = v
  1042  			break
  1043  		}
  1044  	}
  1045  	if highest == "" {
  1046  		highest = versions[len(versions)-1]
  1047  	}
  1048  
  1049  	data, err := r.GoMod(ctx, highest)
  1050  	if err != nil {
  1051  		return nil, err
  1052  	}
  1053  	f, err := modfile.ParseLax("go.mod", data, nil)
  1054  	if err != nil {
  1055  		return nil, err
  1056  	}
  1057  	retractions := make([]modfile.VersionInterval, 0, len(f.Retract))
  1058  	for _, r := range f.Retract {
  1059  		retractions = append(retractions, r.VersionInterval)
  1060  	}
  1061  
  1062  	return func(v string) bool {
  1063  		for _, r := range retractions {
  1064  			if semver.Compare(r.Low, v) <= 0 && semver.Compare(v, r.High) <= 0 {
  1065  				return true
  1066  			}
  1067  		}
  1068  		return false
  1069  	}, nil
  1070  }
  1071  
  1072  func (r *codeRepo) Zip(ctx context.Context, dst io.Writer, version string) error {
  1073  	if version != module.CanonicalVersion(version) {
  1074  		return fmt.Errorf("version %s is not canonical", version)
  1075  	}
  1076  
  1077  	if module.IsPseudoVersion(version) {
  1078  		// findDir ignores the metadata encoded in a pseudo-version,
  1079  		// only using the revision at the end.
  1080  		// Invoke Stat to verify the metadata explicitly so we don't return
  1081  		// a bogus file for an invalid version.
  1082  		_, err := r.Stat(ctx, version)
  1083  		if err != nil {
  1084  			return err
  1085  		}
  1086  	}
  1087  
  1088  	rev, subdir, _, err := r.findDir(ctx, version)
  1089  	if err != nil {
  1090  		return err
  1091  	}
  1092  
  1093  	if gomod, err := r.code.ReadFile(ctx, rev, filepath.Join(subdir, "go.mod"), codehost.MaxGoMod); err == nil {
  1094  		goVers := gover.GoModLookup(gomod, "go")
  1095  		if gover.Compare(goVers, gover.Local()) > 0 {
  1096  			return &gover.TooNewError{What: r.ModulePath() + "@" + version, GoVersion: goVers}
  1097  		}
  1098  	} else if !errors.Is(err, fs.ErrNotExist) {
  1099  		return err
  1100  	}
  1101  
  1102  	dl, err := r.code.ReadZip(ctx, rev, subdir, codehost.MaxZipFile)
  1103  	if err != nil {
  1104  		return err
  1105  	}
  1106  	defer dl.Close()
  1107  	subdir = strings.Trim(subdir, "/")
  1108  
  1109  	// Spool to local file.
  1110  	f, err := os.CreateTemp("", "go-codehost-")
  1111  	if err != nil {
  1112  		dl.Close()
  1113  		return err
  1114  	}
  1115  	defer os.Remove(f.Name())
  1116  	defer f.Close()
  1117  	maxSize := int64(codehost.MaxZipFile)
  1118  	lr := &io.LimitedReader{R: dl, N: maxSize + 1}
  1119  	if _, err := io.Copy(f, lr); err != nil {
  1120  		dl.Close()
  1121  		return err
  1122  	}
  1123  	dl.Close()
  1124  	if lr.N <= 0 {
  1125  		return fmt.Errorf("downloaded zip file too large")
  1126  	}
  1127  	size := (maxSize + 1) - lr.N
  1128  	if _, err := f.Seek(0, 0); err != nil {
  1129  		return err
  1130  	}
  1131  
  1132  	// Translate from zip file we have to zip file we want.
  1133  	zr, err := zip.NewReader(f, size)
  1134  	if err != nil {
  1135  		return err
  1136  	}
  1137  
  1138  	var files []modzip.File
  1139  	if subdir != "" {
  1140  		subdir += "/"
  1141  	}
  1142  	haveLICENSE := false
  1143  	topPrefix := ""
  1144  	for _, zf := range zr.File {
  1145  		if topPrefix == "" {
  1146  			i := strings.Index(zf.Name, "/")
  1147  			if i < 0 {
  1148  				return fmt.Errorf("missing top-level directory prefix")
  1149  			}
  1150  			topPrefix = zf.Name[:i+1]
  1151  		}
  1152  		var name string
  1153  		var found bool
  1154  		if name, found = strings.CutPrefix(zf.Name, topPrefix); !found {
  1155  			return fmt.Errorf("zip file contains more than one top-level directory")
  1156  		}
  1157  
  1158  		if name, found = strings.CutPrefix(name, subdir); !found {
  1159  			continue
  1160  		}
  1161  
  1162  		if name == "" || strings.HasSuffix(name, "/") {
  1163  			continue
  1164  		}
  1165  		files = append(files, zipFile{name: name, f: zf})
  1166  		if name == "LICENSE" {
  1167  			haveLICENSE = true
  1168  		}
  1169  	}
  1170  
  1171  	if !haveLICENSE && subdir != "" {
  1172  		data, err := r.code.ReadFile(ctx, rev, "LICENSE", codehost.MaxLICENSE)
  1173  		if err == nil {
  1174  			files = append(files, dataFile{name: "LICENSE", data: data})
  1175  		}
  1176  	}
  1177  
  1178  	return modzip.Create(dst, module.Version{Path: r.modPath, Version: version}, files)
  1179  }
  1180  
  1181  type zipFile struct {
  1182  	name string
  1183  	f    *zip.File
  1184  }
  1185  
  1186  func (f zipFile) Path() string                 { return f.name }
  1187  func (f zipFile) Lstat() (fs.FileInfo, error)  { return f.f.FileInfo(), nil }
  1188  func (f zipFile) Open() (io.ReadCloser, error) { return f.f.Open() }
  1189  
  1190  type dataFile struct {
  1191  	name string
  1192  	data []byte
  1193  }
  1194  
  1195  func (f dataFile) Path() string                { return f.name }
  1196  func (f dataFile) Lstat() (fs.FileInfo, error) { return dataFileInfo{f}, nil }
  1197  func (f dataFile) Open() (io.ReadCloser, error) {
  1198  	return io.NopCloser(bytes.NewReader(f.data)), nil
  1199  }
  1200  
  1201  type dataFileInfo struct {
  1202  	f dataFile
  1203  }
  1204  
  1205  func (fi dataFileInfo) Name() string       { return path.Base(fi.f.name) }
  1206  func (fi dataFileInfo) Size() int64        { return int64(len(fi.f.data)) }
  1207  func (fi dataFileInfo) Mode() fs.FileMode  { return 0644 }
  1208  func (fi dataFileInfo) ModTime() time.Time { return time.Time{} }
  1209  func (fi dataFileInfo) IsDir() bool        { return false }
  1210  func (fi dataFileInfo) Sys() any           { return nil }
  1211  
  1212  func (fi dataFileInfo) String() string {
  1213  	return fs.FormatFileInfo(fi)
  1214  }
  1215  
  1216  // hasPathPrefix reports whether the path s begins with the
  1217  // elements in prefix.
  1218  func hasPathPrefix(s, prefix string) bool {
  1219  	switch {
  1220  	default:
  1221  		return false
  1222  	case len(s) == len(prefix):
  1223  		return s == prefix
  1224  	case len(s) > len(prefix):
  1225  		if prefix != "" && prefix[len(prefix)-1] == '/' {
  1226  			return strings.HasPrefix(s, prefix)
  1227  		}
  1228  		return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
  1229  	}
  1230  }
  1231  

View as plain text