modload

package standard library
go1.23.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2024 License: BSD-3-Clause Imports: 46 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 added in go1.14

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 added in go1.16

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 added in go1.17

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 added in go1.16

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 CheckGodebug added in go1.23.0

func CheckGodebug(verb, k, v string) error

func CheckRetractions added in go1.16

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 added in go1.16

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 added in go1.16

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 added in go1.18

func EnterModule(ctx context.Context, enterModroot string)

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

func FindGoMod added in go1.21.0

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 go1.21.0

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 added in go1.12

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 added in go1.18

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 added in go1.16

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 added in go1.16

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 added in go1.16

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 added in go1.14

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 added in go1.18

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 added in go1.18

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 go1.21.0

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

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

func PackageModRoot added in go1.19

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 added in go1.13

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 added in go1.18

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 added in go1.18

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 go1.21.0

func Reset()

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

func ShortMessage added in go1.17

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 added in go1.18

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 UpdateGoModFromReqs added in go1.23.0

func UpdateGoModFromReqs(ctx context.Context, opts WriteOpts) (before, after []byte, modFile *modfile.File, err error)

UpdateGoModFromReqs returns a modified go.mod file using the current requirements. It does not commit these changes to disk.

func UpdateWorkFile added in go1.18

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 go1.21.0

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 added in go1.18

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 added in go1.14

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 added in go1.18

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 added in go1.18

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

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

Types

type AllowedFunc added in go1.16

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 added in go1.14

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 added in go1.14

func (e *AmbiguousImportError) Error() string

func (*AmbiguousImportError) ImportPath added in go1.14

func (e *AmbiguousImportError) ImportPath() string

type Conflict added in go1.16

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 go1.21.0

func (c Conflict) String() string

String returns a string that describes the full conflict path.

func (Conflict) Summary added in go1.21.0

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 go1.21.0

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 added in go1.16

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 added in go1.16

func (e *ConstraintError) Error() string

type DirectImportFromImplicitDependencyError added in go1.17

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 added in go1.17

func (*DirectImportFromImplicitDependencyError) ImportPath added in go1.17

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 added in go1.14

func (e *ImportMissingError) Unwrap() error

type ImportMissingSumError added in go1.16

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 added in go1.16

func (e *ImportMissingSumError) Error() string

func (*ImportMissingSumError) ImportPath added in go1.16

func (e *ImportMissingSumError) ImportPath() string

type ListMode added in go1.17

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

type MainModuleSet added in go1.18

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

func (*MainModuleSet) Contains added in go1.18

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

func (*MainModuleSet) DirImportPath added in go1.18

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 added in go1.18

func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex

func (*MainModuleSet) GoVersion added in go1.18

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) Godebugs added in go1.23.0

func (mms *MainModuleSet) Godebugs() []*modfile.Godebug

Godebugs returns the godebug lines set on the single module, in module mode, or on the go.work file in workspace mode. The caller must not modify the result.

func (*MainModuleSet) HighestReplaced added in go1.18

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

func (*MainModuleSet) InGorootSrc added in go1.18

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

func (*MainModuleSet) Index added in go1.18

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

func (*MainModuleSet) Len added in go1.18

func (mms *MainModuleSet) Len() int

func (*MainModuleSet) ModContainingCWD added in go1.18

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 added in go1.18

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

func (*MainModuleSet) ModRoot added in go1.18

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

func (*MainModuleSet) PathPrefix added in go1.18

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

func (*MainModuleSet) SetIndex added in go1.18

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

func (*MainModuleSet) Toolchain added in go1.21.0

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 added in go1.18

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 go1.22.0

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

func (*MainModuleSet) WorkFileReplaceMap added in go1.18

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

type ModuleGraph added in go1.17

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 added in go1.17

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 added in go1.17

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 added in go1.17

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 added in go1.17

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 added in go1.17

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 added in go1.16

type ModuleRetractedError struct {
	Rationale []string
}

func (*ModuleRetractedError) Error added in go1.16

func (e *ModuleRetractedError) Error() string

func (*ModuleRetractedError) Is added in go1.16

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

type NoMatchingVersionError added in go1.13

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 added in go1.13

func (e *NoMatchingVersionError) Error() string

type NoPatchBaseError added in go1.16

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 added in go1.16

func (e *NoPatchBaseError) Error() string

type PackageNotInModuleError added in go1.13

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 added in go1.13

func (e *PackageNotInModuleError) Error() string

func (*PackageNotInModuleError) ImportPath added in go1.15

func (e *PackageNotInModuleError) ImportPath() string

type PackageOpts added in go1.16

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

	// TidyDiff, if true, causes tidy not to modify go.mod or go.sum but
	// instead print the necessary changes as a unified diff. It exits
	// with a non-zero code if the diff is not empty.
	TidyDiff 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 added in go1.18

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 added in go1.18

type QueryMatchesPackagesInMainModuleError added in go1.16

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 added in go1.16

type QueryResult added in go1.13

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

func QueryPackages added in go1.16

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 added in go1.18

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 added in go1.18

func (e *QueryUpgradesAllError) Error() string

type Requirements added in go1.17

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

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

func LoadModFile added in go1.16

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 go1.21.0

func (rs *Requirements) GoVersion() string

GoVersion returns the Go language version for the Requirements.

func (*Requirements) Graph added in go1.17

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 added in go1.17

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 go1.21.0

func (rs *Requirements) String() string

String returns a string describing the Requirements for debugging.

type Root added in go1.16

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 added in go1.16

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 added in go1.16

type WriteOpts added in go1.21.0

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