modload

package standard library
go1.16.12 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2021 License: BSD-3-Clause Imports: 39 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Target module.Version

	// 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
)
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 help 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.

func AllowWriteGoMod

func AllowWriteGoMod()

AllowWriteGoMod undoes the effect of DisallowWriteGoMod: future calls to WriteGoMod will update go.mod if needed. Note that any past calls have been discarded, so typically a call to AlowWriteGoMod should be followed by a call to WriteGoMod.

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

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

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

func CheckTidyVersion added in go1.15.13

func CheckTidyVersion(ctx context.Context, allowError bool)

CheckTidyVersion reports an error to stderr if the Go version indicated by the go.mod file is not supported by this version of the 'go' command.

If allowError is false, such an error terminates the program.

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 DirImportPath

func DirImportPath(dir string) string

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

func DisallowWriteGoMod

func DisallowWriteGoMod()

DisallowWriteGoMod causes future calls to WriteGoMod to do nothing at all.

func EditBuildList added in go1.16

func EditBuildList(ctx context.Context, add, mustSelect []module.Version) 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.

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

func ImportMap

func ImportMap(path string) string

ImportMap returns the actual package import path for an import path found in source code. If the given import path does not appear in the source code for the packages that have been loaded, ImportMap returns the empty string.

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

func IsRevisionQuery(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, listU, listVersions, listRetracted bool) []*modinfo.ModulePublic

func LoadAllModules added in go1.16

func LoadAllModules(ctx context.Context) []module.Version

LoadAllModules loads and returns the list of modules matching the "all" module pattern, starting with the Target module and in a deterministic (stable) order, without loading any packages.

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

The caller must not modify the returned list, but may append to it.

func LoadModFile added in go1.16

func LoadModFile(ctx context.Context)

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. WriteGoMod should be called later to write changes out to disk or report errors in readonly mode.

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

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 MinReqs

func MinReqs() mvs.Reqs

MinReqs returns a Reqs with minimal additional dependencies of Target, as will be written to go.mod.

func ModFile

func ModFile() *modfile.File

ModFile returns the parsed go.mod file.

Note that after calling LoadPackages or LoadAllModules, 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 effective path of the go.mod file. Normally, this "go.mod" in the directory returned by ModRoot, but the -modfile flag may change its location. ModFilePath calls base.Fatalf if there is no main module, even if -modfile is set.

func ModInfoProg

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

func ModRoot

func ModRoot() string

ModRoot returns the root of the main module. It calls base.Fatalf if there is no main module.

func ModuleHasRootPackage added in go1.13

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

ModuleHasRootPackage returns whether module m contains a package m.Path.

func ModuleInfo

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

func PackageBuildInfo

func PackageBuildInfo(path string, deps []string) string

PackageBuildInfo returns a string containing module version information for modules providing packages named by path and deps. path and deps must name packages that were resolved successfully with LoadPackages.

func PackageDir

func PackageDir(path string) string

PackageDir returns the directory containing the source code for the package named by the import path.

func PackageImports added in go1.13

func PackageImports(path string) (imports, testImports []string)

PackageImports returns the imports for the package named by the import path. Test imports will be returned as well if tests were loaded for the package (i.e., if "all" was loaded or if LoadTests was set and the path was matched by a command line argument). PackageImports will return nil for unknown package paths.

func PackageModule

func PackageModule(path string) module.Version

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

func PackageModuleInfo

func PackageModuleInfo(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.

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 ReloadBuildList

func ReloadBuildList() []module.Version

ReloadBuildList resets the state of loaded packages, then loads and returns the build list set by EditBuildList.

func Replacement

func Replacement(mod module.Version) module.Version

Replacement returns the replacement for mod, if any, from go.mod. If there is no replacement for mod, Replacement returns a module.Version with Path == "".

func Selected added in go1.16

func Selected(path string) (version string)

Selected returns the selected version of the module with the given path, or the empty string if the given module has no selected version (either because it is not required or because it is the Target module).

func ShortRetractionRationale added in go1.16

func ShortRetractionRationale(rationale string) string

ShortRetractionRationale returns a retraction rationale string that is safe to print in a terminal. It returns hard-coded strings if the rationale is empty, too long, or contains non-printable characters.

func TargetPackages

func TargetPackages(ctx context.Context, pattern string) *search.Match

TargetPackages returns the list of packages in the target (top-level) module matching pattern, which may be relative to the working directory, under all build tag settings.

func TidyBuildList added in go1.14

func TidyBuildList()

TidyBuildList trims the build list to the minimal requirements needed to retain the same versions of all packages from the preceding call to LoadPackages.

func TrimGoSum added in go1.16

func TrimGoSum()

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 WriteGoMod

func WriteGoMod()

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

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 ErrDisallowd 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 {
	Source     module.Version
	Dep        module.Version
	Constraint module.Version
}

A Conflict documents that Source requires Dep, which conflicts with Constraint. (That is, Dep has the same module path as Constraint but a higher version.)

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 ImportMissingError

type ImportMissingError struct {
	Path     string
	Module   module.Version
	QueryErr error
	// 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 transtively 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 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 {
	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 {
	// 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

	// 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

	// 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

	// SilenceErrors indicates that LoadPackages should not print errors
	// that occur while loading packages. SilenceErrors implies AllowErrors.
	SilenceErrors 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

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

PackageOpts control the behavior of the LoadPackages function.

type QueryMatchesMainModuleError added in go1.16

type QueryMatchesMainModuleError struct {
	Pattern string
	Query   string
}

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

func (*QueryMatchesMainModuleError) Error added in go1.16

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 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=on) 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

Jump to

Keyboard shortcuts

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