cmd/go: move functions to methods

[git-generate]
cd src/cmd/go/internal/modload
rf '
  mv InitWorkfile State.InitWorkfile
  mv FindGoWork State.FindGoWork
  mv WillBeEnabled State.WillBeEnabled
  mv Enabled State.Enabled
  mv inWorkspaceMode State.inWorkspaceMode
  mv HasModRoot State.HasModRoot
  mv MustHaveModRoot State.MustHaveModRoot
  mv ModFilePath State.ModFilePath
'

Change-Id: I207113868af037c9c0049f4207c3d3b4c19468bb
Reviewed-on: https://go-review.googlesource.com/c/go/+/716602
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: Michael Matloob <matloob@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Ian Alexander
2025-10-29 13:29:43 -04:00
parent 0a95856b95
commit 5f8fdb720c
35 changed files with 112 additions and 112 deletions

View File

@@ -121,7 +121,7 @@ func init() {
func runClean(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
if len(args) > 0 {
cacheFlag := ""
switch {
@@ -143,7 +143,7 @@ func runClean(ctx context.Context, cmd *base.Command, args []string) {
// 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
}

View File

@@ -192,12 +192,12 @@ func findEnv(env []cfg.EnvVar, name string) string {
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" {

View File

@@ -61,7 +61,7 @@ func runFmt(ctx context.Context, cmd *base.Command, args []string) {
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

View File

@@ -183,7 +183,7 @@ func init() {
func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
if generateRunFlag != "" {
var err error
@@ -206,7 +206,7 @@ func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
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

View File

@@ -420,7 +420,7 @@ var nl = []byte{'\n'}
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")
@@ -428,7 +428,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
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")
}
@@ -502,7 +502,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
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")
}
}
@@ -526,7 +526,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
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")
}

View File

@@ -57,9 +57,9 @@ func MatchPackage(pattern, cwd string) func(*modload.State, *Package) bool {
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)

View File

@@ -110,14 +110,14 @@ type ModuleJSON struct {
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 {
@@ -170,7 +170,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
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')")
@@ -178,7 +178,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
base.Exit()
}
if *downloadReuse != "" && modload.HasModRoot(moduleLoaderState) {
if *downloadReuse != "" && moduleLoaderState.HasModRoot() {
base.Fatalf("go mod download -reuse cannot be used inside a module")
}

View File

@@ -233,7 +233,7 @@ func runEdit(ctx context.Context, cmd *base.Command, args []string) {
if len(args) == 1 {
gomod = args[0]
} else {
gomod = modload.ModFilePath(moduleLoaderState)
gomod = moduleLoaderState.ModFilePath()
}
if *editModule != "" {

View File

@@ -53,7 +53,7 @@ func init() {
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")

View File

@@ -67,7 +67,7 @@ func init() {
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.")
}
@@ -118,7 +118,7 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
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.

View File

@@ -45,7 +45,7 @@ func init() {
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.

View File

@@ -64,7 +64,7 @@ func init() {
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

View File

@@ -315,7 +315,7 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
// 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" +
@@ -425,7 +425,7 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
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)
@@ -575,7 +575,7 @@ func newResolver(loaderstate *modload.State, ctx context.Context, queries []*que
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 {
@@ -722,7 +722,7 @@ func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q
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
@@ -752,7 +752,7 @@ func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q
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,
@@ -779,7 +779,7 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
// 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 {
@@ -802,7 +802,7 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
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})

View File

@@ -184,7 +184,7 @@ func (q *query) validate(loaderstate *modload.State) error {
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) {

View File

@@ -52,7 +52,7 @@ func findStandardImportPath(path string) string {
// 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)
@@ -69,7 +69,7 @@ func PackageModuleInfo(loaderstate *State, ctx context.Context, pkgpath string)
// 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)
@@ -84,7 +84,7 @@ func PackageModRoot(loaderstate *State, ctx context.Context, pkgpath string) str
}
func ModuleInfo(loaderstate *State, ctx context.Context, path string) *modinfo.ModulePublic {
if !Enabled(loaderstate) {
if !loaderstate.Enabled() {
return nil
}

View File

@@ -165,7 +165,7 @@ func (rs *Requirements) String() string {
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.
@@ -208,7 +208,7 @@ func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Versi
// 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))
@@ -333,7 +333,7 @@ func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, r
}
var graphRoots []module.Version
if inWorkspaceMode(loaderstate) {
if loaderstate.inWorkspaceMode() {
graphRoots = roots
} else {
graphRoots = loaderstate.MainModules.Versions()
@@ -347,7 +347,7 @@ func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, r
)
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)
@@ -529,7 +529,7 @@ func (mg *ModuleGraph) findError() error {
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))

View File

@@ -341,7 +341,7 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
}
}
if HasModRoot(loaderstate) {
if loaderstate.HasModRoot() {
vendorDir := VendorDir(loaderstate)
dir, inVendorDir, _ := dirInModule(path, "", vendorDir, false)
if inVendorDir {
@@ -356,7 +356,7 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
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)
@@ -492,7 +492,7 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
// 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{
@@ -828,7 +828,7 @@ func fetch(loaderstate *State, ctx context.Context, mod module.Version) (dir str
// 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 {

View File

@@ -83,7 +83,7 @@ func EnterWorkspace(loaderstate *State, ctx context.Context) (exit func(), err e
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.
@@ -193,7 +193,7 @@ func (mms *MainModuleSet) getSingleMainModule(loaderstate *State) (module.Versio
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")
@@ -253,7 +253,7 @@ func (mms *MainModuleSet) HighestReplaced() map[string]string {
// 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 {
@@ -273,7 +273,7 @@ func (mms *MainModuleSet) GoVersion(loaderstate *State) string {
// 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
}
@@ -343,13 +343,13 @@ func BinDir(loaderstate *State) string {
// 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,
@@ -357,7 +357,7 @@ func InitWorkfile(loaderstate *State) {
// 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 ""
}
@@ -575,7 +575,7 @@ func Init(loaderstate *State) {
// 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
@@ -627,13 +627,13 @@ func FindGoMod(wd string) string {
// 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)
@@ -666,11 +666,11 @@ func VendorDir(loaderstate *State) string {
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 != ""
@@ -679,16 +679,16 @@ func inWorkspaceMode(loaderstate *State) bool {
// 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)
}
}
@@ -696,8 +696,8 @@ func MustHaveModRoot(loaderstate *State) {
// 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()))
}
@@ -715,7 +715,7 @@ func die(loaderstate *State) {
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 {
@@ -752,7 +752,7 @@ func (e noMainModulesError) Unwrap() error {
func NewNoMainModulesError(s *State) noMainModulesError {
return noMainModulesError{
inWorkspaceMode: inWorkspaceMode(s),
inWorkspaceMode: s.inWorkspaceMode(),
}
}
@@ -920,7 +920,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
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 {
@@ -964,7 +964,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
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.
@@ -1003,7 +1003,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
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'
@@ -1018,7 +1018,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
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.
@@ -1030,7 +1030,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
}
}
if !inWorkspaceMode(loaderstate) {
if !loaderstate.inWorkspaceMode() {
ok := true
for _, g := range f.Godebug {
if err := CheckGodebug("godebug", g.Key, g.Value); err != nil {
@@ -1078,7 +1078,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
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
@@ -1421,7 +1421,7 @@ func requirementsFromModFiles(loaderstate *State, ctx context.Context, workFile
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())
@@ -1516,7 +1516,7 @@ func appendGoAndToolchainRoots(roots []module.Version, goVersion, toolchain stri
// 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
@@ -1563,7 +1563,7 @@ func setDefaultBuildMod(loaderstate *State) {
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
@@ -1651,7 +1651,7 @@ func modulesTextIsForWorkspace(vendorDir string) (bool, error) {
}
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
@@ -1955,7 +1955,7 @@ func UpdateGoModFromReqs(loaderstate *State, ctx context.Context, opts WriteOpts
//
// 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))

View File

@@ -145,7 +145,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
}
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
@@ -154,7 +154,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
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))
}
}
@@ -163,7 +163,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
}
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))
}
}

View File

@@ -294,7 +294,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// If we're outside of a module, ensure that the failure mode
// indicates that.
if !HasModRoot(loaderstate) {
if !loaderstate.HasModRoot() {
die(loaderstate)
}
@@ -546,7 +546,7 @@ func matchLocalDirs(loaderstate *State, ctx context.Context, modRoots []string,
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))
@@ -674,7 +674,7 @@ func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs
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))
}
@@ -800,7 +800,7 @@ func ImportFromFiles(loaderstate *State, ctx context.Context, gofiles []string)
// 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.
@@ -1184,7 +1184,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
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
}
@@ -1399,7 +1399,7 @@ func (ld *loader) updateRequirements(loaderstate *State, ctx context.Context) (c
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.

View File

@@ -574,7 +574,7 @@ type retraction struct {
//
// 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) {
@@ -686,7 +686,7 @@ func rawGoModSummary(loaderstate *State, m module.Version) (*modFileSummary, err
}
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.
//
@@ -694,12 +694,12 @@ func rawGoModSummary(loaderstate *State, m module.Version) (*modFileSummary, err
// 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
@@ -785,7 +785,7 @@ func rawGoModData(loaderstate *State, m module.Version) (name string, data []byt
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.

View File

@@ -176,7 +176,7 @@ func matchPackages(loaderstate *State, ctx context.Context, m *search.Match, tag
walkPkgs(modRoot, loaderstate.MainModules.PathPrefix(mod), pruneGoMod|pruneVendor)
}
}
if HasModRoot(loaderstate) {
if loaderstate.HasModRoot() {
walkPkgs(VendorDir(loaderstate), "", pruneVendor)
}
return

View File

@@ -154,7 +154,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
}
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)))
}
@@ -252,7 +252,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
}
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)
@@ -264,7 +264,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
for _, mod := range vendorReplaced {
r := Replacement(loaderstate, mod)
replacementSource := "go.mod"
if inWorkspaceMode(loaderstate) {
if loaderstate.inWorkspaceMode() {
replacementSource = "the workspace"
}
if r == (module.Version{}) {
@@ -276,7 +276,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
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)

View File

@@ -82,7 +82,7 @@ func runRun(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState.AllowMissingModuleImports()
modload.Init(moduleLoaderState)
} else {
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
}
work.BuildInit(moduleLoaderState)

View File

@@ -25,9 +25,9 @@ func incrementConfig() {
// 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")

View File

@@ -684,7 +684,7 @@ var defaultVetFlags = []string{
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
@@ -742,7 +742,7 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
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

View File

@@ -162,7 +162,7 @@ func listTools(loaderstate *modload.State, ctx context.Context) {
fmt.Println(name)
}
modload.InitWorkfile(loaderstate)
loaderstate.InitWorkfile()
modload.LoadModFile(loaderstate, ctx)
modTools := slices.Sorted(maps.Keys(loaderstate.MainModules.Tools()))
for _, tool := range modTools {
@@ -253,7 +253,7 @@ func loadBuiltinTool(toolName string) string {
}
func loadModTool(loaderstate *modload.State, ctx context.Context, name string) string {
modload.InitWorkfile(loaderstate)
loaderstate.InitWorkfile()
modload.LoadModFile(loaderstate, ctx)
matches := []string{}

View File

@@ -99,7 +99,7 @@ func Select() {
log.SetPrefix("go: ")
defer log.SetPrefix("")
if !modload.WillBeEnabled(moduleLoaderState) {
if !moduleLoaderState.WillBeEnabled() {
return
}
@@ -525,7 +525,7 @@ func raceSafeCopy(old, new string) error {
// 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 {

View File

@@ -126,7 +126,7 @@ func run(ctx context.Context, cmd *base.Command, args []string) {
// The vet/fix commands do custom flag processing;
// initialize workspaces after that.
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
if cfg.DebugTrace != "" {
var close func() error

View File

@@ -460,7 +460,7 @@ var pkgsFilter = func(pkgs []*load.Package) []*load.Package { return pkgs }
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() {
@@ -696,10 +696,10 @@ func runInstall(ctx context.Context, cmd *base.Command, args []string) {
}
}
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 {

View File

@@ -144,7 +144,7 @@ func runEditwork(ctx context.Context, cmd *base.Command, args []string) {
if len(args) == 1 {
gowork = args[0]
} else {
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
gowork = modload.WorkFilePath(moduleLoaderState)
}
if gowork == "" {

View File

@@ -45,7 +45,7 @@ func init() {
func runInit(ctx context.Context, cmd *base.Command, args []string) {
moduleLoaderState := modload.NewState()
modload.InitWorkfile(moduleLoaderState)
moduleLoaderState.InitWorkfile()
moduleLoaderState.ForceUseModules = true

View File

@@ -50,7 +50,7 @@ func init() {
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)")
}

View File

@@ -63,7 +63,7 @@ func init() {
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)")

View File

@@ -47,7 +47,7 @@ func init() {
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)")
}