func runClean(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if len(args) > 0 {
cacheFlag := ""
switch {
// either the flags and arguments explicitly imply a package,
// or no other target (such as a cache) was requested to be cleaned.
cleanPkg := len(args) > 0 || cleanI || cleanR
- if (!modload.Enabled(moduleLoaderState) || modload.HasModRoot(moduleLoaderState)) &&
+ if (!moduleLoaderState.Enabled() || moduleLoaderState.HasModRoot()) &&
!cleanCache && !cleanModcache && !cleanTestcache && !cleanFuzzcache {
cleanPkg = true
}
func ExtraEnvVars(loaderstate *modload.State) []cfg.EnvVar {
gomod := ""
modload.Init(loaderstate)
- if modload.HasModRoot(loaderstate) {
- gomod = modload.ModFilePath(loaderstate)
- } else if modload.Enabled(loaderstate) {
+ if loaderstate.HasModRoot() {
+ gomod = loaderstate.ModFilePath()
+ } else if loaderstate.Enabled() {
gomod = os.DevNull
}
- modload.InitWorkfile(loaderstate)
+ loaderstate.InitWorkfile()
gowork := modload.WorkFilePath(loaderstate)
// As a special case, if a user set off explicitly, report that in GOWORK.
if cfg.Getenv("GOWORK") == "off" {
baseGofmtArgLen := gofmtArgLen
for _, pkg := range load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{}, args) {
- if modload.Enabled(moduleLoaderState) && pkg.Module != nil && !pkg.Module.Main {
+ if moduleLoaderState.Enabled() && pkg.Module != nil && !pkg.Module.Main {
if !printed {
fmt.Fprintf(os.Stderr, "go: not formatting packages in dependency modules\n")
printed = true
func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if generateRunFlag != "" {
var err error
printed := false
pkgOpts := load.PackageOpts{IgnoreImports: true}
for _, pkg := range load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, args) {
- if modload.Enabled(moduleLoaderState) && pkg.Module != nil && !pkg.Module.Main {
+ if moduleLoaderState.Enabled() && pkg.Module != nil && !pkg.Module.Main {
if !printed {
fmt.Fprintf(os.Stderr, "go: not generating in packages in dependency modules\n")
printed = true
func runList(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if *listFmt != "" && listJson {
base.Fatalf("go list -f cannot be used with -json")
if *listReuse != "" && !*listM {
base.Fatalf("go list -reuse cannot be used without -m")
}
- if *listReuse != "" && modload.HasModRoot(moduleLoaderState) {
+ if *listReuse != "" && moduleLoaderState.HasModRoot() {
base.Fatalf("go list -reuse cannot be used inside a module")
}
if cfg.BuildMod == "vendor" {
base.Fatalf("go list -retracted cannot be used when vendoring is enabled")
}
- if !modload.Enabled(moduleLoaderState) {
+ if !moduleLoaderState.Enabled() {
base.Fatalf("go list -retracted can only be used in module-aware mode")
}
}
base.Fatalf("go list -test cannot be used with -m")
}
- if modload.Init(moduleLoaderState); !modload.Enabled(moduleLoaderState) {
+ if modload.Init(moduleLoaderState); !moduleLoaderState.Enabled() {
base.Fatalf("go: list -m cannot be used with GO111MODULE=off")
}
default:
return func(s *modload.State, p *Package) bool {
switch {
- case pattern == "tool" && modload.Enabled(s):
+ case pattern == "tool" && s.Enabled():
return s.MainModules.Tools()[p.ImportPath]
- case pattern == "work" && modload.Enabled(s):
+ case pattern == "work" && s.Enabled():
return p.Module != nil && s.MainModules.Contains(p.Module.Path)
default:
matchPath := pkgpattern.MatchPattern(pattern)
func runDownload(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
// Check whether modules are enabled and whether we're in a module.
moduleLoaderState.ForceUseModules = true
modload.ExplicitWriteGoMod = true
haveExplicitArgs := len(args) > 0
- if modload.HasModRoot(moduleLoaderState) || modload.WorkFilePath(moduleLoaderState) != "" {
+ if moduleLoaderState.HasModRoot() || modload.WorkFilePath(moduleLoaderState) != "" {
modload.LoadModFile(moduleLoaderState, ctx) // to fill MainModules
if haveExplicitArgs {
}
if len(args) == 0 {
- if modload.HasModRoot(moduleLoaderState) {
+ if moduleLoaderState.HasModRoot() {
os.Stderr.WriteString("go: no module dependencies to download\n")
} else {
base.Errorf("go: no modules specified (see 'go help mod download')")
base.Exit()
}
- if *downloadReuse != "" && modload.HasModRoot(moduleLoaderState) {
+ if *downloadReuse != "" && moduleLoaderState.HasModRoot() {
base.Fatalf("go mod download -reuse cannot be used inside a module")
}
if len(args) == 1 {
gomod = args[0]
} else {
- gomod = modload.ModFilePath(moduleLoaderState)
+ gomod = moduleLoaderState.ModFilePath()
}
if *editModule != "" {
func runGraph(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if len(args) > 0 {
base.Fatalf("go: 'go mod graph' accepts no arguments")
func runVendor(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if modload.WorkFilePath(moduleLoaderState) != "" {
base.Fatalf("go: 'go mod vendor' cannot be run in workspace mode. Run 'go work vendor' to vendor the workspace or set 'GOWORK=off' to exit workspace mode.")
}
includeGoVersions := false
isExplicit := map[module.Version]bool{}
gv := loaderstate.MainModules.GoVersion(loaderstate)
- if gover.Compare(gv, "1.14") >= 0 && (modload.FindGoWork(loaderstate, base.Cwd()) != "" || modload.ModFile(loaderstate).Go != nil) {
+ if gover.Compare(gv, "1.14") >= 0 && (loaderstate.FindGoWork(base.Cwd()) != "" || modload.ModFile(loaderstate).Go != nil) {
// If the Go version is at least 1.14, annotate all explicit 'require' and
// 'replace' targets found in the go.mod file so that we can perform a
// stronger consistency check when -mod=vendor is set.
func runVerify(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if len(args) != 0 {
// NOTE(rsc): Could take a module pattern.
func runWhy(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
moduleLoaderState.ForceUseModules = true
moduleLoaderState.RootMode = modload.NeedRoot
modload.ExplicitWriteGoMod = true // don't write go.mod in ListModules
// TODO(#40775): make modload.Init return ErrNoModRoot instead of exiting.
// We could handle that here by printing a different message.
modload.Init(moduleLoaderState)
- if !modload.HasModRoot(moduleLoaderState) {
+ if !moduleLoaderState.HasModRoot() {
base.Fatalf("go: go.mod file not found in current directory or any parent directory.\n" +
"\t'go get' is no longer supported outside a module.\n" +
"\tTo build and install a command, use 'go install' with a version,\n" +
newReqs := reqsFromGoMod(modload.ModFile(moduleLoaderState))
r.reportChanges(oldReqs, newReqs)
- if gowork := modload.FindGoWork(moduleLoaderState, base.Cwd()); gowork != "" {
+ if gowork := moduleLoaderState.FindGoWork(base.Cwd()); gowork != "" {
wf, err := modload.ReadWorkFile(gowork)
if err == nil && modload.UpdateWorkGoVersion(wf, moduleLoaderState.MainModules.GoVersion(moduleLoaderState)) {
modload.WriteWorkFile(gowork, wf)
buildListVersion: initialVersion,
initialVersion: initialVersion,
nonesByPath: map[string]*query{},
- workspace: loadWorkspace(modload.FindGoWork(loaderstate, base.Cwd())),
+ workspace: loadWorkspace(loaderstate.FindGoWork(base.Cwd())),
}
for _, q := range queries {
if !q.isWildcard() {
q.pathOnce(q.pattern, func() pathSet {
- hasModRoot := modload.HasModRoot(loaderstate)
+ hasModRoot := loaderstate.HasModRoot()
if hasModRoot && loaderstate.MainModules.Contains(q.pattern) {
v := module.Version{Path: q.pattern}
// The user has explicitly requested to downgrade their own module to
continue
}
q.pathOnce(curM.Path, func() pathSet {
- if modload.HasModRoot(loaderstate) && curM.Version == "" && loaderstate.MainModules.Contains(curM.Path) {
+ if loaderstate.HasModRoot() && curM.Version == "" && loaderstate.MainModules.Contains(curM.Path) {
return errSet(&modload.QueryMatchesMainModulesError{
MainModules: []module.Version{curM},
Pattern: q.pattern,
// restricted to matching packages in the main module.
pkgPattern, mainModule := loaderstate.MainModules.DirImportPath(loaderstate, ctx, q.pattern)
if pkgPattern == "." {
- modload.MustHaveModRoot(loaderstate)
+ loaderstate.MustHaveModRoot()
versions := loaderstate.MainModules.Versions()
modRoots := make([]string, 0, len(versions))
for _, m := range versions {
return errSet(fmt.Errorf("no package to get in current directory"))
}
if !q.isWildcard() {
- modload.MustHaveModRoot(loaderstate)
+ loaderstate.MustHaveModRoot()
return errSet(fmt.Errorf("%s%s is not a package in module rooted at %s", q.pattern, absDetail, loaderstate.MainModules.ModRoot(mainModule)))
}
search.WarnUnmatched([]*search.Match{match})
if q.pattern == "all" {
// If there is no main module, "all" is not meaningful.
- if !modload.HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
return fmt.Errorf(`cannot match "all": %v`, modload.NewNoMainModulesError(loaderstate))
}
if !versionOkForMainModule(q.version) {
// standard library or if the package was not successfully loaded with
// LoadPackages or ImportFromFiles, nil is returned.
func PackageModuleInfo(loaderstate *State, ctx context.Context, pkgpath string) *modinfo.ModulePublic {
- if isStandardImportPath(pkgpath) || !Enabled(loaderstate) {
+ if isStandardImportPath(pkgpath) || !loaderstate.Enabled() {
return nil
}
m, ok := findModule(loaded, pkgpath)
// standard library or if the package was not successfully loaded with
// LoadPackages or ImportFromFiles, the empty string is returned.
func PackageModRoot(loaderstate *State, ctx context.Context, pkgpath string) string {
- if isStandardImportPath(pkgpath) || !Enabled(loaderstate) || cfg.BuildMod == "vendor" {
+ if isStandardImportPath(pkgpath) || !loaderstate.Enabled() || cfg.BuildMod == "vendor" {
return ""
}
m, ok := findModule(loaded, pkgpath)
}
func ModuleInfo(loaderstate *State, ctx context.Context, path string) *modinfo.ModulePublic {
- if !Enabled(loaderstate) {
+ if !loaderstate.Enabled() {
return nil
}
func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Version) {
rs.graphOnce.Do(func() {
roots := loaderstate.MainModules.Versions()
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
// Use rs.rootModules to pull in the go and toolchain roots
// from the go.work file and preserve the invariant that all
// of rs.rootModules are in mg.g.
// graph, but still distinguishes between direct and indirect
// dependencies.
vendorMod := module.Version{Path: "vendor/modules.txt", Version: ""}
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
for _, m := range loaderstate.MainModules.Versions() {
reqs, _ := rootsFromModFile(loaderstate, m, loaderstate.MainModules.ModFile(m), omitToolchainRoot)
mg.g.Require(m, append(reqs, vendorMod))
}
var graphRoots []module.Version
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
graphRoots = roots
} else {
graphRoots = loaderstate.MainModules.Versions()
)
if pruning != workspace {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
panic("pruning is not workspace in workspace mode")
}
mg.g.Require(loaderstate.MainModules.mustGetSingleMainModule(loaderstate), roots)
func (mg *ModuleGraph) allRootsSelected(loaderstate *State) bool {
var roots []module.Version
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
roots = loaderstate.MainModules.Versions()
} else {
roots, _ = mg.g.RequiredBy(loaderstate.MainModules.mustGetSingleMainModule(loaderstate))
}
}
- if HasModRoot(loaderstate) {
+ if loaderstate.HasModRoot() {
vendorDir := VendorDir(loaderstate)
dir, inVendorDir, _ := dirInModule(path, "", vendorDir, false)
if inVendorDir {
roots = append(roots, vendorDir)
} else {
subCommand := "mod"
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
subCommand = "work"
}
fmt.Fprintf(os.Stderr, "go: ignoring package %s which exists in the vendor directory but is missing from vendor/modules.txt. To sync the vendor directory run go %s vendor.\n", path, subCommand)
// We checked the full module graph and still didn't find the
// requested package.
var queryErr error
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
queryErr = NewNoMainModulesError(loaderstate)
}
return module.Version{}, "", "", nil, &ImportMissingError{
// mustHaveSums reports whether we require that all checksums
// needed to load or build packages are already present in the go.sum file.
func mustHaveSums(loaderstate *State) bool {
- return HasModRoot(loaderstate) && cfg.BuildMod == "readonly" && !inWorkspaceMode(loaderstate)
+ return loaderstate.HasModRoot() && cfg.BuildMod == "readonly" && !loaderstate.inWorkspaceMode()
}
type sumMissingError struct {
loaderstate.ForceUseModules = true
// Load in workspace mode.
- InitWorkfile(loaderstate)
+ loaderstate.InitWorkfile()
LoadModFile(loaderstate, ctx)
// Update the content of the previous main module, and recompute the requirements.
return module.Version{}, errors.New("internal error: mustGetSingleMainModule called in context with no main modules")
}
if len(mms.versions) != 1 {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
return module.Version{}, errors.New("internal error: mustGetSingleMainModule called in workspace mode")
} else {
return module.Version{}, errors.New("internal error: multiple main modules present outside of workspace mode")
// GoVersion returns the go version set on the single module, in module mode,
// or the go.work file in workspace mode.
func (mms *MainModuleSet) GoVersion(loaderstate *State) string {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
return gover.FromGoWork(mms.workFile)
}
if mms != nil && len(mms.versions) == 1 {
// or on the go.work file in workspace mode.
// The caller must not modify the result.
func (mms *MainModuleSet) Godebugs(loaderstate *State) []*modfile.Godebug {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
if mms.workFile != nil {
return mms.workFile.Godebug
}
// 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 InitWorkfile(loaderstate *State) {
+func (loaderstate *State) InitWorkfile() {
// Initialize fsys early because we need overlay to read go.work file.
fips140.Init()
if err := fsys.Init(); err != nil {
base.Fatal(err)
}
- loaderstate.workFilePath = FindGoWork(loaderstate, base.Cwd())
+ loaderstate.workFilePath = loaderstate.FindGoWork(base.Cwd())
}
// FindGoWork returns the name of the go.work file for this command,
// Most code should use Init and Enabled rather than use this directly.
// It is exported mainly for Go toolchain switching, which must process
// the go.work very early at startup.
-func FindGoWork(loaderstate *State, wd string) string {
+func (loaderstate *State) FindGoWork(wd string) string {
if loaderstate.RootMode == NoRoot {
return ""
}
// 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 WillBeEnabled(loaderstate *State) bool {
+func (loaderstate *State) WillBeEnabled() bool {
if loaderstate.modRoots != nil || cfg.ModulesEnabled {
// Already enabled.
return true
// 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 Enabled(loaderstate *State) bool {
+func (loaderstate *State) Enabled() bool {
Init(loaderstate)
return loaderstate.modRoots != nil || cfg.ModulesEnabled
}
func (s *State) vendorDir() (string, error) {
- if inWorkspaceMode(s) {
+ if s.inWorkspaceMode() {
return filepath.Join(filepath.Dir(WorkFilePath(s)), "vendor"), nil
}
mainModule, err := s.MainModules.getSingleMainModule(s)
return dir
}
-func inWorkspaceMode(loaderstate *State) bool {
+func (loaderstate *State) inWorkspaceMode() bool {
if !loaderstate.initialized {
panic("inWorkspaceMode called before modload.Init called")
}
- if !Enabled(loaderstate) {
+ if !loaderstate.Enabled() {
return false
}
return loaderstate.workFilePath != ""
// HasModRoot reports whether a main module or main modules are present.
// HasModRoot may return false even if Enabled returns true: for example, 'get'
// does not require a main module.
-func HasModRoot(loaderstate *State) bool {
+func (loaderstate *State) HasModRoot() bool {
Init(loaderstate)
return loaderstate.modRoots != nil
}
// MustHaveModRoot checks that a main module or main modules are present,
// and calls base.Fatalf if there are no main modules.
-func MustHaveModRoot(loaderstate *State) {
+func (loaderstate *State) MustHaveModRoot() {
Init(loaderstate)
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
die(loaderstate)
}
}
// 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 ModFilePath(loaderstate *State) string {
- MustHaveModRoot(loaderstate)
+func (loaderstate *State) ModFilePath() string {
+ loaderstate.MustHaveModRoot()
return modFilePath(findModuleRoot(base.Cwd()))
}
if cfg.Getenv("GO111MODULE") == "off" {
base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
}
- if !inWorkspaceMode(loaderstate) {
+ if !loaderstate.inWorkspaceMode() {
if dir, name := findAltConfig(base.Cwd()); dir != "" {
rel, err := filepath.Rel(base.Cwd(), dir)
if err != nil {
func NewNoMainModulesError(s *State) noMainModulesError {
return noMainModulesError{
- inWorkspaceMode: inWorkspaceMode(s),
+ inWorkspaceMode: s.inWorkspaceMode(),
}
}
Init(loaderstate)
var workFile *modfile.WorkFile
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
var err error
workFile, loaderstate.modRoots, err = LoadWorkFile(loaderstate.workFilePath)
if err != nil {
roots []module.Version
direct = map[string]bool{"go": true}
)
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
// Since we are in a workspace, the Go version for the synthetic
// "command-line-arguments" module must not exceed the Go version
// for the workspace.
var fixed bool
data, f, err := ReadModFile(gomod, fixVersion(loaderstate, ctx, &fixed))
if err != nil {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
if tooNew, ok := err.(*gover.TooNewError); ok && !strings.HasPrefix(cfg.CmdName, "work ") {
// Switching to a newer toolchain won't help - the go.work has the wrong version.
// Report this more specific error, unless we are a command like 'go work use'
errs = append(errs, err)
continue
}
- if inWorkspaceMode(loaderstate) && !strings.HasPrefix(cfg.CmdName, "work ") {
+ if loaderstate.inWorkspaceMode() && !strings.HasPrefix(cfg.CmdName, "work ") {
// Refuse to use workspace if its go version is too old.
// Disable this check if we are a workspace command like work use or work sync,
// which will fix the problem.
}
}
- if !inWorkspaceMode(loaderstate) {
+ if !loaderstate.inWorkspaceMode() {
ok := true
for _, g := range f.Godebug {
if err := CheckGodebug("godebug", g.Key, g.Value); err != nil {
rs.initVendor(loaderstate, vendorList)
}
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
// We don't need to update the mod file so return early.
loaderstate.requirements = rs
return rs, nil
var roots []module.Version
direct := map[string]bool{}
var pruning modPruning
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
pruning = workspace
roots = make([]module.Version, len(loaderstate.MainModules.Versions()), 2+len(loaderstate.MainModules.Versions()))
copy(roots, loaderstate.MainModules.Versions())
// wasn't provided. setDefaultBuildMod may be called multiple times.
func setDefaultBuildMod(loaderstate *State) {
if cfg.BuildModExplicit {
- if inWorkspaceMode(loaderstate) && cfg.BuildMod != "readonly" && cfg.BuildMod != "vendor" {
+ if loaderstate.inWorkspaceMode() && cfg.BuildMod != "readonly" && cfg.BuildMod != "vendor" {
switch cfg.CmdName {
case "work sync", "mod graph", "mod verify", "mod why":
// These commands run with BuildMod set to mod, but they don't take the
if len(loaderstate.modRoots) >= 1 {
var goVersion string
var versionSource string
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
versionSource = "go.work"
if wfg := loaderstate.MainModules.WorkFile().Go; wfg != nil {
goVersion = wfg.Version
}
func mustHaveCompleteRequirements(loaderstate *State) bool {
- return cfg.BuildMod != "mod" && !inWorkspaceMode(loaderstate)
+ return cfg.BuildMod != "mod" && !loaderstate.inWorkspaceMode()
}
// addGoStmt adds a go directive to the go.mod file if it does not already
//
// In workspace mode, commitRequirements only writes changes to go.work.sum.
func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts) (err error) {
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
// go.mod files aren't updated in workspace mode, but we still want to
// update the go.work.sum file.
return modfetch.WriteGoSum(ctx, keepSums(loaderstate, ctx, loaded, loaderstate.requirements, addBuildListZipSums), mustHaveCompleteRequirements(loaderstate))
}
if arg == "all" || strings.Contains(arg, "...") {
needFullGraph = true
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(loaderstate))
}
continue
if vers == "upgrade" || vers == "patch" {
if _, ok := rs.rootSelected(loaderstate, path); !ok || rs.pruning == unpruned {
needFullGraph = true
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(loaderstate))
}
}
}
if _, ok := rs.rootSelected(loaderstate, arg); !ok || rs.pruning == unpruned {
needFullGraph = true
- if mode&ListVersions == 0 && !HasModRoot(loaderstate) {
+ if mode&ListVersions == 0 && !loaderstate.HasModRoot() {
base.Fatalf("go: cannot match %q without -versions or an explicit version: %v", arg, NewNoMainModulesError(loaderstate))
}
}
// If we're outside of a module, ensure that the failure mode
// indicates that.
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
die(loaderstate)
}
if !slices.Contains(modRoots, modRoot) && search.InDir(absDir, cfg.GOROOTsrc) == "" && pathInModuleCache(loaderstate, ctx, absDir, rs) == "" {
m.Dirs = []string{}
scope := "main module or its selected dependencies"
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
scope = "modules listed in go.work or their selected dependencies"
}
m.AddError(fmt.Errorf("directory prefix %s does not contain %s", base.ShortPath(absDir), scope))
if dirstr == "directory ." {
dirstr = "current directory"
}
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
if mr := findModuleRoot(absDir); mr != "" {
return "", fmt.Errorf("%s is contained in a module that is not one of the workspace modules listed in go.work. You can add the module to the workspace using:\n\tgo work use %s", dirstr, base.ShortPath(mr))
}
// DirImportPath returns the effective import path for dir,
// provided it is within a main module, or else returns ".".
func (mms *MainModuleSet) DirImportPath(loaderstate *State, ctx context.Context, dir string) (path string, m module.Version) {
- if !HasModRoot(loaderstate) {
+ if !loaderstate.HasModRoot() {
return ".", module.Version{}
}
LoadModFile(loaderstate, ctx) // Sets targetPrefix.
continue
}
- if !ld.ResolveMissingImports || (!HasModRoot(loaderstate) && !loaderstate.allowMissingModuleImports) {
+ if !ld.ResolveMissingImports || (!loaderstate.HasModRoot() && !loaderstate.allowMissingModuleImports) {
// We've loaded as much as we can without resolving missing imports.
break
}
continue
}
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
// In workspace mode / workspace pruning mode, the roots are the main modules
// rather than the main module's direct dependencies. The check below on the selected
// roots does not apply.
//
// The caller must not modify the returned summary.
func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error) {
- if m.Version == "" && !inWorkspaceMode(loaderstate) && loaderstate.MainModules.Contains(m.Path) {
+ if m.Version == "" && !loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
panic("internal error: goModSummary called on a main module")
}
if gover.IsToolchain(m.Path) {
}
return &modFileSummary{module: m}, nil
}
- if m.Version == "" && !inWorkspaceMode(loaderstate) && loaderstate.MainModules.Contains(m.Path) {
+ if m.Version == "" && !loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
// Calling rawGoModSummary implies that we are treating m as a module whose
// requirements aren't the roots of the module graph and can't be modified.
//
// are the roots of the module graph and we expect them to be kept consistent.
panic("internal error: rawGoModSummary called on a main module")
}
- if m.Version == "" && inWorkspaceMode(loaderstate) && m.Path == "command-line-arguments" {
+ if m.Version == "" && loaderstate.inWorkspaceMode() && m.Path == "command-line-arguments" {
// "go work sync" calls LoadModGraph to make sure the module graph is valid.
// If there are no modules in the workspace, we synthesize an empty
// command-line-arguments module, which rawGoModData cannot read a go.mod for.
return &modFileSummary{module: m}, nil
- } else if m.Version == "" && inWorkspaceMode(loaderstate) && loaderstate.MainModules.Contains(m.Path) {
+ } else if m.Version == "" && loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
// When go get uses EnterWorkspace to check that the workspace loads properly,
// it will update the contents of the workspace module's modfile in memory. To use the updated
// contents of the modfile when doing the load, don't read from disk and instead
if m.Version == "" {
dir := m.Path
if !filepath.IsAbs(dir) {
- if inWorkspaceMode(loaderstate) && loaderstate.MainModules.Contains(m.Path) {
+ if loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
dir = loaderstate.MainModules.ModRoot(m)
} else {
// m is a replacement module with only a file path.
walkPkgs(modRoot, loaderstate.MainModules.PathPrefix(mod), pruneGoMod|pruneVendor)
}
}
- if HasModRoot(loaderstate) {
+ if loaderstate.HasModRoot() {
walkPkgs(VendorDir(loaderstate), "", pruneVendor)
}
return
}
pre114 := false
- if !inWorkspaceMode(loaderstate) { // workspace mode was added after Go 1.14
+ if !loaderstate.inWorkspaceMode() { // workspace mode was added after Go 1.14
if len(indexes) != 1 {
panic(fmt.Errorf("not in workspace mode but number of indexes is %v, not 1", len(indexes)))
}
}
if !foundRequire {
article := ""
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
article = "a "
}
vendErrorf(mod, "is marked as explicit in vendor/modules.txt, but not explicitly required in %vgo.mod", article)
for _, mod := range vendorReplaced {
r := Replacement(loaderstate, mod)
replacementSource := "go.mod"
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
replacementSource = "the workspace"
}
if r == (module.Version{}) {
if vendErrors.Len() > 0 {
subcmd := "mod"
- if inWorkspaceMode(loaderstate) {
+ if loaderstate.inWorkspaceMode() {
subcmd = "work"
}
base.Fatalf("go: inconsistent vendoring in %s:%s\n\n\tTo ignore the vendor directory, use -mod=readonly or -mod=mod.\n\tTo sync the vendor directory, run:\n\t\tgo %s vendor", filepath.Dir(VendorDir(loaderstate)), vendErrors, subcmd)
moduleLoaderState.AllowMissingModuleImports()
modload.Init(moduleLoaderState)
} else {
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
}
work.BuildInit(moduleLoaderState)
// TODO(jitsu): Telemetry for the go/mode counters should eventually be
// moved to modload.Init()
s := modload.NewState()
- if !modload.WillBeEnabled(s) {
+ if !s.WillBeEnabled() {
counter.Inc("go/mode:gopath")
- } else if workfile := modload.FindGoWork(s, base.Cwd()); workfile != "" {
+ } else if workfile := s.FindGoWork(base.Cwd()); workfile != "" {
counter.Inc("go/mode:workspace")
} else {
counter.Inc("go/mode:module")
func runTest(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
pkgArgs, testArgs = testFlags(args)
- modload.InitWorkfile(moduleLoaderState) // The test command does custom flag processing; initialize workspaces after that.
+ moduleLoaderState.InitWorkfile() // The test command does custom flag processing; initialize workspaces after that.
if cfg.DebugTrace != "" {
var close func() error
if !mainMods.Contains(m.Path) {
base.Fatalf("cannot use -fuzz flag on package outside the main module")
}
- } else if pkgs[0].Standard && modload.Enabled(moduleLoaderState) {
+ } else if pkgs[0].Standard && moduleLoaderState.Enabled() {
// Because packages in 'std' and 'cmd' are part of the standard library,
// they are only treated as part of a module in 'go mod' subcommands and
// 'go get'. However, we still don't want to accidentally corrupt their
fmt.Println(name)
}
- modload.InitWorkfile(loaderstate)
+ loaderstate.InitWorkfile()
modload.LoadModFile(loaderstate, ctx)
modTools := slices.Sorted(maps.Keys(loaderstate.MainModules.Tools()))
for _, tool := range modTools {
}
func loadModTool(loaderstate *modload.State, ctx context.Context, name string) string {
- modload.InitWorkfile(loaderstate)
+ loaderstate.InitWorkfile()
modload.LoadModFile(loaderstate, ctx)
matches := []string{}
log.SetPrefix("go: ")
defer log.SetPrefix("")
- if !modload.WillBeEnabled(moduleLoaderState) {
+ if !moduleLoaderState.WillBeEnabled() {
return
}
// The toolchain line overrides the version line
func modGoToolchain(loaderstate *modload.State) (file, goVers, toolchain string) {
wd := base.UncachedCwd()
- file = modload.FindGoWork(loaderstate, wd)
+ file = loaderstate.FindGoWork(wd)
// $GOWORK can be set to a file that does not yet exist, if we are running 'go work init'.
// Do not try to load the file in that case
if _, err := os.Stat(file); err != nil {
// The vet/fix commands do custom flag processing;
// initialize workspaces after that.
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if cfg.DebugTrace != "" {
var close func() error
func runBuild(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
BuildInit(moduleLoaderState)
b := NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
defer func() {
}
}
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
BuildInit(moduleLoaderState)
pkgs := load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{AutoVCS: true}, args)
- if cfg.ModulesEnabled && !modload.HasModRoot(moduleLoaderState) {
+ if cfg.ModulesEnabled && !moduleLoaderState.HasModRoot() {
haveErrors := false
allMissingErrors := true
for _, pkg := range pkgs {
if len(args) == 1 {
gowork = args[0]
} else {
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
gowork = modload.WorkFilePath(moduleLoaderState)
}
if gowork == "" {
func runInit(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
moduleLoaderState.ForceUseModules = true
func runSync(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
moduleLoaderState.ForceUseModules = true
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if modload.WorkFilePath(moduleLoaderState) == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
}
func runUse(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
moduleLoaderState.ForceUseModules = true
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
gowork := modload.WorkFilePath(moduleLoaderState)
if gowork == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
func runVendor(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
- modload.InitWorkfile(moduleLoaderState)
+ moduleLoaderState.InitWorkfile()
if modload.WorkFilePath(moduleLoaderState) == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
}