modload

package standard library
go1.16beta1 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2020 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 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 itself is line-oriented, with // comments but
no /* */ comments. Each line holds a single directive, made up of a
verb followed by arguments. For example:

	module my/thing
	go 1.12
	require other/thing v1.0.2
	require new/thing/v2 v2.3.4
	exclude old/thing v1.2.3
	replace bad/thing v1.4.5 => good/thing v1.4.5
	retract v1.5.6

The verbs are
	module, to define the module path;
	go, to set the expected language version;
	require, to require a particular module at a given version or later;
	exclude, to exclude a particular module version from use;
	replace, to replace a module version with a different module version; and
	retract, to indicate a previously released version should not be used.
Exclude and replace apply only in the main module's go.mod and are ignored
in dependencies.  See https://golang.ir/ref/mod for details.

The leading verb can be factored out of adjacent lines to create a block,
like in Go imports:

	require (
		new/thing/v2 v2.3.4
		old/thing v1.2.3
	)

The go.mod file is designed both to be edited directly and to be
easily updated by tools. The 'go mod edit' command can be used to
parse and edit the go.mod file from programs and tools.
See 'go help mod edit'.

The go command automatically updates go.mod each time it uses the
module graph, to make sure go.mod always accurately reflects reality
and is properly formatted. For example, consider this go.mod file:

        module M

        require (
                A v1
                B v1.0.0
                C v1.0.0
                D v1.2.3
                E dev
        )

        exclude D v1.2.3

The update rewrites non-canonical version identifiers to semver form,
so A's v1 becomes v1.0.0 and E's dev becomes the pseudo-version for the
latest commit on the dev branch, perhaps v0.0.0-20180523231146-b3f5c0f6e5f1.

The update modifies requirements to respect exclusions, so the
requirement on the excluded D v1.2.3 is updated to use the next
available version of D, perhaps D v1.2.4 or D v1.3.0.

The update removes redundant or misleading requirements.
For example, if A v1.0.0 itself requires B v1.2.0 and C v1.0.0,
then go.mod's requirement of B v1.0.0 is misleading (superseded by
A's need for v1.2.0), and its requirement of C v1.0.0 is redundant
(implied by A's need for the same version), so both will be removed.
If module M contains packages that directly import packages from B or
C, then the requirements will be kept but updated to the actual
versions being used.

Finally, the update reformats the go.mod in a canonical formatting, so
that future mechanical changes will result in minimal diffs.

Because the module graph defines the meaning of import statements, any
commands that load packages also use and therefore update go.mod,
including go build, go get, go install, go list, go test, go mod graph,
go mod tidy, and go mod why.

The expected language version, set by the go directive, determines
which language features are available when compiling the module.
Language features available in that version will be available for use.
Language features removed in earlier versions, or added in later versions,
will not be available. Note that the language version does not affect
build tags, which are determined by the Go release being used.
	`,
}
View Source
var HelpModules = &base.Command{
	UsageLine: "modules",
	Short:     "modules, module versions, and more",
	Long: `
A module is a collection of related Go packages.
Modules are the unit of source code interchange and versioning.
The go command has direct support for working with modules,
including recording and resolving dependencies on other modules.
Modules replace the old GOPATH-based approach to specifying
which source files are used in a given build.

Module support

The go command includes support for Go modules. Module-aware mode is active
by default whenever a go.mod file is found in the current directory or in
any parent directory.

The quickest way to take advantage of module support is to check out your
repository, create a go.mod file (described in the next section) there, and run
go commands from within that file tree.

For more fine-grained control, the go command continues to respect
a temporary environment variable, GO111MODULE, which can be set to one
of three string values: off, on, or auto (the default).
If GO111MODULE=on, then the go command requires the use of modules,
never consulting GOPATH. We refer to this as the command
being module-aware or running in "module-aware mode".
If GO111MODULE=off, then the go command never uses
module support. Instead it looks in vendor directories and GOPATH
to find dependencies; we now refer to this as "GOPATH mode."
If GO111MODULE=auto or is unset, then the go command enables or disables
module support based on the current directory.
Module support is enabled only when the current directory contains a
go.mod file or is below a directory containing a go.mod file.

In module-aware mode, GOPATH no longer defines the meaning of imports
during a build, but it still stores downloaded dependencies (in GOPATH/pkg/mod)
and installed commands (in GOPATH/bin, unless GOBIN is set).

Defining a module

A module is defined by a tree of Go source files with a go.mod file
in the tree's root directory. The directory containing the go.mod file
is called the module root. Typically the module root will also correspond
to a source code repository root (but in general it need not).
The module is the set of all Go packages in the module root and its
subdirectories, but excluding subtrees with their own go.mod files.

The "module path" is the import path prefix corresponding to the module root.
The go.mod file defines the module path and lists the specific versions
of other modules that should be used when resolving imports during a build,
by giving their module paths and versions.

For example, this go.mod declares that the directory containing it is the root
of the module with path example.com/m, and it also declares that the module
depends on specific versions of golang.org/x/text and gopkg.in/yaml.v2:

	module example.com/m

	require (
		golang.org/x/text v0.3.0
		gopkg.in/yaml.v2 v2.1.0
	)

The go.mod file can also specify replacements and excluded versions
that only apply when building the module directly; they are ignored
when the module is incorporated into a larger build.
For more about the go.mod file, see 'go help go.mod'.

To start a new module, simply create a go.mod file in the root of the
module's directory tree, containing only a module statement.
The 'go mod init' command can be used to do this:

	go mod init example.com/m

In a project already using an existing dependency management tool like
godep, glide, or dep, 'go mod init' will also add require statements
matching the existing configuration.

Once the go.mod file exists, no additional steps are required:
go commands like 'go build', 'go test', or even 'go list' will automatically
add new dependencies as needed to satisfy imports.

The main module and the build list

The "main module" is the module containing the directory where the go command
is run. The go command finds the module root by looking for a go.mod in the
current directory, or else the current directory's parent directory,
or else the parent's parent directory, and so on.

The main module's go.mod file defines the precise set of packages available
for use by the go command, through require, replace, and exclude statements.
Dependency modules, found by following require statements, also contribute
to the definition of that set of packages, but only through their go.mod
files' require statements: any replace and exclude statements in dependency
modules are ignored. The replace and exclude statements therefore allow the
main module complete control over its own build, without also being subject
to complete control by dependencies.

The set of modules providing packages to builds is called the "build list".
The build list initially contains only the main module. Then the go command
adds to the list the exact module versions required by modules already
on the list, recursively, until there is nothing left to add to the list.
If multiple versions of a particular module are added to the list,
then at the end only the latest version (according to semantic version
ordering) is kept for use in the build.

The 'go list' command provides information about the main module
and the build list. For example:

	go list -m              # print path of main module
	go list -m -f={{.Dir}}  # print root directory of main module
	go list -m all          # print build list

Maintaining module requirements

The go.mod file is meant to be readable and editable by both programmers and
tools. Most updates to dependencies can be performed using "go get" and
"go mod tidy". Other module-aware build commands may be invoked using the
-mod=mod flag to automatically add missing requirements and fix inconsistencies.

The "go get" command updates go.mod to change the module versions used in a
build. An upgrade of one module may imply upgrading others, and similarly a
downgrade of one module may imply downgrading others. The "go get" command
makes these implied changes as well. See "go help module-get".

The "go mod" command provides other functionality for use in maintaining
and understanding modules and go.mod files. See "go help mod", particularly
"go help mod tidy" and "go help mod edit".

As part of maintaining the require statements in go.mod, the go command
tracks which ones provide packages imported directly by the current module
and which ones provide packages only used indirectly by other module
dependencies. Requirements needed only for indirect uses are marked with a
"// indirect" comment in the go.mod file. Indirect requirements may be
automatically removed from the go.mod file once they are implied by other
direct requirements. Indirect requirements only arise when using modules
that fail to state some of their own dependencies or when explicitly
upgrading a module's dependencies ahead of its own stated requirements.

The -mod build flag provides additional control over the updating and use of
go.mod for commands that build packages like "go build" and "go test".

If invoked with -mod=readonly (the default in most situations), the go command
reports an error if a package named on the command line or an imported package
is not provided by any module in the build list computed from the main module's
requirements. The go command also reports an error if a module's checksum is
missing from go.sum (see Module downloading and verification). Either go.mod or
go.sum must be updated in these situations.

If invoked with -mod=mod, the go command automatically updates go.mod and
go.sum, fixing inconsistencies and adding missing requirements and checksums
as needed. If the go command finds an unfamiliar import, it looks up the
module containing that import and adds a requirement for the latest version
of that module to go.mod. In most cases, therefore, one may add an import to
source code and run "go build", "go test", or even "go list" with -mod=mod:
as part of analyzing the package, the go command will resolve the import and
update the go.mod file.

If invoked with -mod=vendor, the go command loads packages from the main
module's vendor directory instead of downloading modules to and loading packages
from the module cache. The go command assumes the vendor directory holds
correct copies of dependencies, and it does not compute the set of required
module versions from go.mod files. However, the go command does check that
vendor/modules.txt (generated by "go mod vendor") contains metadata consistent
with go.mod.

If the go command is not invoked with a -mod flag, and the vendor directory
is present, and the "go" version in go.mod is 1.14 or higher, the go command
will act as if it were invoked with -mod=vendor. Otherwise, the -mod flag
defaults to -mod=readonly.

Note that neither "go get" nor the "go mod" subcommands accept the -mod flag.

Pseudo-versions

The go.mod file and the go command more generally use semantic versions as
the standard form for describing module versions, so that versions can be
compared to determine which should be considered earlier or later than another.
A module version like v1.2.3 is introduced by tagging a revision in the
underlying source repository. Untagged revisions can be referred to
using a "pseudo-version" like v0.0.0-yyyymmddhhmmss-abcdefabcdef,
where the time is the commit time in UTC and the final suffix is the prefix
of the commit hash. The time portion ensures that two pseudo-versions can
be compared to determine which happened later, the commit hash identifes
the underlying commit, and the prefix (v0.0.0- in this example) is derived from
the most recent tagged version in the commit graph before this commit.

There are three pseudo-version forms:

vX.0.0-yyyymmddhhmmss-abcdefabcdef is used when there is no earlier
versioned commit with an appropriate major version before the target commit.
(This was originally the only form, so some older go.mod files use this form
even for commits that do follow tags.)

vX.Y.Z-pre.0.yyyymmddhhmmss-abcdefabcdef is used when the most
recent versioned commit before the target commit is vX.Y.Z-pre.

vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdefabcdef is used when the most
recent versioned commit before the target commit is vX.Y.Z.

Pseudo-versions never need to be typed by hand: the go command will accept
the plain commit hash and translate it into a pseudo-version (or a tagged
version if available) automatically. This conversion is an example of a
module query.

Module queries

The go command accepts a "module query" in place of a module version
both on the command line and in the main module's go.mod file.
(After evaluating a query found in the main module's go.mod file,
the go command updates the file to replace the query with its result.)

A fully-specified semantic version, such as "v1.2.3",
evaluates to that specific version.

A semantic version prefix, such as "v1" or "v1.2",
evaluates to the latest available tagged version with that prefix.

A semantic version comparison, such as "<v1.2.3" or ">=v1.5.6",
evaluates to the available tagged version nearest to the comparison target
(the latest version for < and <=, the earliest version for > and >=).

The string "latest" matches the latest available tagged version,
or else the underlying source repository's latest untagged revision.

The string "upgrade" is like "latest", but if the module is
currently required at a later version than the version "latest"
would select (for example, a newer pre-release version), "upgrade"
will select the later version instead.

The string "patch" matches the latest available tagged version
of a module with the same major and minor version numbers as the
currently required version. If no version is currently required,
"patch" is equivalent to "latest".

A revision identifier for the underlying source repository, such as
a commit hash prefix, revision tag, or branch name, selects that
specific code revision. If the revision is also tagged with a
semantic version, the query evaluates to that semantic version.
Otherwise the query evaluates to a pseudo-version for the commit.
Note that branches and tags with names that are matched by other
query syntax cannot be selected this way. For example, the query
"v2" means the latest version starting with "v2", not the branch
named "v2".

All queries prefer release versions to pre-release versions.
For example, "<v1.2.3" will prefer to return "v1.2.2"
instead of "v1.2.3-pre1", even though "v1.2.3-pre1" is nearer
to the comparison target.

Module versions disallowed by exclude statements in the
main module's go.mod are considered unavailable and cannot
be returned by queries.

For example, these commands are all valid:

	go get github.com/gorilla/mux@latest    # same (@latest is default for 'go get')
	go get github.com/gorilla/[email protected]    # records v1.6.2
	go get github.com/gorilla/mux@e3702bed2 # records v1.6.2
	go get github.com/gorilla/mux@c856192   # records v0.0.0-20180517173623-c85619274f5d
	go get github.com/gorilla/mux@master    # records current meaning of master

Module compatibility and semantic versioning

The go command requires that modules use semantic versions and expects that
the versions accurately describe compatibility: it assumes that v1.5.4 is a
backwards-compatible replacement for v1.5.3, v1.4.0, and even v1.0.0.
More generally the go command expects that packages follow the
"import compatibility rule", which says:

"If an old package and a new package have the same import path,
the new package must be backwards compatible with the old package."

Because the go command assumes the import compatibility rule,
a module definition can only set the minimum required version of one
of its dependencies: it cannot set a maximum or exclude selected versions.
Still, the import compatibility rule is not a guarantee: it may be that
v1.5.4 is buggy and not a backwards-compatible replacement for v1.5.3.
Because of this, the go command never updates from an older version
to a newer version of a module unasked.

In semantic versioning, changing the major version number indicates a lack
of backwards compatibility with earlier versions. To preserve import
compatibility, the go command requires that modules with major version v2
or later use a module path with that major version as the final element.
For example, version v2.0.0 of example.com/m must instead use module path
example.com/m/v2, and packages in that module would use that path as
their import path prefix, as in example.com/m/v2/sub/pkg. Including the
major version number in the module path and import paths in this way is
called "semantic import versioning". Pseudo-versions for modules with major
version v2 and later begin with that major version instead of v0, as in
v2.0.0-20180326061214-4fc5987536ef.

As a special case, module paths beginning with gopkg.in/ continue to use the
conventions established on that system: the major version is always present,
and it is preceded by a dot instead of a slash: gopkg.in/yaml.v1
and gopkg.in/yaml.v2, not gopkg.in/yaml and gopkg.in/yaml/v2.

The go command treats modules with different module paths as unrelated:
it makes no connection between example.com/m and example.com/m/v2.
Modules with different major versions can be used together in a build
and are kept separate by the fact that their packages use different
import paths.

In semantic versioning, major version v0 is for initial development,
indicating no expectations of stability or backwards compatibility.
Major version v0 does not appear in the module path, because those
versions are preparation for v1.0.0, and v1 does not appear in the
module path either.

Code written before the semantic import versioning convention
was introduced may use major versions v2 and later to describe
the same set of unversioned import paths as used in v0 and v1.
To accommodate such code, if a source code repository has a
v2.0.0 or later tag for a file tree with no go.mod, the version is
considered to be part of the v1 module's available versions
and is given an +incompatible suffix when converted to a module
version, as in v2.0.0+incompatible. The +incompatible tag is also
applied to pseudo-versions derived from such versions, as in
v2.0.1-0.yyyymmddhhmmss-abcdefabcdef+incompatible.

In general, having a dependency in the build list (as reported by 'go list -m all')
on a v0 version, pre-release version, pseudo-version, or +incompatible version
is an indication that problems are more likely when upgrading that
dependency, since there is no expectation of compatibility for those.

See https://research.swtch.com/vgo-import for more information about
semantic import versioning, and see https://semver.org/ for more about
semantic versioning.

Module code layout

For now, see https://research.swtch.com/vgo-module for information
about how source code in version control systems is mapped to
module file trees.

Module downloading and verification

The go command can fetch modules from a proxy or connect to source control
servers directly, according to the setting of the GOPROXY environment
variable (see 'go help env'). The default setting for GOPROXY is
"https://proxy.golang.org,direct", which means to try the
Go module mirror run by Google and fall back to a direct connection
if the proxy reports that it does not have the module (HTTP error 404 or 410).
See https://proxy.golang.org/privacy for the service's privacy policy.

If GOPROXY is set to the string "direct", downloads use a direct connection to
source control servers. Setting GOPROXY to "off" disallows downloading modules
from any source. Otherwise, GOPROXY is expected to be list of module proxy URLs
separated by either comma (,) or pipe (|) characters, which control error
fallback behavior. For each request, the go command tries each proxy in
sequence. If there is an error, the go command will try the next proxy in the
list if the error is a 404 or 410 HTTP response or if the current proxy is
followed by a pipe character, indicating it is safe to fall back on any error.

The GOPRIVATE and GONOPROXY environment variables allow bypassing
the proxy for selected modules. See 'go help private' for details.

No matter the source of the modules, the go command checks downloads against
known checksums, to detect unexpected changes in the content of any specific
module version from one day to the next. This check first consults the current
module's go.sum file but falls back to the Go checksum database, controlled by
the GOSUMDB and GONOSUMDB environment variables. See 'go help module-auth'
for details.

See 'go help goproxy' for details about the proxy protocol and also
the format of the cached downloaded packages.

Modules and vendoring

When using modules, the go command typically satisfies dependencies by
downloading modules from their sources and using those downloaded copies
(after verification, as described in the previous section). Vendoring may
be used to allow interoperation with older versions of Go, or to ensure
that all files used for a build are stored together in a single file tree.

The command 'go mod vendor' constructs a directory named vendor in the main
module's root directory that contains copies of all packages needed to support
builds and tests of packages in the main module. 'go mod vendor' also
creates the file vendor/modules.txt that contains metadata about vendored
packages and module versions. This file should be kept consistent with go.mod:
when vendoring is used, 'go mod vendor' should be run after go.mod is updated.

If the vendor directory is present in the main module's root directory, it will
be used automatically if the "go" version in the main module's go.mod file is
1.14 or higher. Build commands like 'go build' and 'go test' will load packages
from the vendor directory instead of accessing the network or the local module
cache. To explicitly enable vendoring, invoke the go command with the flag
-mod=vendor. To disable vendoring, use the flag -mod=mod.

Unlike vendoring in GOPATH, the go command ignores vendor directories in
locations other than the main module's root directory.
	`,
}

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 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 sets a default for cfg.BuildMod if it does not already have an explicit value.

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 in the build list contains a package, but we don't have a sum for its .zip file.

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

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