modload

package
v0.9.2202 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2024 License: BSD-3-Clause Imports: 45 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// RootMode determines whether a module root is needed.
	RootMode Root

	// ForceUseModules may be set to force modules to be enabled when
	// GO111MODULE=auto or to report an error when GO111MODULE=off.
	ForceUseModules bool

	// ExplicitWriteGoMod prevents LoadPackages, ListModules, and other functions
	// from updating go.mod and go.sum or reporting errors when updates are
	// needed. A package should set this if it would cause go.mod to be written
	// multiple times (for example, 'go get' calls LoadPackages multiple times) or
	// if it needs some other operation to be successful before go.mod and go.sum
	// can be written (for example, 'go mod download' must download modules before
	// adding sums to go.sum). Packages that set this are responsible for calling
	// WriteGoMod explicitly.
	ExplicitWriteGoMod bool
)

Variables set by other packages.

TODO(#40775): See if these can be plumbed as explicit parameters.

View Source
var ErrDisallowed = errors.New("disallowed module version")

ErrDisallowed is returned by version predicates passed to Query and similar functions to indicate that a version should not be considered.

View Source
var ErrNoModRoot = errors.New("go.mod file not found in current directory or any parent directory; see 'go help modules'")
View Source
var HelpGoMod = &base.Command{
	UsageLine: "go.mod",
	Short:     "the go.mod file",
	Long: `
A module version is defined by a tree of source files, with a go.mod
file in its root. When the go command is run, it looks in the current
directory and then successive parent directories to find the go.mod
marking the root of the main (current) module.

The go.mod file format is described in detail at
https://golang.org/ref/mod#go-mod-file.

To create a new go.mod file, use 'go mod init'. For details see
'go help mod init' or https://golang.org/ref/mod#go-mod-init.

To add missing module requirements or remove unneeded requirements,
use 'go mod tidy'. For details, see 'go help mod tidy' or
https://golang.org/ref/mod#go-mod-tidy.

To add, upgrade, downgrade, or remove a specific module requirement, use
'go get'. For details, see 'go help module-get' or
https://golang.org/ref/mod#go-get.

To make other changes or to parse go.mod as JSON for use by other tools,
use 'go mod edit'. See 'go help mod edit' or
https://golang.org/ref/mod#go-mod-edit.
	`,
}
View Source
var HelpModules = &base.Command{
	UsageLine: "modules",
	Short:     "modules, module versions, and more",
	Long: `
Modules are how Go manages dependencies.

A module is a collection of packages that are released, versioned, and
distributed together. Modules may be downloaded directly from version control
repositories or from module proxy servers.

For a series of tutorials on modules, see
https://golang.org/doc/tutorial/create-module.

For a detailed reference on modules, see https://golang.org/ref/mod.

By default, the go command may download modules from https://proxy.golang.org.
It may authenticate modules using the checksum database at
https://sum.golang.org. Both services are operated by the Go team at Google.
The privacy policies for these services are available at
https://proxy.golang.org/privacy and https://sum.golang.org/privacy,
respectively.

The go command's download behavior may be configured using GOPROXY, GOSUMDB,
GOPRIVATE, and other environment variables. See 'go help environment'
and https://golang.org/ref/mod#private-module-privacy for more information.
	`,
}

Functions

func AllowMissingModuleImports

func AllowMissingModuleImports()

AllowMissingModuleImports allows import paths to be resolved to modules when there is no module root. Normally, this is forbidden because it's slow and there's no way to make the result reproducible, but some commands like 'go get' are expected to do this.

This function affects the default cfg.BuildMod when outside of a module, so it can only be called prior to Init.

func BinDir

func BinDir() string

func CheckAllowed

func CheckAllowed(ctx context.Context, m module.Version) error

CheckAllowed returns an error equivalent to ErrDisallowed if m is excluded by the main module's go.mod or retracted by its author. Most version queries use this to filter out versions that should not be used.

func CheckDeprecation

func CheckDeprecation(ctx context.Context, m module.Version) (deprecation string, err error)

CheckDeprecation returns a deprecation message from the go.mod file of the latest version of the given module. Deprecation messages are comments before or on the same line as the module directives that start with "Deprecated:" and run until the end of the paragraph.

CheckDeprecation returns an error if the message can't be loaded. CheckDeprecation returns "", nil if there is no deprecation message.

func CheckExclusions

func CheckExclusions(ctx context.Context, m module.Version) error

CheckExclusions returns an error equivalent to ErrDisallowed if module m is excluded by the main module's go.mod file.

func CheckRetractions

func CheckRetractions(ctx context.Context, m module.Version) (err error)

CheckRetractions returns an error if module m has been retracted by its author.

func CreateModFile

func CreateModFile(ctx context.Context, modPath string)

CreateModFile initializes a new module by creating a go.mod file.

If modPath is empty, CreateModFile will attempt to infer the path from the directory location within GOPATH.

If a vendoring configuration file is present, CreateModFile will attempt to translate it to go.mod directives. The resulting build list may not be exactly the same as in the legacy configuration (for example, we can't get packages at multiple versions from the same module).

func EditBuildList

func EditBuildList(ctx context.Context, add, mustSelect []module.Version) (changed bool, err error)

EditBuildList edits the global build list by first adding every module in add to the existing build list, then adjusting versions (and adding or removing requirements as needed) until every module in mustSelect is selected at the given version.

(Note that the newly-added modules might not be selected in the resulting build list: they could be lower than existing requirements or conflict with versions in mustSelect.)

If the versions listed in mustSelect are mutually incompatible (due to one of the listed modules requiring a higher version of another), EditBuildList returns a *ConstraintError and leaves the build list in its previous state.

On success, EditBuildList reports whether the selected version of any module in the build list may have been changed (possibly to or from "none") as a result.

func Enabled

func Enabled() bool

Enabled reports whether modules are (or must be) enabled. If modules are enabled but there is no main module, Enabled returns true and then the first use of module information will call die (usually through MustModRoot).

func EnterModule

func EnterModule(ctx context.Context, enterModroot string)

EnterModule resets MainModules and requirements to refer to just this one module.

func FindGoMod added in v0.7.2202

func FindGoMod(wd string) string

FindGoMod returns the name of the go.mod file for this command, or the empty string if there isn't one. Most code should use Init and Enabled rather than use this directly. It is exported mainly for Go toolchain switching, which must process the go.mod very early at startup.

func FindGoWork added in v0.7.2202

func FindGoWork(wd string) string

FindGoWork returns the name of the go.work file for this command, or the empty string if there isn't one. Most code should use Init and Enabled rather than use this directly. It is exported mainly for Go toolchain switching, which must process the go.work very early at startup.

func HasModRoot

func HasModRoot() bool

HasModRoot reports whether a main module is present. HasModRoot may return false even if Enabled returns true: for example, 'get' does not require a main module.

func ImportFromFiles

func ImportFromFiles(ctx context.Context, gofiles []string)

ImportFromFiles adds modules to the build list as needed to satisfy the imports in the named Go source files.

Errors in missing dependencies are silenced.

TODO(bcmills): Silencing errors seems off. Take a closer look at this and figure out what the error-reporting actually ought to be.

func Init

func Init()

Init determines whether module mode is enabled, locates the root of the current module (if any), sets environment variables for Git subprocesses, and configures the cfg, codehost, load, modfetch, and search packages for use with modules.

func InitWorkfile

func InitWorkfile()

InitWorkfile initializes the workFilePath variable for commands that operate in workspace mode. It should not be called by other commands, for example 'go mod tidy', that don't operate in workspace mode.

func IsRevisionQuery

func IsRevisionQuery(path, vers string) bool

IsRevisionQuery returns true if vers is a version query that may refer to a particular version or revision in a repository like "v1.0.0", "master", or "0123abcd". IsRevisionQuery returns false if vers is a query that chooses from among available versions like "latest" or ">v1.0.0".

func ListModules

func ListModules(ctx context.Context, args []string, mode ListMode, reuseFile string) ([]*modinfo.ModulePublic, error)

ListModules returns a description of the modules matching args, if known, along with any error preventing additional matches from being identified.

The returned slice can be nonempty even if the error is non-nil.

func LoadPackages

func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string)

LoadPackages identifies the set of packages matching the given patterns and loads the packages in the import graph rooted at that set.

func Lookup

func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error)

Lookup returns the source directory, import path, and any loading error for the package at path as imported from the package in parentDir. Lookup requires that one of the Load functions in this package has already been called.

func MatchInModule

func MatchInModule(ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match

MatchInModule identifies the packages matching the given pattern within the given module version, which does not need to be in the build list or module requirement graph.

If m is the zero module.Version, MatchInModule matches the pattern against the standard library (std and cmd) in GOROOT/src.

func ModFile

func ModFile() *modfile.File

ModFile returns the parsed go.mod file.

Note that after calling LoadPackages or LoadModGraph, the require statements in the modfile.File are no longer the source of truth and will be ignored: edits made directly will be lost at the next call to WriteGoMod. To make permanent changes to the require statements in go.mod, edit it before loading.

func ModFilePath

func ModFilePath() string

ModFilePath returns the path that would be used for the go.mod file, if in module mode. ModFilePath calls base.Fatalf if there is no main module, even if -modfile is set.

func ModInfoData

func ModInfoData(info string) []byte

func ModInfoProg

func ModInfoProg(info string, isgccgo bool) []byte

func ModuleInfo

func ModuleInfo(ctx context.Context, path string) *modinfo.ModulePublic

func MustHaveModRoot

func MustHaveModRoot()

MustHaveModRoot checks that a main module or main modules are present, and calls base.Fatalf if there are no main modules.

func OverrideRoots added in v0.7.2202

func OverrideRoots(ctx context.Context, replace []module.Version)

OverrideRoots edits the global requirement roots by replacing the specific module versions.

func PackageModRoot

func PackageModRoot(ctx context.Context, pkgpath string) string

PackageModRoot returns the module root directory for the module that provides a given package. If modules are not enabled or if the package is in the standard library or if the package was not successfully loaded with LoadPackages or ImportFromFiles, the empty string is returned.

func PackageModule

func PackageModule(path string) module.Version

PackageModule returns the module providing the package named by the import path.

func PackageModuleInfo

func PackageModuleInfo(ctx context.Context, pkgpath string) *modinfo.ModulePublic

PackageModuleInfo returns information about the module that provides a given package. If modules are not enabled or if the package is in the standard library or if the package was not successfully loaded with LoadPackages or ImportFromFiles, nil is returned.

func Query

func Query(ctx context.Context, path, query, current string, allowed AllowedFunc) (*modfetch.RevInfo, error)

Query looks up a revision of a given module given a version query string. The module must be a complete module path. The version must take one of the following forms:

  • the literal string "latest", denoting the latest available, allowed tagged version, with non-prereleases preferred over prereleases. If there are no tagged versions in the repo, latest returns the most recent commit.

  • the literal string "upgrade", equivalent to "latest" except that if current is a newer version, current will be returned (see below).

  • the literal string "patch", denoting the latest available tagged version with the same major and minor number as current (see below).

  • v1, denoting the latest available tagged version v1.x.x.

  • v1.2, denoting the latest available tagged version v1.2.x.

  • v1.2.3, a semantic version string denoting that tagged version.

  • <v1.2.3, <=v1.2.3, >v1.2.3, >=v1.2.3, denoting the version closest to the target and satisfying the given operator, with non-prereleases preferred over prereleases.

  • a repository commit identifier or tag, denoting that commit.

current denotes the currently-selected version of the module; it may be "none" if no version is currently selected, or "" if the currently-selected version is unknown or should not be considered. If query is "upgrade" or "patch", current will be returned if it is a newer semantic version or a chronologically later pseudo-version than the version that would otherwise be chosen. This prevents accidental downgrades from newer pre-release or development versions.

The allowed function (which may be nil) is used to filter out unsuitable versions (see AllowedFunc documentation for details). If the query refers to a specific revision (for example, "master"; see IsRevisionQuery), and the revision is disallowed by allowed, Query returns the error. If the query does not refer to a specific revision (for example, "latest"), Query acts as if versions disallowed by allowed do not exist.

If path is the path of the main module and the query is "latest", Query returns Target.Version as the version.

Query often returns a non-nil *RevInfo with a non-nil error, to provide an info.Origin that can allow the error to be cached.

func QueryPattern

func QueryPattern(ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) (pkgMods []QueryResult, modOnly *QueryResult, err error)

QueryPattern looks up the module(s) containing at least one package matching the given pattern at the given version. The results are sorted by module path length in descending order. If any proxy provides a non-empty set of candidate modules, no further proxies are tried.

For wildcard patterns, QueryPattern looks in modules with package paths up to the first "..." in the pattern. For the pattern "example.com/a/b.../c", QueryPattern would consider prefixes of "example.com/a".

If any matching package is in the main module, QueryPattern considers only the main module and only the version "latest", without checking for other possible modules.

QueryPattern always returns at least one QueryResult (which may be only modOnly) or a non-nil error.

func ReadModFile

func ReadModFile(gomod string, fix modfile.VersionFixer) (data []byte, f *modfile.File, err error)

ReadModFile reads and parses the mod file at gomod. ReadModFile properly applies the overlay, locks the file while reading, and applies fix, if applicable.

func ReadWorkFile

func ReadWorkFile(path string) (*modfile.WorkFile, error)

ReadWorkFile reads and parses the go.work file at the given path.

func Replacement

func Replacement(mod module.Version) module.Version

Replacement returns the replacement for mod, if any. If the path in the module.Version is relative it's relative to the single main module outside workspace mode, or the workspace's directory in workspace mode.

func Reset added in v0.7.2202

func Reset()

Reset clears all the initialized, cached state about the use of modules, so that we can start over.

func ShortMessage

func ShortMessage(message, emptyDefault string) string

ShortMessage returns a string from go.mod (for example, a retraction rationale or deprecation message) that is safe to print in a terminal.

If the given string is empty, ShortMessage returns the given default. If the given string is too long or contains non-printable characters, ShortMessage returns a hard-coded string.

func ToDirectoryPath

func ToDirectoryPath(path string) string

ToDirectoryPath adds a prefix if necessary so that path in unambiguously an absolute path or a relative path starting with a '.' or '..' path component.

func UpdateWorkFile

func UpdateWorkFile(wf *modfile.WorkFile)

UpdateWorkFile updates comments on directory directives in the go.work file to include the associated module path.

func UpdateWorkGoVersion added in v0.7.2202

func UpdateWorkGoVersion(wf *modfile.WorkFile, goVers string) (changed bool)

UpdateWorkGoVersion updates the go line in wf to be at least goVers, reporting whether it changed the file.

func VendorDir

func VendorDir() string

func Why

func Why(path string) string

Why returns the "go mod why" output stanza for the given package, without the leading # comment. The package graph must have been loaded already, usually by LoadPackages. If there is no reason for the package to be in the current build, Why returns an empty string.

func WhyDepth

func WhyDepth(path string) int

WhyDepth returns the number of steps in the Why listing. If there is no reason for the package to be in the current build, WhyDepth returns 0.

func WillBeEnabled

func WillBeEnabled() bool

WillBeEnabled checks whether modules should be enabled but does not initialize modules by installing hooks. If Init has already been called, WillBeEnabled returns the same result as Enabled.

This function is needed to break a cycle. The main package needs to know whether modules are enabled in order to install the module or GOPATH version of 'go get', but Init reads the -modfile flag in 'go get', so it shouldn't be called until the command is installed and flags are parsed. Instead of calling Init and Enabled, the main package can call this function.

func WorkFilePath

func WorkFilePath() string

WorkFilePath returns the absolute path of the go.work file, or "" if not in workspace mode. WorkFilePath must be called after InitWorkfile.

func WriteGoMod

func WriteGoMod(ctx context.Context, opts WriteOpts) error

WriteGoMod writes the current build list back to go.mod.

func WriteWorkFile

func WriteWorkFile(path string, wf *modfile.WorkFile) error

WriteWorkFile cleans and writes out the go.work file to the given path.

Types

type AllowedFunc

type AllowedFunc func(context.Context, module.Version) error

AllowedFunc is used by Query and other functions to filter out unsuitable versions, for example, those listed in exclude directives in the main module's go.mod file.

An AllowedFunc returns an error equivalent to ErrDisallowed for an unsuitable version. Any other error indicates the function was unable to determine whether the version should be allowed, for example, the function was unable to fetch or parse a go.mod file containing retractions. Typically, errors other than ErrDisallowed may be ignored.

type AmbiguousImportError

type AmbiguousImportError struct {
	Dirs    []string
	Modules []module.Version // Either empty or 1:1 with Dirs.
	// contains filtered or unexported fields
}

An AmbiguousImportError indicates an import of a package found in multiple modules in the build list, or found in both the main module and its vendor directory.

func (*AmbiguousImportError) Error

func (e *AmbiguousImportError) Error() string

func (*AmbiguousImportError) ImportPath

func (e *AmbiguousImportError) ImportPath() string

type Conflict

type Conflict struct {
	// Path is a path of requirements starting at some module version passed in
	// the mustSelect argument and ending at a module whose requirements make that
	// version unacceptable. (Path always has len ≥ 1.)
	Path []module.Version

	// If Err is nil, Constraint is a module version passed in the mustSelect
	// argument that has the same module path as, and a lower version than,
	// the last element of the Path slice.
	Constraint module.Version

	// If Constraint is unset, Err is an error encountered when loading the
	// requirements of the last element in Path.
	Err error
}

A Conflict is a path of requirements starting at a root or proposed root in the requirement graph, explaining why that root either causes a module passed in the mustSelect list to EditBuildList to be unattainable, or introduces an unresolvable error in loading the requirement graph.

func (Conflict) String added in v0.7.2202

func (c Conflict) String() string

String returns a string that describes the full conflict path.

func (Conflict) Summary added in v0.7.2202

func (c Conflict) Summary() string

Summary returns a string that describes only the first and last modules in the conflict path.

func (Conflict) UnwrapModuleError added in v0.7.2202

func (c Conflict) UnwrapModuleError() error

UnwrapModuleError returns c.Err, but unwraps it if it is a module.ModuleError with a version and path matching the last entry in the Path slice.

type ConstraintError

type ConstraintError struct {
	// Conflict lists the source of the conflict for each version in mustSelect
	// that could not be selected due to the requirements of some other version in
	// mustSelect.
	Conflicts []Conflict
}

A ConstraintError describes inconsistent constraints in EditBuildList

func (*ConstraintError) Error

func (e *ConstraintError) Error() string

type DirectImportFromImplicitDependencyError

type DirectImportFromImplicitDependencyError struct {
	ImporterPath string
	ImportedPath string
	Module       module.Version
}

A DirectImportFromImplicitDependencyError indicates a package directly imported by a package or test in the main module that is satisfied by a dependency that is not explicit in the main module's go.mod file.

func (*DirectImportFromImplicitDependencyError) Error

func (*DirectImportFromImplicitDependencyError) ImportPath

type ImportMissingError

type ImportMissingError struct {
	Path     string
	Module   module.Version
	QueryErr error

	ImportingMainModule module.Version
	// contains filtered or unexported fields
}

func (*ImportMissingError) Error

func (e *ImportMissingError) Error() string

func (*ImportMissingError) ImportPath

func (e *ImportMissingError) ImportPath() string

func (*ImportMissingError) Unwrap

func (e *ImportMissingError) Unwrap() error

type ImportMissingSumError

type ImportMissingSumError struct {
	// contains filtered or unexported fields
}

ImportMissingSumError is reported in readonly mode when we need to check if a module contains a package, but we don't have a sum for its .zip file. We might need sums for multiple modules to verify the package is unique.

TODO(#43653): consolidate multiple errors of this type into a single error that suggests a 'go get' command for root packages that transitively import packages from modules with missing sums. load.CheckPackageErrors would be a good place to consolidate errors, but we'll need to attach the import stack here.

func (*ImportMissingSumError) Error

func (e *ImportMissingSumError) Error() string

func (*ImportMissingSumError) ImportPath

func (e *ImportMissingSumError) ImportPath() string

type ListMode

type ListMode int
const (
	ListU ListMode = 1 << iota
	ListRetracted
	ListDeprecated
	ListVersions
	ListRetractedVersions
)

type MainModuleSet

type MainModuleSet struct {
	// contains filtered or unexported fields
}
var MainModules *MainModuleSet

func (*MainModuleSet) Contains

func (mms *MainModuleSet) Contains(path string) bool

func (*MainModuleSet) DirImportPath

func (mms *MainModuleSet) DirImportPath(ctx context.Context, dir string) (path string, m module.Version)

DirImportPath returns the effective import path for dir, provided it is within a main module, or else returns ".".

func (*MainModuleSet) GetSingleIndexOrNil

func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex

func (*MainModuleSet) GoVersion

func (mms *MainModuleSet) GoVersion() string

GoVersion returns the go version set on the single module, in module mode, or the go.work file in workspace mode.

func (*MainModuleSet) HighestReplaced

func (mms *MainModuleSet) HighestReplaced() map[string]string

func (*MainModuleSet) InGorootSrc

func (mms *MainModuleSet) InGorootSrc(m module.Version) bool

func (*MainModuleSet) Index

func (mms *MainModuleSet) Index(m module.Version) *modFileIndex

func (*MainModuleSet) Len

func (mms *MainModuleSet) Len() int

func (*MainModuleSet) ModContainingCWD

func (mms *MainModuleSet) ModContainingCWD() module.Version

ModContainingCWD returns the main module containing the working directory, or module.Version{} if none of the main modules contain the working directory.

func (*MainModuleSet) ModFile

func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File

func (*MainModuleSet) ModRoot

func (mms *MainModuleSet) ModRoot(m module.Version) string

func (*MainModuleSet) PathPrefix

func (mms *MainModuleSet) PathPrefix(m module.Version) string

func (*MainModuleSet) SetIndex

func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex)

func (*MainModuleSet) Toolchain added in v0.7.2202

func (mms *MainModuleSet) Toolchain() string

Toolchain returns the toolchain set on the single module, in module mode, or the go.work file in workspace mode.

func (*MainModuleSet) Versions

func (mms *MainModuleSet) Versions() []module.Version

Versions returns the module.Version values of each of the main modules. For each of them, the Path fields are ordinary module paths and the Version fields are empty strings. Callers should not modify the returned slice.

func (*MainModuleSet) WorkFile added in v0.7.2202

func (mms *MainModuleSet) WorkFile() *modfile.WorkFile

func (*MainModuleSet) WorkFileReplaceMap

func (mms *MainModuleSet) WorkFileReplaceMap() map[module.Version]module.Version

type ModuleGraph

type ModuleGraph struct {
	// contains filtered or unexported fields
}

A ModuleGraph represents the complete graph of module dependencies of a main module.

If the main module supports module graph pruning, the graph does not include transitive dependencies of non-root (implicit) dependencies.

func LoadModGraph

func LoadModGraph(ctx context.Context, goVersion string) (*ModuleGraph, error)

LoadModGraph loads and returns the graph of module dependencies of the main module, without loading any packages.

If the goVersion string is non-empty, the returned graph is the graph as interpreted by the given Go version (instead of the version indicated in the go.mod file).

Modules are loaded automatically (and lazily) in LoadPackages: LoadModGraph need only be called if LoadPackages is not, typically in commands that care about modules but no particular package.

func (*ModuleGraph) BuildList

func (mg *ModuleGraph) BuildList() []module.Version

BuildList returns the selected versions of all modules present in the graph, beginning with the main modules.

The order of the remaining elements in the list is deterministic but arbitrary.

The caller must not modify the returned list, but may safely append to it and may rely on it not to be modified.

func (*ModuleGraph) RequiredBy

func (mg *ModuleGraph) RequiredBy(m module.Version) (reqs []module.Version, ok bool)

RequiredBy returns the dependencies required by module m in the graph, or ok=false if module m's dependencies are pruned out.

The caller must not modify the returned slice, but may safely append to it and may rely on it not to be modified.

func (*ModuleGraph) Selected

func (mg *ModuleGraph) Selected(path string) (version string)

Selected returns the selected version of the module with the given path.

If no version is selected, Selected returns version "none".

func (*ModuleGraph) WalkBreadthFirst

func (mg *ModuleGraph) WalkBreadthFirst(f func(m module.Version))

WalkBreadthFirst invokes f once, in breadth-first order, for each module version other than "none" that appears in the graph, regardless of whether that version is selected.

type ModuleRetractedError

type ModuleRetractedError struct {
	Rationale []string
}

func (*ModuleRetractedError) Error

func (e *ModuleRetractedError) Error() string

func (*ModuleRetractedError) Is

func (e *ModuleRetractedError) Is(err error) bool

type NoMatchingVersionError

type NoMatchingVersionError struct {
	// contains filtered or unexported fields
}

A NoMatchingVersionError indicates that Query found a module at the requested path, but not at any versions satisfying the query string and allow-function.

NOTE: NoMatchingVersionError MUST NOT implement Is(fs.ErrNotExist).

If the module came from a proxy, that proxy had to return a successful status code for the versions it knows about, and thus did not have the opportunity to return a non-400 status code to suppress fallback.

func (*NoMatchingVersionError) Error

func (e *NoMatchingVersionError) Error() string

type NoPatchBaseError

type NoPatchBaseError struct {
	// contains filtered or unexported fields
}

A NoPatchBaseError indicates that Query was called with the query "patch" but with a current version of "" or "none".

func (*NoPatchBaseError) Error

func (e *NoPatchBaseError) Error() string

type PackageNotInModuleError

type PackageNotInModuleError struct {
	MainModules []module.Version
	Mod         module.Version
	Replacement module.Version
	Query       string
	Pattern     string
}

A PackageNotInModuleError indicates that QueryPattern found a candidate module at the requested version, but that module did not contain any packages matching the requested pattern.

NOTE: PackageNotInModuleError MUST NOT implement Is(fs.ErrNotExist).

If the module came from a proxy, that proxy had to return a successful status code for the versions it knows about, and thus did not have the opportunity to return a non-400 status code to suppress fallback.

func (*PackageNotInModuleError) Error

func (e *PackageNotInModuleError) Error() string

func (*PackageNotInModuleError) ImportPath

func (e *PackageNotInModuleError) ImportPath() string

type PackageOpts

type PackageOpts struct {
	// TidyGoVersion is the Go version to which the go.mod file should be updated
	// after packages have been loaded.
	//
	// An empty TidyGoVersion means to use the Go version already specified in the
	// main module's go.mod file, or the latest Go version if there is no main
	// module.
	TidyGoVersion string

	// Tags are the build tags in effect (as interpreted by the
	// cmd/go/internal/imports package).
	// If nil, treated as equivalent to imports.Tags().
	Tags map[string]bool

	// Tidy, if true, requests that the build list and go.sum file be reduced to
	// the minimal dependencies needed to reproducibly reload the requested
	// packages.
	Tidy bool

	// TidyCompatibleVersion is the oldest Go version that must be able to
	// reproducibly reload the requested packages.
	//
	// If empty, the compatible version is the Go version immediately prior to the
	// 'go' version listed in the go.mod file.
	TidyCompatibleVersion string

	// VendorModulesInGOROOTSrc indicates that if we are within a module in
	// GOROOT/src, packages in the module's vendor directory should be resolved as
	// actual module dependencies (instead of standard-library packages).
	VendorModulesInGOROOTSrc bool

	// ResolveMissingImports indicates that we should attempt to add module
	// dependencies as needed to resolve imports of packages that are not found.
	//
	// For commands that support the -mod flag, resolving imports may still fail
	// if the flag is set to "readonly" (the default) or "vendor".
	ResolveMissingImports bool

	// AssumeRootsImported indicates that the transitive dependencies of the root
	// packages should be treated as if those roots will be imported by the main
	// module.
	AssumeRootsImported bool

	// AllowPackage, if non-nil, is called after identifying the module providing
	// each package. If AllowPackage returns a non-nil error, that error is set
	// for the package, and the imports and test of that package will not be
	// loaded.
	//
	// AllowPackage may be invoked concurrently by multiple goroutines,
	// and may be invoked multiple times for a given package path.
	AllowPackage func(ctx context.Context, path string, mod module.Version) error

	// LoadTests loads the test dependencies of each package matching a requested
	// pattern. If ResolveMissingImports is also true, test dependencies will be
	// resolved if missing.
	LoadTests bool

	// UseVendorAll causes the "all" package pattern to be interpreted as if
	// running "go mod vendor" (or building with "-mod=vendor").
	//
	// This is a no-op for modules that declare 'go 1.16' or higher, for which this
	// is the default (and only) interpretation of the "all" pattern in module mode.
	UseVendorAll bool

	// AllowErrors indicates that LoadPackages should not terminate the process if
	// an error occurs.
	AllowErrors bool

	// SilencePackageErrors indicates that LoadPackages should not print errors
	// that occur while matching or loading packages, and should not terminate the
	// process if such an error occurs.
	//
	// Errors encountered in the module graph will still be reported.
	//
	// The caller may retrieve the silenced package errors using the Lookup
	// function, and matching errors are still populated in the Errs field of the
	// associated search.Match.)
	SilencePackageErrors bool

	// SilenceMissingStdImports indicates that LoadPackages should not print
	// errors or terminate the process if an imported package is missing, and the
	// import path looks like it might be in the standard library (perhaps in a
	// future version).
	SilenceMissingStdImports bool

	// SilenceNoGoErrors indicates that LoadPackages should not print
	// imports.ErrNoGo errors.
	// This allows the caller to invoke LoadPackages (and report other errors)
	// without knowing whether the requested packages exist for the given tags.
	//
	// Note that if a requested package does not exist *at all*, it will fail
	// during module resolution and the error will not be suppressed.
	SilenceNoGoErrors bool

	// SilenceUnmatchedWarnings suppresses the warnings normally emitted for
	// patterns that did not match any packages.
	SilenceUnmatchedWarnings bool

	// Resolve the query against this module.
	MainModule module.Version

	// If Switcher is non-nil, then LoadPackages passes all encountered errors
	// to Switcher.Error and tries Switcher.Switch before base.ExitIfErrors.
	Switcher gover.Switcher
}

PackageOpts control the behavior of the LoadPackages function.

type QueryMatchesMainModulesError

type QueryMatchesMainModulesError struct {
	MainModules []module.Version
	Pattern     string
	Query       string
}

A QueryMatchesMainModulesError indicates that a query requests a version of the main module that cannot be satisfied. (The main module's version cannot be changed.)

func (*QueryMatchesMainModulesError) Error

type QueryMatchesPackagesInMainModuleError

type QueryMatchesPackagesInMainModuleError struct {
	Pattern  string
	Query    string
	Packages []string
}

A QueryMatchesPackagesInMainModuleError indicates that a query cannot be satisfied because it matches one or more packages found in the main module.

func (*QueryMatchesPackagesInMainModuleError) Error

type QueryResult

type QueryResult struct {
	Mod      module.Version
	Rev      *modfetch.RevInfo
	Packages []string
}

func QueryPackages

func QueryPackages(ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) ([]QueryResult, error)

QueryPackages is like QueryPattern, but requires that the pattern match at least one package and omits the non-package result (if any).

type QueryUpgradesAllError

type QueryUpgradesAllError struct {
	MainModules []module.Version
	Query       string
}

A QueryUpgradesAllError indicates that a query requests an upgrade on the all pattern. (The main module's version cannot be changed.)

func (*QueryUpgradesAllError) Error

func (e *QueryUpgradesAllError) Error() string

type Requirements

type Requirements struct {
	// contains filtered or unexported fields
}

A Requirements represents a logically-immutable set of root module requirements.

func LoadModFile

func LoadModFile(ctx context.Context) *Requirements

LoadModFile sets Target and, if there is a main module, parses the initial build list from its go.mod file.

LoadModFile may make changes in memory, like adding a go directive and ensuring requirements are consistent. The caller is responsible for ensuring those changes are written to disk by calling LoadPackages or ListModules (unless ExplicitWriteGoMod is set) or by calling WriteGoMod directly.

As a side-effect, LoadModFile may change cfg.BuildMod to "vendor" if -mod wasn't set explicitly and automatic vendoring should be enabled.

If LoadModFile or CreateModFile has already been called, LoadModFile returns the existing in-memory requirements (rather than re-reading them from disk).

LoadModFile checks the roots of the module graph for consistency with each other, but unlike LoadModGraph does not load the full module graph or check it for global consistency. Most callers outside of the modload package should use LoadModGraph instead.

func (*Requirements) GoVersion added in v0.7.2202

func (rs *Requirements) GoVersion() string

GoVersion returns the Go language version for the Requirements.

func (*Requirements) Graph

func (rs *Requirements) Graph(ctx context.Context) (*ModuleGraph, error)

Graph returns the graph of module requirements loaded from the current root modules (as reported by RootModules).

Graph always makes a best effort to load the requirement graph despite any errors, and always returns a non-nil *ModuleGraph.

If the requirements of any relevant module fail to load, Graph also returns a non-nil error of type *mvs.BuildListError.

func (*Requirements) IsDirect

func (rs *Requirements) IsDirect(path string) bool

IsDirect returns whether the given module provides a package directly imported by a package or test in the main module.

func (*Requirements) String added in v0.7.2202

func (rs *Requirements) String() string

String returns a string describing the Requirements for debugging.

type Root

type Root int
const (
	// AutoRoot is the default for most commands. modload.Init will look for
	// a go.mod file in the current directory or any parent. If none is found,
	// modules may be disabled (GO111MODULE=auto) or commands may run in a
	// limited module mode.
	AutoRoot Root = iota

	// NoRoot is used for commands that run in module mode and ignore any go.mod
	// file the current directory or in parent directories.
	NoRoot

	// NeedRoot is used for commands that must run in module mode and don't
	// make sense without a main module.
	NeedRoot
)

type WildcardInFirstElementError

type WildcardInFirstElementError struct {
	Pattern string
	Query   string
}

A WildcardInFirstElementError indicates that a pattern passed to QueryPattern had a wildcard in its first path element, and therefore had no pattern-prefix modules to search in.

func (*WildcardInFirstElementError) Error

type WriteOpts added in v0.7.2202

type WriteOpts struct {
	DropToolchain     bool // go get toolchain@none
	ExplicitToolchain bool // go get has set explicit toolchain version

	// TODO(bcmills): Make 'go mod tidy' update the go version in the Requirements
	// instead of writing directly to the modfile.File
	TidyWroteGo bool // Go.Version field already updated by 'go mod tidy'
}

WriteOpts control the behavior of WriteGoMod.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL