Documentation ¶
Index ¶
- Constants
- Variables
- func AllowMissingModuleImports()
- func BinDir() string
- func CheckAllowed(ctx context.Context, m module.Version) error
- func CheckDeprecation(ctx context.Context, m module.Version) (deprecation string, err error)
- func CheckExclusions(ctx context.Context, m module.Version) error
- func CheckRetractions(ctx context.Context, m module.Version) (err error)
- func CreateModFile(ctx context.Context, modPath string)
- func CreateWorkFile(ctx context.Context, workFile string, modDirs []string)
- func EditBuildList(ctx context.Context, add, mustSelect []module.Version) (changed bool, err error)
- func Enabled() bool
- func EnterModule(ctx context.Context, enterModroot string)
- func HasModRoot() bool
- func ImportFromFiles(ctx context.Context, gofiles []string)
- func ImportMap(path string) string
- func Init()
- func InitWorkfile()
- func IsRevisionQuery(vers string) bool
- func LatestGoVersion() string
- func ListModules(ctx context.Context, args []string, mode ListMode) ([]*modinfo.ModulePublic, error)
- func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string)
- func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error)
- func MatchInModule(ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match
- func ModFile() *modfile.File
- func ModFilePath() string
- func ModInfoData(info string) []byte
- func ModInfoProg(info string, isgccgo bool) []byte
- func ModuleInfo(ctx context.Context, path string) *modinfo.ModulePublic
- func MustHaveModRoot()
- func PackageDir(path string) string
- func PackageModule(path string) module.Version
- func PackageModuleInfo(ctx context.Context, pkgpath string) *modinfo.ModulePublic
- func Query(ctx context.Context, path, query, current string, allowed AllowedFunc) (*modfetch.RevInfo, error)
- func QueryPattern(ctx context.Context, pattern, query string, current func(string) string, ...) (pkgMods []QueryResult, modOnly *QueryResult, err error)
- func ReadModFile(gomod string, fix modfile.VersionFixer) (data []byte, f *modfile.File, err error)
- func ReadWorkFile(path string) (*modfile.WorkFile, error)
- func Replacement(mod module.Version) module.Version
- func ShortMessage(message, emptyDefault string) string
- func ToDirectoryPath(path string) string
- func UpdateWorkFile(wf *modfile.WorkFile)
- func VendorDir() string
- func Why(path string) string
- func WhyDepth(path string) int
- func WillBeEnabled() bool
- func WorkFilePath() string
- func WriteGoMod(ctx context.Context) error
- func WriteWorkFile(path string, wf *modfile.WorkFile) error
- type AllowedFunc
- type AmbiguousImportError
- type Conflict
- type ConstraintError
- type DirectImportFromImplicitDependencyError
- type ImportMissingError
- type ImportMissingSumError
- type ListMode
- type MainModuleSet
- func (mms *MainModuleSet) Contains(path string) bool
- func (mms *MainModuleSet) DirImportPath(ctx context.Context, dir string) (path string, m module.Version)
- func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex
- func (mms *MainModuleSet) GoVersion() string
- func (mms *MainModuleSet) HighestReplaced() map[string]string
- func (mms *MainModuleSet) InGorootSrc(m module.Version) bool
- func (mms *MainModuleSet) Index(m module.Version) *modFileIndex
- func (mms *MainModuleSet) Len() int
- func (mms *MainModuleSet) ModContainingCWD() module.Version
- func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File
- func (mms *MainModuleSet) ModRoot(m module.Version) string
- func (mms *MainModuleSet) PathPrefix(m module.Version) string
- func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex)
- func (mms *MainModuleSet) Versions() []module.Version
- func (mms *MainModuleSet) WorkFileReplaceMap() map[module.Version]module.Version
- type ModuleGraph
- type ModuleRetractedError
- type NoMatchingVersionError
- type NoPatchBaseError
- type PackageNotInModuleError
- type PackageOpts
- type QueryMatchesMainModulesError
- type QueryMatchesPackagesInMainModuleError
- type QueryResult
- type QueryUpgradesAllError
- type Requirements
- type Root
- type WildcardInFirstElementError
Constants ¶
const ( // ExplicitIndirectVersionV is the Go version (plus leading "v") at which a // module's go.mod file is expected to list explicit requirements on every // module that provides any package transitively imported by that module. // // Other indirect dependencies of such a module can be safely pruned out of // the module graph; see https://golang.org/ref/mod#graph-pruning. ExplicitIndirectVersionV = "v1.17" )
Variables ¶
var ( // RootMode determines whether a module root is needed. RootMode Root // ForceUseModules may be set to force modules to be enabled when // GO111MODULE=auto or to report an error when GO111MODULE=off. ForceUseModules bool // ExplicitWriteGoMod prevents LoadPackages, ListModules, and other functions // from updating go.mod and go.sum or reporting errors when updates are // needed. A package should set this if it would cause go.mod to be written // multiple times (for example, 'go get' calls LoadPackages multiple times) or // if it needs some other operation to be successful before go.mod and go.sum // can be written (for example, 'go mod download' must download modules before // adding sums to go.sum). Packages that set this are responsible for calling // WriteGoMod explicitly. ExplicitWriteGoMod bool )
Variables set by other packages.
TODO(#40775): See if these can be plumbed as explicit parameters.
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.
var ErrNoModRoot = errors.New("go.mod file not found in current directory or any parent directory; see 'go help modules'")
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.
`,
}
var HelpModules = &base.Command{
UsageLine: "modules",
Short: "modules, module versions, and more",
Long: `
Modules are how Go manages dependencies.
A module is a collection of packages that are released, versioned, and
distributed together. Modules may be downloaded directly from version control
repositories or from module proxy servers.
For a series of tutorials on modules, see
https://golang.org/doc/tutorial/create-module.
For a detailed reference on modules, see https://golang.org/ref/mod.
By default, the go command may download modules from https://proxy.golang.org.
It may authenticate modules using the checksum database at
https://sum.golang.org. Both services are operated by the Go team at Google.
The privacy policies for these services are available at
https://proxy.golang.org/privacy and https://sum.golang.org/privacy,
respectively.
The go command's download behavior may be configured using GOPROXY, GOSUMDB,
GOPRIVATE, and other environment variables. See 'go help environment'
and https://golang.org/ref/mod#private-module-privacy for more information.
`,
}
Functions ¶
func AllowMissingModuleImports ¶
func AllowMissingModuleImports()
AllowMissingModuleImports allows import paths to be resolved to modules when there is no module root. Normally, this is forbidden because it's slow and there's no way to make the result reproducible, but some commands like 'go get' are expected to do this.
This function affects the default cfg.BuildMod when outside of a module, so it can only be called prior to Init.
func CheckAllowed ¶
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 ¶
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 ¶
CheckExclusions returns an error equivalent to ErrDisallowed if module m is excluded by the main module's go.mod file.
func CheckRetractions ¶
CheckRetractions returns an error if module m has been retracted by its author.
func CreateModFile ¶
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 CreateWorkFile ¶ added in v0.1.0
CreateWorkFile initializes a new workspace by creating a go.work file.
func EditBuildList ¶
EditBuildList edits the global build list by first adding every module in add to the existing build list, then adjusting versions (and adding or removing requirements as needed) until every module in mustSelect is selected at the given version.
(Note that the newly-added modules might not be selected in the resulting build list: they could be lower than existing requirements or conflict with versions in mustSelect.)
If the versions listed in mustSelect are mutually incompatible (due to one of the listed modules requiring a higher version of another), EditBuildList returns a *ConstraintError and leaves the build list in its previous state.
On success, EditBuildList reports whether the selected version of any module in the build list may have been changed (possibly to or from "none") as a result.
func Enabled ¶
func Enabled() bool
Enabled reports whether modules are (or must be) enabled. If modules are enabled but there is no main module, Enabled returns true and then the first use of module information will call die (usually through MustModRoot).
func EnterModule ¶ added in v0.1.0
EnterModule resets MainModules and requirements to refer to just this one module.
func HasModRoot ¶
func HasModRoot() bool
HasModRoot reports whether a main module is present. HasModRoot may return false even if Enabled returns true: for example, 'get' does not require a main module.
func ImportFromFiles ¶
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 ¶
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 InitWorkfile ¶ added in v0.1.0
func InitWorkfile()
InitWorkfile initializes the workFilePath variable for commands that operate in workspace mode. It should not be called by other commands, for example 'go mod tidy', that don't operate in workspace mode.
func IsRevisionQuery ¶
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 ¶
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 ¶
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 ¶
Lookup returns the source directory, import path, and any loading error for the package at path as imported from the package in parentDir. Lookup requires that one of the Load functions in this package has already been called.
func MatchInModule ¶
func MatchInModule(ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match
MatchInModule identifies the packages matching the given pattern within the given module version, which does not need to be in the build list or module requirement graph.
If m is the zero module.Version, MatchInModule matches the pattern against the standard library (std and cmd) in GOROOT/src.
func ModFile ¶
ModFile returns the parsed go.mod file.
Note that after calling LoadPackages or LoadModGraph, the require statements in the modfile.File are no longer the source of truth and will be ignored: edits made directly will be lost at the next call to WriteGoMod. To make permanent changes to the require statements in go.mod, edit it before loading.
func ModFilePath ¶
func ModFilePath() string
ModFilePath returns the path that would be used for the go.mod file, if in module mode. ModFilePath calls base.Fatalf if there is no main module, even if -modfile is set.
func ModInfoData ¶ added in v0.1.0
func ModInfoProg ¶
func ModuleInfo ¶
func ModuleInfo(ctx context.Context, path string) *modinfo.ModulePublic
func MustHaveModRoot ¶ added in v0.1.0
func MustHaveModRoot()
MustHaveModRoot checks that a main module or main modules are present, and calls base.Fatalf if there are no main modules.
func PackageDir ¶
PackageDir returns the directory containing the source code for the package named by the import path.
func PackageModule ¶
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 ¶
func QueryPattern(ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) (pkgMods []QueryResult, modOnly *QueryResult, err error)
QueryPattern looks up the module(s) containing at least one package matching the given pattern at the given version. The results are sorted by module path length in descending order. If any proxy provides a non-empty set of candidate modules, no further proxies are tried.
For wildcard patterns, QueryPattern looks in modules with package paths up to the first "..." in the pattern. For the pattern "example.com/a/b.../c", QueryPattern would consider prefixes of "example.com/a".
If any matching package is in the main module, QueryPattern considers only the main module and only the version "latest", without checking for other possible modules.
QueryPattern always returns at least one QueryResult (which may be only modOnly) or a non-nil error.
func ReadModFile ¶ added in v0.1.0
ReadModFile reads and parses the mod file at gomod. ReadModFile properly applies the overlay, locks the file while reading, and applies fix, if applicable.
func ReadWorkFile ¶ added in v0.1.0
ReadWorkFile reads and parses the go.work file at the given path.
func Replacement ¶
Replacement returns the replacement for mod, if any. If the path in the module.Version is relative it's relative to the single main module outside workspace mode, or the workspace's directory in workspace mode.
func ShortMessage ¶
ShortMessage returns a string from go.mod (for example, a retraction rationale or deprecation message) that is safe to print in a terminal.
If the given string is empty, ShortMessage returns the given default. If the given string is too long or contains non-printable characters, ShortMessage returns a hard-coded string.
func ToDirectoryPath ¶ added in v0.1.0
ToDirectoryPath adds a prefix if necessary so that path in unambiguously an absolute path or a relative path starting with a '.' or '..' path component.
func UpdateWorkFile ¶ added in v0.1.0
UpdateWorkFile updates comments on directory directives in the go.work file to include the associated module path.
func Why ¶
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 ¶
WhyDepth returns the number of steps in the Why listing. If there is no reason for the package to be in the current build, WhyDepth returns 0.
func WillBeEnabled ¶
func WillBeEnabled() bool
WillBeEnabled checks whether modules should be enabled but does not initialize modules by installing hooks. If Init has already been called, WillBeEnabled returns the same result as Enabled.
This function is needed to break a cycle. The main package needs to know whether modules are enabled in order to install the module or GOPATH version of 'go get', but Init reads the -modfile flag in 'go get', so it shouldn't be called until the command is installed and flags are parsed. Instead of calling Init and Enabled, the main package can call this function.
func WorkFilePath ¶ added in v0.1.0
func WorkFilePath() string
WorkFilePath returns the absolute path of the go.work file, or "" if not in workspace mode. WorkFilePath must be called after InitWorkfile.
func WriteGoMod ¶
WriteGoMod writes the current build list back to go.mod.
Types ¶
type AllowedFunc ¶
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 ¶
type AmbiguousImportError struct { Dirs []string Modules []module.Version // Either empty or 1:1 with Dirs. // contains filtered or unexported fields }
An AmbiguousImportError indicates an import of a package found in multiple modules in the build list, or found in both the main module and its vendor directory.
func (*AmbiguousImportError) Error ¶
func (e *AmbiguousImportError) Error() string
func (*AmbiguousImportError) ImportPath ¶
func (e *AmbiguousImportError) ImportPath() string
type Conflict ¶
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 ¶
type ConstraintError struct { // Conflict lists the source of the conflict for each version in mustSelect // that could not be selected due to the requirements of some other version in // mustSelect. Conflicts []Conflict }
A ConstraintError describes inconsistent constraints in EditBuildList
func (*ConstraintError) Error ¶
func (e *ConstraintError) Error() string
type DirectImportFromImplicitDependencyError ¶
type DirectImportFromImplicitDependencyError struct { ImporterPath string ImportedPath string Module module.Version }
A DirectImportFromImplicitDependencyError indicates a package directly imported by a package or test in the main module that is satisfied by a dependency that is not explicit in the main module's go.mod file.
func (*DirectImportFromImplicitDependencyError) Error ¶
func (e *DirectImportFromImplicitDependencyError) Error() string
func (*DirectImportFromImplicitDependencyError) ImportPath ¶
func (e *DirectImportFromImplicitDependencyError) ImportPath() string
type ImportMissingError ¶
type ImportMissingError struct { Path string Module module.Version QueryErr error ImportingMainModule module.Version // contains filtered or unexported fields }
func (*ImportMissingError) Error ¶
func (e *ImportMissingError) Error() string
func (*ImportMissingError) ImportPath ¶
func (e *ImportMissingError) ImportPath() string
func (*ImportMissingError) Unwrap ¶
func (e *ImportMissingError) Unwrap() error
type ImportMissingSumError ¶
type ImportMissingSumError struct {
// contains filtered or unexported fields
}
ImportMissingSumError is reported in readonly mode when we need to check if a module contains a package, but we don't have a sum for its .zip file. We might need sums for multiple modules to verify the package is unique.
TODO(#43653): consolidate multiple errors of this type into a single error that suggests a 'go get' command for root packages that 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 ¶
func (e *ImportMissingSumError) Error() string
func (*ImportMissingSumError) ImportPath ¶
func (e *ImportMissingSumError) ImportPath() string
type MainModuleSet ¶ added in v0.1.0
type MainModuleSet struct {
// contains filtered or unexported fields
}
var MainModules *MainModuleSet
func (*MainModuleSet) Contains ¶ added in v0.1.0
func (mms *MainModuleSet) Contains(path string) bool
func (*MainModuleSet) DirImportPath ¶ added in v0.1.0
func (mms *MainModuleSet) DirImportPath(ctx context.Context, dir string) (path string, m module.Version)
DirImportPath returns the effective import path for dir, provided it is within a main module, or else returns ".".
func (*MainModuleSet) GetSingleIndexOrNil ¶ added in v0.1.0
func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex
func (*MainModuleSet) GoVersion ¶ added in v0.1.0
func (mms *MainModuleSet) GoVersion() string
GoVersion returns the go version set on the single module, in module mode, or the go.work file in workspace mode.
func (*MainModuleSet) HighestReplaced ¶ added in v0.1.0
func (mms *MainModuleSet) HighestReplaced() map[string]string
func (*MainModuleSet) InGorootSrc ¶ added in v0.1.0
func (mms *MainModuleSet) InGorootSrc(m module.Version) bool
func (*MainModuleSet) Index ¶ added in v0.1.0
func (mms *MainModuleSet) Index(m module.Version) *modFileIndex
func (*MainModuleSet) Len ¶ added in v0.1.0
func (mms *MainModuleSet) Len() int
func (*MainModuleSet) ModContainingCWD ¶ added in v0.1.0
func (mms *MainModuleSet) ModContainingCWD() module.Version
ModContainingCWD returns the main module containing the working directory, or module.Version{} if none of the main modules contain the working directory.
func (*MainModuleSet) ModFile ¶ added in v0.1.0
func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File
func (*MainModuleSet) ModRoot ¶ added in v0.1.0
func (mms *MainModuleSet) ModRoot(m module.Version) string
func (*MainModuleSet) PathPrefix ¶ added in v0.1.0
func (mms *MainModuleSet) PathPrefix(m module.Version) string
func (*MainModuleSet) SetIndex ¶ added in v0.1.0
func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex)
func (*MainModuleSet) Versions ¶ added in v0.1.0
func (mms *MainModuleSet) Versions() []module.Version
Versions returns the module.Version values of each of the main modules. For each of them, the Path fields are ordinary module paths and the Version fields are empty strings. Callers should not modify the returned slice.
func (*MainModuleSet) WorkFileReplaceMap ¶ added in v0.1.0
func (mms *MainModuleSet) WorkFileReplaceMap() map[module.Version]module.Version
type ModuleGraph ¶
type ModuleGraph struct {
// contains filtered or unexported fields
}
A ModuleGraph represents the complete graph of module dependencies of a main module.
If the main module supports module graph pruning, the graph does not include transitive dependencies of non-root (implicit) dependencies.
func LoadModGraph ¶
func LoadModGraph(ctx context.Context, goVersion string) *ModuleGraph
LoadModGraph loads and returns the graph of module dependencies of the main module, without loading any packages.
If the goVersion string is non-empty, the returned graph is the graph as interpreted by the given Go version (instead of the version indicated in the go.mod file).
Modules are loaded automatically (and lazily) in LoadPackages: LoadModGraph need only be called if LoadPackages is not, typically in commands that care about modules but no particular package.
func (*ModuleGraph) BuildList ¶
func (mg *ModuleGraph) BuildList() []module.Version
BuildList returns the selected versions of all modules present in the graph, beginning with 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 ¶
RequiredBy returns the dependencies required by module m in the graph, or ok=false if module m's dependencies are pruned out.
The caller must not modify the returned slice, but may safely append to it and may rely on it not to be modified.
func (*ModuleGraph) Selected ¶
func (mg *ModuleGraph) Selected(path string) (version string)
Selected returns the selected version of the module with the given path.
If no version is selected, Selected returns version "none".
func (*ModuleGraph) WalkBreadthFirst ¶
func (mg *ModuleGraph) WalkBreadthFirst(f func(m module.Version))
WalkBreadthFirst invokes f once, in breadth-first order, for each module version other than "none" that appears in the graph, regardless of whether that version is selected.
type ModuleRetractedError ¶
type ModuleRetractedError struct {
Rationale []string
}
func (*ModuleRetractedError) Error ¶
func (e *ModuleRetractedError) Error() string
func (*ModuleRetractedError) Is ¶
func (e *ModuleRetractedError) Is(err error) bool
type NoMatchingVersionError ¶
type NoMatchingVersionError struct {
// contains filtered or unexported fields
}
A NoMatchingVersionError indicates that Query found a module at the requested path, but not at any versions satisfying the query string and allow-function.
NOTE: NoMatchingVersionError MUST NOT implement Is(fs.ErrNotExist).
If the module came from a proxy, that proxy had to return a successful status code for the versions it knows about, and thus did not have the opportunity to return a non-400 status code to suppress fallback.
func (*NoMatchingVersionError) Error ¶
func (e *NoMatchingVersionError) Error() string
type NoPatchBaseError ¶
type NoPatchBaseError struct {
// contains filtered or unexported fields
}
A NoPatchBaseError indicates that Query was called with the query "patch" but with a current version of "" or "none".
func (*NoPatchBaseError) Error ¶
func (e *NoPatchBaseError) Error() string
type PackageNotInModuleError ¶
type PackageNotInModuleError struct { MainModules []module.Version Mod module.Version Replacement module.Version Query string Pattern string }
A PackageNotInModuleError indicates that QueryPattern found a candidate module at the requested version, but that module did not contain any packages matching the requested pattern.
NOTE: PackageNotInModuleError MUST NOT implement Is(fs.ErrNotExist).
If the module came from a proxy, that proxy had to return a successful status code for the versions it knows about, and thus did not have the opportunity to return a non-400 status code to suppress fallback.
func (*PackageNotInModuleError) Error ¶
func (e *PackageNotInModuleError) Error() string
func (*PackageNotInModuleError) ImportPath ¶
func (e *PackageNotInModuleError) ImportPath() string
type PackageOpts ¶
type PackageOpts struct { // 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 // Resolve the query against this module. MainModule module.Version }
PackageOpts control the behavior of the LoadPackages function.
type QueryMatchesMainModulesError ¶ added in v0.1.0
type QueryMatchesMainModulesError struct { MainModules []module.Version Pattern string Query string }
A QueryMatchesMainModulesError indicates that a query requests a version of the main module that cannot be satisfied. (The main module's version cannot be changed.)
func (*QueryMatchesMainModulesError) Error ¶ added in v0.1.0
func (e *QueryMatchesMainModulesError) Error() string
type QueryMatchesPackagesInMainModuleError ¶
A QueryMatchesPackagesInMainModuleError indicates that a query cannot be satisfied because it matches one or more packages found in the main module.
func (*QueryMatchesPackagesInMainModuleError) Error ¶
func (e *QueryMatchesPackagesInMainModuleError) Error() string
type QueryResult ¶
func QueryPackages ¶
func QueryPackages(ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) ([]QueryResult, error)
QueryPackages is like QueryPattern, but requires that the pattern match at least one package and omits the non-package result (if any).
type QueryUpgradesAllError ¶ added in v0.1.0
A QueryUpgradesAllError indicates that a query requests an upgrade on the all pattern. (The main module's version cannot be changed.)
func (*QueryUpgradesAllError) Error ¶ added in v0.1.0
func (e *QueryUpgradesAllError) Error() string
type Requirements ¶
type Requirements struct {
// contains filtered or unexported fields
}
A Requirements represents a logically-immutable set of root module requirements.
func LoadModFile ¶
func LoadModFile(ctx context.Context) *Requirements
LoadModFile sets Target and, if there is a main module, parses the initial build list from its go.mod file.
LoadModFile may make changes in memory, like adding a go directive and ensuring requirements are consistent. The caller is responsible for ensuring those changes are written to disk by calling LoadPackages or ListModules (unless ExplicitWriteGoMod is set) or by calling WriteGoMod directly.
As a side-effect, LoadModFile may change cfg.BuildMod to "vendor" if -mod wasn't set explicitly and automatic vendoring should be enabled.
If LoadModFile or CreateModFile has already been called, LoadModFile returns the existing in-memory requirements (rather than re-reading them from disk).
LoadModFile checks the roots of the module graph for consistency with each other, but unlike LoadModGraph does not load the full module graph or check it for global consistency. Most callers outside of the modload package should use LoadModGraph instead.
func (*Requirements) Graph ¶
func (rs *Requirements) Graph(ctx context.Context) (*ModuleGraph, error)
Graph returns the graph of module requirements loaded from the current root modules (as reported by RootModules).
Graph always makes a best effort to load the requirement graph despite any errors, and always returns a non-nil *ModuleGraph.
If the requirements of any relevant module fail to load, Graph also returns a non-nil error of type *mvs.BuildListError.
func (*Requirements) IsDirect ¶
func (rs *Requirements) IsDirect(path string) bool
IsDirect returns whether the given module provides a package directly imported by a package or test in the main module.
type Root ¶
type Root int
const ( // AutoRoot is the default for most commands. modload.Init will look for // a go.mod file in the current directory or any parent. If none is found, // modules may be disabled (GO111MODULE=auto) or commands may run in a // limited module mode. AutoRoot Root = iota // NoRoot is used for commands that run in module mode and ignore any go.mod // file the current directory or in parent directories. NoRoot // NeedRoot is used for commands that must run in module mode and don't // make sense without a main module. NeedRoot )
type WildcardInFirstElementError ¶
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 ¶
func (e *WildcardInFirstElementError) Error() string