modload

package standard library
Version: go1.17.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2021 License: BSD-3-Clause Imports: 40 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
)

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.
	`,
}
View Source
var (
	Target module.Version
)

Variables set in initTarget (during {Load,Create}ModFile).

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

func DirImportPath(ctx context.Context, 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) (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 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 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 LatestGoVersion added in go1.17

func LatestGoVersion() string

LatestGoVersion returns the latest version of the Go language supported by this toolchain, like "1.17".

func ListModules

func ListModules(ctx context.Context, args []string, mode ListMode) ([]*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 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 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 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.

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 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 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 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(ctx context.Context)

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

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

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 is lazily loaded, 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

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

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 not relevant (such as if they are pruned out by lazy loading).

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 {
	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 {
	// GoVersion is the Go version to which the go.mod file should be updated
	// after packages have been loaded.
	//
	// An empty GoVersion 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.
	GoVersion 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 minimial dependencies needed to reproducibly reload the requested
	// packages.
	Tidy bool

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

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

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

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

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

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

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

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

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

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

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

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

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 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, and will write those changes back to disk unless DisallowWriteGoMod is in effect.

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

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL