aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIan Alexander <jitsu@google.com>2026-04-07 09:51:06 -0400
committerIan Alexander <jitsu@google.com>2026-04-07 11:22:46 -0700
commit30ed7f97faa41413659a871c6ccc10de51b58c41 (patch)
tree0f1d4381525d829aa2ee85af2b56c1aa68487c26
parentda723e15d7492143459c65e4fecf2c17dc0fa1e4 (diff)
downloadgo-30ed7f97faa41413659a871c6ccc10de51b58c41.tar.xz
cmd/go/internal/modload: rename State to Loader
Rename modload.State to modload.Loader. Rename all references to module loader state. The term "Loader" now refers to the module loader by default. The package loader was explicitly renamed "packageLoader" in an earlier change in order to distinguish it from the module loader. [git-generate] cd src/cmd/go/internal/modload rf ' mv State Loader mv NewState NewLoader mv mvsReqs.loaderstate mvsReqs.ld mv replacementRepo.loaderstate replacementRepo.ld mv TestQueryImport.loaderstate TestQueryImport.ld mv LoadPackages.ld LoadPackages.pld mv Loader.CheckAllowed.s Loader.CheckAllowed.ld mv Loader.CheckExclusions.s Loader.CheckExclusions.ld mv Loader.CheckRetractions.s Loader.CheckRetractions.ld mv Loader.Reset.s Loader.Reset.ld mv Loader.setState.s Loader.setState.ld mv Loader.Fetcher.s Loader.Fetcher.ld mv Loader.vendorDir.s Loader.vendorDir.ld mv Loader.VendorDirOrEmpty.s Loader.VendorDirOrEmpty.ld mv Loader.AllowMissingModuleImports.s Loader.AllowMissingModuleImports.ld mv NewNoMainModulesError.s NewNoMainModulesError.ld mv BinDir.loaderstate BinDir.ld mv CheckDeprecation.loaderstate CheckDeprecation.ld mv CreateModFile.loaderstate CreateModFile.ld mv EditBuildList.loaderstate EditBuildList.ld mv EnterModule.loaderstate EnterModule.ld mv EnterWorkspace.loaderstate EnterWorkspace.ld mv ImportFromFiles.loaderstate ImportFromFiles.ld mv Init.loaderstate Init.ld mv ListModules.loaderstate ListModules.ld mv LoadModFile.loaderstate LoadModFile.ld mv LoadModGraph.loaderstate LoadModGraph.ld mv LoadPackages.loaderstate LoadPackages.ld mv Loader.Enabled.loaderstate Loader.Enabled.ld mv Loader.FindGoWork.loaderstate Loader.FindGoWork.ld mv Loader.HasModRoot.loaderstate Loader.HasModRoot.ld mv Loader.InitWorkfile.loaderstate Loader.InitWorkfile.ld mv Loader.ModFilePath.loaderstate Loader.ModFilePath.ld mv Loader.MustHaveModRoot.loaderstate Loader.MustHaveModRoot.ld mv Loader.PackageModule.loaderstate Loader.PackageModule.ld mv Loader.Why.loaderstate Loader.Why.ld mv Loader.WhyDepth.loaderstate Loader.WhyDepth.ld mv Loader.WillBeEnabled.loaderstate Loader.WillBeEnabled.ld mv Loader.inWorkspaceMode.loaderstate Loader.inWorkspaceMode.ld mv Lookup.loaderstate Lookup.ld mv MainModuleSet.DirImportPath.loaderstate MainModuleSet.DirImportPath.ld mv MainModuleSet.GetSingleIndexOrNil.loaderstate MainModuleSet.GetSingleIndexOrNil.ld mv MainModuleSet.GoVersion.loaderstate MainModuleSet.GoVersion.ld mv MainModuleSet.Godebugs.loaderstate MainModuleSet.Godebugs.ld mv MainModuleSet.getSingleMainModule.loaderstate MainModuleSet.getSingleMainModule.ld mv MainModuleSet.mustGetSingleMainModule.loaderstate MainModuleSet.mustGetSingleMainModule.ld mv MatchInModule.loaderstate MatchInModule.ld mv ModFile.loaderstate ModFile.ld mv ModuleGraph.allRootsSelected.loaderstate ModuleGraph.allRootsSelected.ld mv ModuleInfo.loaderstate ModuleInfo.ld mv PackageModRoot.loaderstate PackageModRoot.ld mv PackageModuleInfo.loaderstate PackageModuleInfo.ld mv Query.loaderstate Query.ld mv QueryPackages.loaderstate QueryPackages.ld mv QueryPattern.loaderstate QueryPattern.ld mv Replacement.loaderstate Replacement.ld mv Requirements.GoVersion.loaderstate Requirements.GoVersion.ld mv Requirements.Graph.loaderstate Requirements.Graph.ld mv Requirements.hasRedundantRoot.loaderstate Requirements.hasRedundantRoot.ld mv Requirements.initVendor.loaderstate Requirements.initVendor.ld mv Requirements.rootSelected.loaderstate Requirements.rootSelected.ld mv UpdateGoModFromReqs.loaderstate UpdateGoModFromReqs.ld mv VendorDir.loaderstate VendorDir.ld mv WorkFilePath.loaderstate WorkFilePath.ld mv WriteGoMod.loaderstate WriteGoMod.ld mv addDeprecation.loaderstate addDeprecation.ld mv addRetraction.loaderstate addRetraction.ld mv addUpdate.loaderstate addUpdate.ld mv addVersions.loaderstate addVersions.ld mv canonicalizeReplacePath.loaderstate canonicalizeReplacePath.ld mv checkReuse.loaderstate checkReuse.ld mv checkVendorConsistency.loaderstate checkVendorConsistency.ld mv commitRequirements.loaderstate commitRequirements.ld mv convertPruning.loaderstate convertPruning.ld mv die.loaderstate die.ld mv editRequirements.loaderstate editRequirements.ld mv expandGraph.loaderstate expandGraph.ld mv extendGraph.loaderstate extendGraph.ld mv fetch.loaderstate fetch.ld mv fixVersion.loaderstate fixVersion.ld mv goModSummary.loaderstate goModSummary.ld mv importFromModules.loaderstate importFromModules.ld mv keepSums.loaderstate keepSums.ld mv listModules.loaderstate listModules.ld mv loadFromRoots.loaderstate loadFromRoots.ld mv loadModFile.loaderstate loadModFile.ld mv loadPkg.fromExternalModule.loaderstate loadPkg.fromExternalModule.ld mv lookupRepo.loaderstate lookupRepo.ld mv makeMainModules.loaderstate makeMainModules.ld mv matchLocalDirs.loaderstate matchLocalDirs.ld mv matchPackages.loaderstate matchPackages.ld mv moduleInfo.loaderstate moduleInfo.ld mv modulePrefixesExcludingTarget.loaderstate modulePrefixesExcludingTarget.ld mv mustHaveCompleteRequirements.loaderstate mustHaveCompleteRequirements.ld mv mustHaveSums.loaderstate mustHaveSums.ld mv newRequirements.loaderstate newRequirements.ld mv overrideRoots.loaderstate overrideRoots.ld mv packageLoader.applyPkgFlags.loaderstate packageLoader.applyPkgFlags.ld mv packageLoader.checkMultiplePaths.loaderstate packageLoader.checkMultiplePaths.ld mv packageLoader.checkTidyCompatibility.loaderstate packageLoader.checkTidyCompatibility.ld mv packageLoader.goVersion.loaderstate packageLoader.goVersion.ld mv packageLoader.load.loaderstate packageLoader.load.ld mv packageLoader.pkg.loaderstate packageLoader.pkg.ld mv packageLoader.pkgTest.loaderstate packageLoader.pkgTest.ld mv packageLoader.preloadRootModules.loaderstate packageLoader.preloadRootModules.ld mv packageLoader.resolveMissingImports.loaderstate packageLoader.resolveMissingImports.ld mv packageLoader.stdVendor.loaderstate packageLoader.stdVendor.ld mv packageLoader.updateRequirements.loaderstate packageLoader.updateRequirements.ld mv parseIgnorePatterns.loaderstate parseIgnorePatterns.ld mv pathInModuleCache.loaderstate pathInModuleCache.ld mv previousVersion.loaderstate previousVersion.ld mv queryImport.loaderstate queryImport.ld mv queryLatestVersionIgnoringRetractions.loaderstate queryLatestVersionIgnoringRetractions.ld mv queryMatcher.filterVersions.loaderstate queryMatcher.filterVersions.ld mv queryPrefixModules.loaderstate queryPrefixModules.ld mv queryProxy.loaderstate queryProxy.ld mv queryReuse.loaderstate queryReuse.ld mv rawGoModData.loaderstate rawGoModData.ld mv rawGoModSummary.loaderstate rawGoModSummary.ld mv readModGraph.loaderstate readModGraph.ld mv replaceRelativeTo.loaderstate replaceRelativeTo.ld mv replacementFrom.loaderstate replacementFrom.ld mv requirementsFromModFiles.loaderstate requirementsFromModFiles.ld mv resolveLocalPackage.loaderstate resolveLocalPackage.ld mv resolveReplacement.loaderstate resolveReplacement.ld mv rootsFromModFile.loaderstate rootsFromModFile.ld mv setDefaultBuildMod.loaderstate setDefaultBuildMod.ld mv spotCheckRoots.loaderstate spotCheckRoots.ld mv tidyPrunedRoots.loaderstate tidyPrunedRoots.ld mv tidyRoots.loaderstate tidyRoots.ld mv tidyUnprunedRoots.loaderstate tidyUnprunedRoots.ld mv updatePrunedRoots.loaderstate updatePrunedRoots.ld mv updateRoots.loaderstate updateRoots.ld mv updateUnprunedRoots.loaderstate updateUnprunedRoots.ld mv updateWorkspaceRoots.loaderstate updateWorkspaceRoots.ld mv versionHasGoMod.loaderstate versionHasGoMod.ld mv versions.loaderstate versions.ld ' sed -i -e 's/loaderstate/ld/g' query_test.go cd ../bug rf ' mv runBug.moduleLoaderState runBug.moduleLoader mv printEnvDetails.loaderstate printEnvDetails.ld mv printGoEnv.loaderstate printGoEnv.ld ' cd ../clean rf ' mv runClean.moduleLoaderState runClean.moduleLoader ' cd ../envcmd rf ' mv runEnv.moduleLoaderState runEnv.moduleLoader mv ExtraEnvVars.loaderstate ExtraEnvVars.ld mv ExtraEnvVarsCostly.loaderstate ExtraEnvVarsCostly.ld ' cd ../fmtcmd rf ' mv runFmt.moduleLoaderState runFmt.moduleLoader ' cd ../generate rf ' mv runGenerate.moduleLoaderState runGenerate.moduleLoader ' cd ../list rf ' mv runList.moduleLoaderState runList.moduleLoader ' cd ../load rf ' mv GoFilesPackage.loaderstate GoFilesPackage.ld mv LoadImportWithFlags.loaderstate LoadImportWithFlags.ld mv LoadPackage.loaderstate LoadPackage.ld mv LoadPackageWithFlags.loaderstate LoadPackageWithFlags.ld mv Package.load.loaderstate Package.load.ld mv PackagesAndErrors.loaderstate PackagesAndErrors.ld mv PackagesAndErrorsOutsideModule.loaderstate PackagesAndErrorsOutsideModule.ld mv TestPackageList.loaderstate TestPackageList.ld mv TestPackagesAndErrors.loaderstate TestPackagesAndErrors.ld mv TestPackagesFor.loaderstate TestPackagesFor.ld mv defaultGODEBUG.loaderstate defaultGODEBUG.ld mv defaultGODEBUGGoVersion.loaderstate defaultGODEBUGGoVersion.ld mv disallowInternal.loaderstate disallowInternal.ld mv loadImport.loaderstate loadImport.ld mv loadPackageData.loaderstate loadPackageData.ld mv preload.preloadImports.loaderstate preload.preloadImports.ld mv preload.preloadMatches.loaderstate preload.preloadMatches.ld mv setToolFlags.loaderstate setToolFlags.ld ' cd ../modcmd rf ' mv runDownload.moduleLoaderState runDownload.moduleLoader mv runEdit.moduleLoaderState runEdit.moduleLoader mv runGraph.moduleLoaderState runGraph.moduleLoader mv runInit.moduleLoaderState runInit.moduleLoader mv runTidy.moduleLoaderState runTidy.moduleLoader mv runVendor.moduleLoaderState runVendor.moduleLoader mv runVerify.moduleLoaderState runVerify.moduleLoader mv runWhy.moduleLoaderState runWhy.moduleLoader mv RunVendor.loaderstate RunVendor.ld mv verifyMod.loaderstate verifyMod.ld ' cd ../modget rf ' mv runGet.moduleLoaderState runGet.moduleLoader mv newQuery.loaderstate newQuery.ld mv newResolver.loaderstate newResolver.ld mv parseArgs.loaderstate parseArgs.ld mv query.validate.loaderstate query.validate.ld mv resolver.applyUpgrades.loaderstate resolver.applyUpgrades.ld mv resolver.checkPackageProblems.loaderstate resolver.checkPackageProblems.ld mv resolver.checkWildcardVersions.loaderstate resolver.checkWildcardVersions.ld mv resolver.findAndUpgradeImports.loaderstate resolver.findAndUpgradeImports.ld mv resolver.findMissingWildcards.loaderstate resolver.findMissingWildcards.ld mv resolver.loadPackages.loaderstate resolver.loadPackages.ld mv resolver.matchInModule.loaderstate resolver.matchInModule.ld mv resolver.performLocalQueries.loaderstate resolver.performLocalQueries.ld mv resolver.performPathQueries.loaderstate resolver.performPathQueries.ld mv resolver.performPatternAllQueries.loaderstate resolver.performPatternAllQueries.ld mv resolver.performToolQueries.loaderstate resolver.performToolQueries.ld mv resolver.performWildcardQueries.loaderstate resolver.performWildcardQueries.ld mv resolver.performWorkQueries.loaderstate resolver.performWorkQueries.ld mv resolver.queryModule.loaderstate resolver.queryModule.ld mv resolver.queryNone.loaderstate resolver.queryNone.ld mv resolver.queryPackages.loaderstate resolver.queryPackages.ld mv resolver.queryPath.loaderstate resolver.queryPath.ld mv resolver.queryPattern.loaderstate resolver.queryPattern.ld mv resolver.queryWildcard.loaderstate resolver.queryWildcard.ld mv resolver.resolveQueries.loaderstate resolver.resolveQueries.ld mv resolver.tryWildcard.loaderstate resolver.tryWildcard.ld mv resolver.updateBuildList.loaderstate resolver.updateBuildList.ld mv updateTools.loaderstate updateTools.ld ' cd ../run rf ' mv runRun.moduleLoaderState runRun.moduleLoader ' cd ../test rf ' mv runTest.moduleLoaderState runTest.moduleLoader mv addTestVet.loaderstate addTestVet.ld mv builderTest.loaderstate builderTest.ld ' cd ../tool rf ' mv runTool.moduleLoaderState runTool.moduleLoader mv buildAndRunBuiltinTool.loaderstate buildAndRunBuiltinTool.ld mv buildAndRunModtool.loaderstate buildAndRunModtool.ld mv buildAndRunTool.loaderstate buildAndRunTool.ld mv listTools.loaderstate listTools.ld mv loadModTool.loaderstate loadModTool.ld ' cd ../toolchain rf ' mv Select.moduleLoaderState Select.moduleLoader mv Switcher.loaderstate Switcher.ld mv SwitchOrFatal.loaderstate SwitchOrFatal.ld mv maybeSwitchForGoInstallVersion.loaderstate maybeSwitchForGoInstallVersion.ld mv modGoToolchain.loaderstate modGoToolchain.ld ' cd ../vet rf ' mv run.moduleLoaderState run.moduleLoader ' cd ../work rf ' mv runBuild.moduleLoaderState runBuild.moduleLoader mv runInstall.moduleLoaderState runInstall.moduleLoader mv BuildInit.loaderstate BuildInit.ld mv InstallPackages.loaderstate InstallPackages.ld mv installOutsideModule.loaderstate installOutsideModule.ld ' cd ../workcmd rf ' mv runEditwork.moduleLoaderState runEditwork.moduleLoader mv runInit.moduleLoaderState runInit.moduleLoader mv runSync.moduleLoaderState runSync.moduleLoader mv runUse.moduleLoaderState runUse.moduleLoader mv runVendor.moduleLoaderState runVendor.moduleLoader ' Change-Id: I903063b9f637a2f19a050b4cd660c870da772e54 Reviewed-on: https://go-review.googlesource.com/c/go/+/763620 Reviewed-by: Michael Matloob <matloob@golang.org> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Michael Matloob <matloob@google.com>
-rw-r--r--src/cmd/go/internal/bug/bug.go16
-rw-r--r--src/cmd/go/internal/clean/clean.go8
-rw-r--r--src/cmd/go/internal/doc/dirs.go2
-rw-r--r--src/cmd/go/internal/doc/doc.go6
-rw-r--r--src/cmd/go/internal/doc/mod.go2
-rw-r--r--src/cmd/go/internal/envcmd/env.go26
-rw-r--r--src/cmd/go/internal/fmtcmd/fmt.go6
-rw-r--r--src/cmd/go/internal/generate/generate.go8
-rw-r--r--src/cmd/go/internal/list/list.go38
-rw-r--r--src/cmd/go/internal/load/flag.go6
-rw-r--r--src/cmd/go/internal/load/flag_test.go2
-rw-r--r--src/cmd/go/internal/load/godebug.go14
-rw-r--r--src/cmd/go/internal/load/pkg.go150
-rw-r--r--src/cmd/go/internal/load/search.go14
-rw-r--r--src/cmd/go/internal/load/test.go22
-rw-r--r--src/cmd/go/internal/modcmd/download.go44
-rw-r--r--src/cmd/go/internal/modcmd/edit.go4
-rw-r--r--src/cmd/go/internal/modcmd/graph.go12
-rw-r--r--src/cmd/go/internal/modcmd/init.go6
-rw-r--r--src/cmd/go/internal/modcmd/tidy.go12
-rw-r--r--src/cmd/go/internal/modcmd/vendor.go48
-rw-r--r--src/cmd/go/internal/modcmd/verify.go16
-rw-r--r--src/cmd/go/internal/modcmd/why.go24
-rw-r--r--src/cmd/go/internal/modget/get.go268
-rw-r--r--src/cmd/go/internal/modget/query.go12
-rw-r--r--src/cmd/go/internal/modload/build.go78
-rw-r--r--src/cmd/go/internal/modload/buildlist.go208
-rw-r--r--src/cmd/go/internal/modload/edit.go30
-rw-r--r--src/cmd/go/internal/modload/import.go102
-rw-r--r--src/cmd/go/internal/modload/import_test.go10
-rw-r--r--src/cmd/go/internal/modload/init.go472
-rw-r--r--src/cmd/go/internal/modload/list.go54
-rw-r--r--src/cmd/go/internal/modload/load.go310
-rw-r--r--src/cmd/go/internal/modload/modfile.go116
-rw-r--r--src/cmd/go/internal/modload/mvs.go20
-rw-r--r--src/cmd/go/internal/modload/query.go94
-rw-r--r--src/cmd/go/internal/modload/query_test.go4
-rw-r--r--src/cmd/go/internal/modload/search.go46
-rw-r--r--src/cmd/go/internal/modload/vendor.go24
-rw-r--r--src/cmd/go/internal/run/run.go26
-rw-r--r--src/cmd/go/internal/telemetrystats/telemetrystats.go2
-rw-r--r--src/cmd/go/internal/test/test.go42
-rw-r--r--src/cmd/go/internal/tool/tool.go46
-rw-r--r--src/cmd/go/internal/toolchain/select.go34
-rw-r--r--src/cmd/go/internal/toolchain/switch.go18
-rw-r--r--src/cmd/go/internal/vet/vet.go14
-rw-r--r--src/cmd/go/internal/work/action.go16
-rw-r--r--src/cmd/go/internal/work/build.go60
-rw-r--r--src/cmd/go/internal/work/exec.go2
-rw-r--r--src/cmd/go/internal/work/init.go4
-rw-r--r--src/cmd/go/internal/workcmd/edit.go6
-rw-r--r--src/cmd/go/internal/workcmd/init.go10
-rw-r--r--src/cmd/go/internal/workcmd/sync.go30
-rw-r--r--src/cmd/go/internal/workcmd/use.go12
-rw-r--r--src/cmd/go/internal/workcmd/vendor.go8
55 files changed, 1332 insertions, 1332 deletions
diff --git a/src/cmd/go/internal/bug/bug.go b/src/cmd/go/internal/bug/bug.go
index c224502ecf..a6b2b1d623 100644
--- a/src/cmd/go/internal/bug/bug.go
+++ b/src/cmd/go/internal/bug/bug.go
@@ -42,17 +42,17 @@ func init() {
}
func runBug(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if len(args) > 0 {
base.Fatalf("go: bug takes no arguments")
}
- work.BuildInit(moduleLoaderState)
+ work.BuildInit(moduleLoader)
var buf strings.Builder
buf.WriteString(bugHeader)
printGoVersion(&buf)
buf.WriteString("### Does this issue reproduce with the latest release?\n\n\n")
- printEnvDetails(moduleLoaderState, &buf)
+ printEnvDetails(moduleLoader, &buf)
buf.WriteString(bugFooter)
body := buf.String()
@@ -93,21 +93,21 @@ func printGoVersion(w io.Writer) {
fmt.Fprintf(w, "\n")
}
-func printEnvDetails(loaderstate *modload.State, w io.Writer) {
+func printEnvDetails(ld *modload.Loader, w io.Writer) {
fmt.Fprintf(w, "### What operating system and processor architecture are you using (`go env`)?\n\n")
fmt.Fprintf(w, "<details><summary><code>go env</code> Output</summary><br><pre>\n")
fmt.Fprintf(w, "$ go env\n")
- printGoEnv(loaderstate, w)
+ printGoEnv(ld, w)
printGoDetails(w)
printOSDetails(w)
printCDetails(w)
fmt.Fprintf(w, "</pre></details>\n\n")
}
-func printGoEnv(loaderstate *modload.State, w io.Writer) {
+func printGoEnv(ld *modload.Loader, w io.Writer) {
env := envcmd.MkEnv()
- env = append(env, envcmd.ExtraEnvVars(loaderstate)...)
- env = append(env, envcmd.ExtraEnvVarsCostly(loaderstate)...)
+ env = append(env, envcmd.ExtraEnvVars(ld)...)
+ env = append(env, envcmd.ExtraEnvVarsCostly(ld)...)
envcmd.PrintEnv(w, env, false)
}
diff --git a/src/cmd/go/internal/clean/clean.go b/src/cmd/go/internal/clean/clean.go
index 51581c27e1..8adc8b48c6 100644
--- a/src/cmd/go/internal/clean/clean.go
+++ b/src/cmd/go/internal/clean/clean.go
@@ -120,8 +120,8 @@ func init() {
}
func runClean(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
if len(args) > 0 {
cacheFlag := ""
switch {
@@ -143,13 +143,13 @@ 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 (!moduleLoaderState.Enabled() || moduleLoaderState.HasModRoot()) &&
+ if (!moduleLoader.Enabled() || moduleLoader.HasModRoot()) &&
!cleanCache && !cleanModcache && !cleanTestcache && !cleanFuzzcache {
cleanPkg = true
}
if cleanPkg {
- for _, pkg := range load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{}, args) {
+ for _, pkg := range load.PackagesAndErrors(moduleLoader, ctx, load.PackageOpts{}, args) {
clean(pkg)
}
}
diff --git a/src/cmd/go/internal/doc/dirs.go b/src/cmd/go/internal/doc/dirs.go
index 86b4b526a3..b2e49aaf78 100644
--- a/src/cmd/go/internal/doc/dirs.go
+++ b/src/cmd/go/internal/doc/dirs.go
@@ -183,7 +183,7 @@ func findCodeRoots() []Dir {
// For now it's okay to use a new state because we're just
// using it to determine whether we're in module mode. But
// it would be good to avoid an extra run of modload.Init.
- if state := modload.NewState(); state.WillBeEnabled() {
+ if state := modload.NewLoader(); state.WillBeEnabled() {
usingModules = state.HasModRoot()
if usingModules && cfg.GOROOT != "" {
list = append(list,
diff --git a/src/cmd/go/internal/doc/doc.go b/src/cmd/go/internal/doc/doc.go
index 5a7c1a458c..4376e3344e 100644
--- a/src/cmd/go/internal/doc/doc.go
+++ b/src/cmd/go/internal/doc/doc.go
@@ -371,7 +371,7 @@ func parseArgs(ctx context.Context, flagSet *flag.FlagSet, args []string) (pkg *
if err != nil {
log.Fatal(err)
}
- loader := modload.NewState()
+ loader := modload.NewLoader()
if testGOPATH {
loader = modload.NewDisabledState()
}
@@ -556,7 +556,7 @@ func parseArgs(ctx context.Context, flagSet *flag.FlagSet, args []string) (pkg *
return mustLoadPackage(ctx, loader, wd), "", arg, false
}
-func loadPackage(ctx context.Context, loader *modload.State, pattern string) (*load.Package, error) {
+func loadPackage(ctx context.Context, loader *modload.Loader, pattern string) (*load.Package, error) {
if !search.NewMatch(pattern).IsLiteral() {
return nil, fmt.Errorf("pattern %q does not specify a single package", pattern)
}
@@ -579,7 +579,7 @@ func loadPackage(ctx context.Context, loader *modload.State, pattern string) (*l
return p, nil
}
-func mustLoadPackage(ctx context.Context, loader *modload.State, dir string) *load.Package {
+func mustLoadPackage(ctx context.Context, loader *modload.Loader, dir string) *load.Package {
pkg, err := loadPackage(ctx, loader, dir)
if err != nil {
log.Fatal(err)
diff --git a/src/cmd/go/internal/doc/mod.go b/src/cmd/go/internal/doc/mod.go
index e139cc1208..adf6e60485 100644
--- a/src/cmd/go/internal/doc/mod.go
+++ b/src/cmd/go/internal/doc/mod.go
@@ -15,7 +15,7 @@ import (
)
// loadVersioned loads a package at a specific version.
-func loadVersioned(ctx context.Context, loader *modload.State, pkgPath, version string) (*load.Package, error) {
+func loadVersioned(ctx context.Context, loader *modload.Loader, pkgPath, version string) (*load.Package, error) {
var opts load.PackageOpts
args := []string{
fmt.Sprintf("%s@%s", pkgPath, version),
diff --git a/src/cmd/go/internal/envcmd/env.go b/src/cmd/go/internal/envcmd/env.go
index 7289f58632..e950c65169 100644
--- a/src/cmd/go/internal/envcmd/env.go
+++ b/src/cmd/go/internal/envcmd/env.go
@@ -189,16 +189,16 @@ func findEnv(env []cfg.EnvVar, name string) string {
}
// ExtraEnvVars returns environment variables that should not leak into child processes.
-func ExtraEnvVars(loaderstate *modload.State) []cfg.EnvVar {
+func ExtraEnvVars(ld *modload.Loader) []cfg.EnvVar {
gomod := ""
- modload.Init(loaderstate)
- if loaderstate.HasModRoot() {
- gomod = loaderstate.ModFilePath()
- } else if loaderstate.Enabled() {
+ modload.Init(ld)
+ if ld.HasModRoot() {
+ gomod = ld.ModFilePath()
+ } else if ld.Enabled() {
gomod = os.DevNull
}
- loaderstate.InitWorkfile()
- gowork := modload.WorkFilePath(loaderstate)
+ ld.InitWorkfile()
+ gowork := modload.WorkFilePath(ld)
// As a special case, if a user set off explicitly, report that in GOWORK.
if cfg.Getenv("GOWORK") == "off" {
gowork = "off"
@@ -211,8 +211,8 @@ func ExtraEnvVars(loaderstate *modload.State) []cfg.EnvVar {
// ExtraEnvVarsCostly returns environment variables that should not leak into child processes
// but are costly to evaluate.
-func ExtraEnvVarsCostly(loaderstate *modload.State) []cfg.EnvVar {
- b := work.NewBuilder("", loaderstate.VendorDirOrEmpty)
+func ExtraEnvVarsCostly(ld *modload.Loader) []cfg.EnvVar {
+ b := work.NewBuilder("", ld.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -272,7 +272,7 @@ func argKey(arg string) string {
}
func runEnv(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if *envJson && *envU {
base.Fatalf("go: cannot use -json with -u")
}
@@ -307,7 +307,7 @@ func runEnv(ctx context.Context, cmd *base.Command, args []string) {
}
env := cfg.CmdEnv
- env = append(env, ExtraEnvVars(moduleLoaderState)...)
+ env = append(env, ExtraEnvVars(moduleLoader)...)
if err := fsys.Init(); err != nil {
base.Fatal(err)
@@ -337,8 +337,8 @@ func runEnv(ctx context.Context, cmd *base.Command, args []string) {
}
}
if needCostly {
- work.BuildInit(moduleLoaderState)
- env = append(env, ExtraEnvVarsCostly(moduleLoaderState)...)
+ work.BuildInit(moduleLoader)
+ env = append(env, ExtraEnvVarsCostly(moduleLoader)...)
}
if len(args) > 0 {
diff --git a/src/cmd/go/internal/fmtcmd/fmt.go b/src/cmd/go/internal/fmtcmd/fmt.go
index fe356bdc08..7f7322b6d7 100644
--- a/src/cmd/go/internal/fmtcmd/fmt.go
+++ b/src/cmd/go/internal/fmtcmd/fmt.go
@@ -50,7 +50,7 @@ See also: go fix, go vet.
}
func runFmt(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
printed := false
gofmt := gofmtPath()
@@ -60,8 +60,8 @@ func runFmt(ctx context.Context, cmd *base.Command, args []string) {
baseGofmtArgs := len(gofmtArgs)
baseGofmtArgLen := gofmtArgLen
- for _, pkg := range load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{}, args) {
- if moduleLoaderState.Enabled() && pkg.Module != nil && !pkg.Module.Main {
+ for _, pkg := range load.PackagesAndErrors(moduleLoader, ctx, load.PackageOpts{}, args) {
+ if moduleLoader.Enabled() && pkg.Module != nil && !pkg.Module.Main {
if !printed {
fmt.Fprintf(os.Stderr, "go: not formatting packages in dependency modules\n")
printed = true
diff --git a/src/cmd/go/internal/generate/generate.go b/src/cmd/go/internal/generate/generate.go
index 59142859c1..bb66ce4bbd 100644
--- a/src/cmd/go/internal/generate/generate.go
+++ b/src/cmd/go/internal/generate/generate.go
@@ -182,8 +182,8 @@ func init() {
}
func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
if generateRunFlag != "" {
var err error
@@ -205,8 +205,8 @@ func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
// Even if the arguments are .go files, this loop suffices.
printed := false
pkgOpts := load.PackageOpts{IgnoreImports: true}
- for _, pkg := range load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, args) {
- if moduleLoaderState.Enabled() && pkg.Module != nil && !pkg.Module.Main {
+ for _, pkg := range load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, args) {
+ if moduleLoader.Enabled() && pkg.Module != nil && !pkg.Module.Main {
if !printed {
fmt.Fprintf(os.Stderr, "go: not generating in packages in dependency modules\n")
printed = true
diff --git a/src/cmd/go/internal/list/list.go b/src/cmd/go/internal/list/list.go
index 6df9c334fe..31dcc206aa 100644
--- a/src/cmd/go/internal/list/list.go
+++ b/src/cmd/go/internal/list/list.go
@@ -419,8 +419,8 @@ func (v *jsonFlag) needAny(fields ...string) bool {
var nl = []byte{'\n'}
func runList(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
if *listFmt != "" && listJson {
base.Fatalf("go list -f cannot be used with -json")
@@ -428,11 +428,11 @@ 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 != "" && moduleLoaderState.HasModRoot() {
+ if *listReuse != "" && moduleLoader.HasModRoot() {
base.Fatalf("go list -reuse cannot be used inside a module")
}
- work.BuildInit(moduleLoaderState)
+ work.BuildInit(moduleLoader)
out := newTrackingWriter(os.Stdout)
defer out.w.Flush()
@@ -480,7 +480,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
fm := template.FuncMap{
"join": strings.Join,
"context": context,
- "module": func(path string) *modinfo.ModulePublic { return modload.ModuleInfo(moduleLoaderState, ctx, path) },
+ "module": func(path string) *modinfo.ModulePublic { return modload.ModuleInfo(moduleLoader, ctx, path) },
}
tmpl, err := template.New("main").Funcs(fm).Parse(*listFmt)
if err != nil {
@@ -497,12 +497,12 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
}
}
- modload.Init(moduleLoaderState)
+ modload.Init(moduleLoader)
if *listRetracted {
if cfg.BuildMod == "vendor" {
base.Fatalf("go list -retracted cannot be used when vendoring is enabled")
}
- if !moduleLoaderState.Enabled() {
+ if !moduleLoader.Enabled() {
base.Fatalf("go list -retracted can only be used in module-aware mode")
}
}
@@ -526,11 +526,11 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
base.Fatalf("go list -test cannot be used with -m")
}
- if modload.Init(moduleLoaderState); !moduleLoaderState.Enabled() {
+ if modload.Init(moduleLoader); !moduleLoader.Enabled() {
base.Fatalf("go: list -m cannot be used with GO111MODULE=off")
}
- modload.LoadModFile(moduleLoaderState, ctx) // Sets cfg.BuildMod as a side-effect.
+ modload.LoadModFile(moduleLoader, ctx) // Sets cfg.BuildMod as a side-effect.
if cfg.BuildMod == "vendor" {
const actionDisabledFormat = "go: can't %s using the vendor directory\n\t(Use -mod=mod or -mod=readonly to bypass.)"
@@ -570,7 +570,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
if *listReuse != "" && len(args) == 0 {
base.Fatalf("go: list -m -reuse only has an effect with module@version arguments")
}
- mods, err := modload.ListModules(moduleLoaderState, ctx, args, mode, *listReuse)
+ mods, err := modload.ListModules(moduleLoader, ctx, args, mode, *listReuse)
if !*listE {
for _, m := range mods {
if m.Error != nil {
@@ -614,7 +614,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
SuppressBuildInfo: !*listExport && !listJsonFields.needAny("Stale", "StaleReason"),
SuppressEmbedFiles: !*listExport && !listJsonFields.needAny("EmbedFiles", "TestEmbedFiles", "XTestEmbedFiles"),
}
- pkgs := load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, args)
+ pkgs := load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, args)
if !*listE {
w := 0
for _, pkg := range pkgs {
@@ -649,10 +649,10 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
sema.Release(1)
wg.Done()
}
- pmain, ptest, pxtest = load.TestPackagesAndErrors(moduleLoaderState, ctx, done, pkgOpts, p, nil)
+ pmain, ptest, pxtest = load.TestPackagesAndErrors(moduleLoader, ctx, done, pkgOpts, p, nil)
} else {
var perr *load.Package
- pmain, ptest, pxtest, perr = load.TestPackagesFor(moduleLoaderState, ctx, pkgOpts, p, nil)
+ pmain, ptest, pxtest, perr = load.TestPackagesFor(moduleLoader, ctx, pkgOpts, p, nil)
if perr != nil {
base.Fatalf("go: can't load test package: %s", perr.Error)
}
@@ -714,7 +714,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
// Do we need to run a build to gather information?
needStale := (listJson && listJsonFields.needAny("Stale", "StaleReason")) || strings.Contains(*listFmt, ".Stale")
if needStale || *listExport || *listCompiled {
- b := work.NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
+ b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
if *listE {
b.AllowErrors = true
}
@@ -728,13 +728,13 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
b.NeedExport = *listExport
b.NeedCompiledGoFiles = *listCompiled
if cfg.BuildCover {
- load.PrepareForCoverageBuild(moduleLoaderState, pkgs)
+ load.PrepareForCoverageBuild(moduleLoader, pkgs)
}
a := &work.Action{}
// TODO: Use pkgsFilter?
for _, p := range pkgs {
if len(p.GoFiles)+len(p.CgoFiles) > 0 {
- a.Deps = append(a.Deps, b.AutoAction(moduleLoaderState, work.ModeInstall, work.ModeInstall, p))
+ a.Deps = append(a.Deps, b.AutoAction(moduleLoader, work.ModeInstall, work.ModeInstall, p))
}
}
b.Do(ctx, a)
@@ -742,8 +742,8 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
for _, p := range pkgs {
// Show vendor-expanded paths in listing
- p.TestImports = p.Resolve(moduleLoaderState, p.TestImports)
- p.XTestImports = p.Resolve(moduleLoaderState, p.XTestImports)
+ p.TestImports = p.Resolve(moduleLoader, p.TestImports)
+ p.XTestImports = p.Resolve(moduleLoader, p.XTestImports)
p.DepOnly = !cmdline[p]
if *listCompiled {
@@ -851,7 +851,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
if *listRetracted {
mode |= modload.ListRetracted
}
- rmods, err := modload.ListModules(moduleLoaderState, ctx, args, mode, *listReuse)
+ rmods, err := modload.ListModules(moduleLoader, ctx, args, mode, *listReuse)
if err != nil && !*listE {
base.Error(err)
}
diff --git a/src/cmd/go/internal/load/flag.go b/src/cmd/go/internal/load/flag.go
index a9188db0fd..f0dc99b07a 100644
--- a/src/cmd/go/internal/load/flag.go
+++ b/src/cmd/go/internal/load/flag.go
@@ -30,7 +30,7 @@ type PerPackageFlag struct {
// A ppfValue is a single <pattern>=<flags> per-package flag value.
type ppfValue struct {
- match func(*modload.State, *Package) bool // compiled pattern
+ match func(*modload.Loader, *Package) bool // compiled pattern
flags []string
}
@@ -43,7 +43,7 @@ func (f *PerPackageFlag) Set(v string) error {
func (f *PerPackageFlag) set(v, cwd string) error {
f.raw = v
f.present = true
- match := func(_ *modload.State, p *Package) bool { return p.Internal.CmdlinePkg || p.Internal.CmdlineFiles } // default predicate with no pattern
+ match := func(_ *modload.Loader, p *Package) bool { return p.Internal.CmdlinePkg || p.Internal.CmdlineFiles } // default predicate with no pattern
// For backwards compatibility with earlier flag splitting, ignore spaces around flags.
v = strings.TrimSpace(v)
if v == "" {
@@ -89,7 +89,7 @@ func (f *PerPackageFlag) Present() bool {
//
// The module loader state is used by the matcher to know if certain
// patterns match packages within the state's MainModules.
-func (f *PerPackageFlag) For(s *modload.State, p *Package) []string {
+func (f *PerPackageFlag) For(s *modload.Loader, p *Package) []string {
flags := []string{}
for _, v := range f.values {
if v.match(s, p) {
diff --git a/src/cmd/go/internal/load/flag_test.go b/src/cmd/go/internal/load/flag_test.go
index 0c2363cb79..13d195aa8f 100644
--- a/src/cmd/go/internal/load/flag_test.go
+++ b/src/cmd/go/internal/load/flag_test.go
@@ -126,7 +126,7 @@ func TestPerPackageFlag(t *testing.T) {
}
for _, p := range tt.pkgs {
dir := nativeDir(p.dir)
- flags := ppFlags.For(modload.NewState(), &Package{PackagePublic: PackagePublic{ImportPath: p.path, Dir: dir}, Internal: PackageInternal{CmdlinePkg: p.cmdline}})
+ flags := ppFlags.For(modload.NewLoader(), &Package{PackagePublic: PackagePublic{ImportPath: p.path, Dir: dir}, Internal: PackageInternal{CmdlinePkg: p.cmdline}})
if !reflect.DeepEqual(flags, p.flags) {
t.Errorf("For(%v, %v, %v) = %v, want %v", p.path, dir, p.cmdline, flags, p.flags)
}
diff --git a/src/cmd/go/internal/load/godebug.go b/src/cmd/go/internal/load/godebug.go
index a6bcdad627..9f8182b82a 100644
--- a/src/cmd/go/internal/load/godebug.go
+++ b/src/cmd/go/internal/load/godebug.go
@@ -42,12 +42,12 @@ func ParseGoDebug(text string) (key, value string, err error) {
return k, v, nil
}
-func defaultGODEBUGGoVersion(loaderstate *modload.State, p *Package) string {
- if !loaderstate.Enabled() {
+func defaultGODEBUGGoVersion(ld *modload.Loader, p *Package) string {
+ if !ld.Enabled() {
// GOPATH mode. Use Go 1.20.
return "1.20"
}
- if loaderstate.RootMode == modload.NoRoot && p.Module != nil {
+ if ld.RootMode == modload.NoRoot && p.Module != nil {
// This is go install pkg@version or go run pkg@version.
// Use the Go version from the package.
// If there isn't one, then assume Go 1.20, the last
@@ -57,18 +57,18 @@ func defaultGODEBUGGoVersion(loaderstate *modload.State, p *Package) string {
}
return "1.20"
}
- return loaderstate.MainModules.GoVersion(loaderstate)
+ return ld.MainModules.GoVersion(ld)
}
// defaultGODEBUG returns the default GODEBUG setting for the main package p.
// When building a test binary, directives, testDirectives, and xtestDirectives
// list additional directives from the package under test.
-func defaultGODEBUG(loaderstate *modload.State, p *Package, directives, testDirectives, xtestDirectives []build.Directive) string {
+func defaultGODEBUG(ld *modload.Loader, p *Package, directives, testDirectives, xtestDirectives []build.Directive) string {
if p.Name != "main" {
return ""
}
- goVersion := defaultGODEBUGGoVersion(loaderstate, p)
+ goVersion := defaultGODEBUGGoVersion(ld, p)
var m map[string]string
@@ -79,7 +79,7 @@ func defaultGODEBUG(loaderstate *modload.State, p *Package, directives, testDire
}
// Add directives from main module go.mod.
- for _, g := range loaderstate.MainModules.Godebugs(loaderstate) {
+ for _, g := range ld.MainModules.Godebugs(ld) {
if m == nil {
m = make(map[string]string)
}
diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go
index e2a77d7d7d..f40de7fe12 100644
--- a/src/cmd/go/internal/load/pkg.go
+++ b/src/cmd/go/internal/load/pkg.go
@@ -356,7 +356,7 @@ func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportSta
// can produce better error messages if it starts with the original paths.
// The initial load of p loads all the non-test imports and rewrites
// the vendored paths, so nothing should ever call p.vendored(p.Imports).
-func (p *Package) Resolve(s *modload.State, imports []string) []string {
+func (p *Package) Resolve(s *modload.Loader, imports []string) []string {
if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
panic("internal error: p.Resolve(p.Imports) called")
}
@@ -687,8 +687,8 @@ const (
)
// LoadPackage does Load import, but without a parent package load context
-func LoadPackage(loaderstate *modload.State, ctx context.Context, opts PackageOpts, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
- p, err := loadImport(loaderstate, ctx, opts, nil, path, srcDir, nil, stk, importPos, mode)
+func LoadPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
+ p, err := loadImport(ld, ctx, opts, nil, path, srcDir, nil, stk, importPos, mode)
if err != nil {
base.Fatalf("internal error: loadImport of %q with nil parent returned an error", path)
}
@@ -704,7 +704,7 @@ func LoadPackage(loaderstate *modload.State, ctx context.Context, opts PackageOp
// The returned PackageError, if any, describes why parent is not allowed
// to import the named package, with the error referring to importPos.
// The PackageError can only be non-nil when parent is not nil.
-func loadImport(loaderstate *modload.State, ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError) {
+func loadImport(ld *modload.Loader, ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError) {
ctx, span := trace.StartSpan(ctx, "modload.loadImport "+path)
defer span.Done()
@@ -719,9 +719,9 @@ func loadImport(loaderstate *modload.State, ctx context.Context, opts PackageOpt
parentRoot = parent.Root
parentIsStd = parent.Standard
}
- bp, loaded, err := loadPackageData(loaderstate, ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
+ bp, loaded, err := loadPackageData(ld, ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
if loaded && pre != nil && !opts.IgnoreImports {
- pre.preloadImports(loaderstate, ctx, opts, bp.Imports, bp)
+ pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
}
if bp == nil {
p := &Package{
@@ -772,7 +772,7 @@ func loadImport(loaderstate *modload.State, ctx context.Context, opts PackageOpt
// Load package.
// loadPackageData may return bp != nil even if an error occurs,
// in order to return partial information.
- p.load(loaderstate, ctx, opts, path, stk, importPos, bp, err)
+ p.load(ld, ctx, opts, path, stk, importPos, bp, err)
if !cfg.ModulesEnabled && path != cleanImport(path) {
p.Error = &PackageError{
@@ -785,7 +785,7 @@ func loadImport(loaderstate *modload.State, ctx context.Context, opts PackageOpt
}
// Checked on every import because the rules depend on the code doing the importing.
- if perr := disallowInternal(loaderstate, ctx, srcDir, parent, parentPath, p, stk); perr != nil {
+ if perr := disallowInternal(ld, ctx, srcDir, parent, parentPath, p, stk); perr != nil {
perr.setPos(importPos)
return p, perr
}
@@ -839,7 +839,7 @@ func extractFirstImport(importPos []token.Position) *token.Position {
//
// loadPackageData returns a boolean, loaded, which is true if this is the
// first time the package was loaded. Callers may preload imports in this case.
-func loadPackageData(loaderstate *modload.State, ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
+func loadPackageData(ld *modload.Loader, ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
ctx, span := trace.StartSpan(ctx, "load.loadPackageData "+path)
defer span.Done()
@@ -884,7 +884,7 @@ func loadPackageData(loaderstate *modload.State, ctx context.Context, path, pare
r.path = newPath
r.dir = dir
} else if cfg.ModulesEnabled {
- r.dir, r.path, r.err = modload.Lookup(loaderstate, parentPath, parentIsStd, path)
+ r.dir, r.path, r.err = modload.Lookup(ld, parentPath, parentIsStd, path)
} else if build.IsLocalImport(path) {
r.dir = filepath.Join(parentDir, path)
r.path = dirToImportPath(r.dir)
@@ -893,7 +893,7 @@ func loadPackageData(loaderstate *modload.State, ctx context.Context, path, pare
// find out the key to use in packageCache without the
// overhead of repeated calls to buildContext.Import.
// The code is also needed in a few other places anyway.
- r.path = resolveImportPath(loaderstate, path, parentPath, parentDir, parentRoot, parentIsStd)
+ r.path = resolveImportPath(ld, path, parentPath, parentDir, parentRoot, parentIsStd)
} else if mode&ResolveModule != 0 {
r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
}
@@ -922,7 +922,7 @@ func loadPackageData(loaderstate *modload.State, ctx context.Context, path, pare
} else {
buildContext.GOPATH = "" // Clear GOPATH so packages are imported as pure module packages
}
- modroot := modload.PackageModRoot(loaderstate, ctx, r.path)
+ modroot := modload.PackageModRoot(ld, ctx, r.path)
if modroot == "" && str.HasPathPrefix(r.dir, cfg.GOROOTsrc) {
modroot = cfg.GOROOTsrc
gorootSrcCmd := filepath.Join(cfg.GOROOTsrc, "cmd")
@@ -943,7 +943,7 @@ func loadPackageData(loaderstate *modload.State, ctx context.Context, path, pare
if cfg.ModulesEnabled {
// Override data.p.Root, since ImportDir sets it to $GOPATH, if
// the module is inside $GOPATH/src.
- if info := modload.PackageModuleInfo(loaderstate, ctx, path); info != nil {
+ if info := modload.PackageModuleInfo(ld, ctx, path); info != nil {
data.p.Root = info.Dir
}
}
@@ -990,7 +990,7 @@ func loadPackageData(loaderstate *modload.State, ctx context.Context, path, pare
if cfg.GOBIN != "" {
data.p.BinDir = cfg.GOBIN
} else if cfg.ModulesEnabled {
- data.p.BinDir = modload.BinDir(loaderstate)
+ data.p.BinDir = modload.BinDir(ld)
}
}
@@ -1069,7 +1069,7 @@ func newPreload() *preload {
// preloadMatches loads data for package paths matched by patterns.
// When preloadMatches returns, some packages may not be loaded yet, but
// loadPackageData and loadImport are always safe to call.
-func (pre *preload) preloadMatches(loaderstate *modload.State, ctx context.Context, opts PackageOpts, matches []*search.Match) {
+func (pre *preload) preloadMatches(ld *modload.Loader, ctx context.Context, opts PackageOpts, matches []*search.Match) {
for _, m := range matches {
for _, pkg := range m.Pkgs {
select {
@@ -1078,10 +1078,10 @@ func (pre *preload) preloadMatches(loaderstate *modload.State, ctx context.Conte
case pre.sema <- struct{}{}:
go func(pkg string) {
mode := 0 // don't use vendoring or module import resolution
- bp, loaded, err := loadPackageData(loaderstate, ctx, pkg, "", base.Cwd(), "", false, mode)
+ bp, loaded, err := loadPackageData(ld, ctx, pkg, "", base.Cwd(), "", false, mode)
<-pre.sema
if bp != nil && loaded && err == nil && !opts.IgnoreImports {
- pre.preloadImports(loaderstate, ctx, opts, bp.Imports, bp)
+ pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
}
}(pkg)
}
@@ -1092,7 +1092,7 @@ func (pre *preload) preloadMatches(loaderstate *modload.State, ctx context.Conte
// preloadImports queues a list of imports for preloading.
// When preloadImports returns, some packages may not be loaded yet,
// but loadPackageData and loadImport are always safe to call.
-func (pre *preload) preloadImports(loaderstate *modload.State, ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
+func (pre *preload) preloadImports(ld *modload.Loader, ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
for _, path := range imports {
if path == "C" || path == "unsafe" {
@@ -1103,10 +1103,10 @@ func (pre *preload) preloadImports(loaderstate *modload.State, ctx context.Conte
return
case pre.sema <- struct{}{}:
go func(path string) {
- bp, loaded, err := loadPackageData(loaderstate, ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
+ bp, loaded, err := loadPackageData(ld, ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
<-pre.sema
if bp != nil && loaded && err == nil && !opts.IgnoreImports {
- pre.preloadImports(loaderstate, ctx, opts, bp.Imports, bp)
+ pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
}
}(path)
}
@@ -1152,7 +1152,7 @@ func isDir(path string) bool {
// First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
// If vendor expansion doesn't trigger, then the path is also subject to
// Go 1.11 module legacy conversion (golang.org/issue/25069).
-func ResolveImportPath(s *modload.State, parent *Package, path string) (found string) {
+func ResolveImportPath(s *modload.Loader, parent *Package, path string) (found string) {
var parentPath, parentDir, parentRoot string
parentIsStd := false
if parent != nil {
@@ -1164,7 +1164,7 @@ func ResolveImportPath(s *modload.State, parent *Package, path string) (found st
return resolveImportPath(s, path, parentPath, parentDir, parentRoot, parentIsStd)
}
-func resolveImportPath(s *modload.State, path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
+func resolveImportPath(s *modload.Loader, path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
if cfg.ModulesEnabled {
if _, p, e := modload.Lookup(s, parentPath, parentIsStd, path); e == nil {
return p
@@ -1464,7 +1464,7 @@ func reusePackage(p *Package, stk *ImportStack) *Package {
// is allowed to import p.
// If the import is allowed, disallowInternal returns the original package p.
// If not, it returns a new package containing just an appropriate error.
-func disallowInternal(loaderstate *modload.State, ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *PackageError {
+func disallowInternal(ld *modload.Loader, ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *PackageError {
// golang.org/s/go14internal:
// An import of a path containing the element “internal”
// is disallowed if the importing code is outside the tree
@@ -1553,7 +1553,7 @@ func disallowInternal(loaderstate *modload.State, ctx context.Context, srcDir st
// directory containing them.
// If the directory is outside the main modules, this will resolve to ".",
// which is not a prefix of any valid module.
- importerPath, _ = loaderstate.MainModules.DirImportPath(loaderstate, ctx, importer.Dir)
+ importerPath, _ = ld.MainModules.DirImportPath(ld, ctx, importer.Dir)
}
parentOfInternal := p.ImportPath[:i]
if str.HasPathPrefix(importerPath, parentOfInternal) {
@@ -1772,7 +1772,7 @@ func (p *Package) DefaultExecName() string {
// load populates p using information from bp, err, which should
// be the result of calling build.Context.Import.
// stk contains the import stack, not including path itself.
-func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
+func (p *Package) load(ld *modload.Loader, ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
p.copyBuild(opts, bp)
// The localPrefix is the path we interpret ./ imports relative to,
@@ -1836,7 +1836,7 @@ func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts Pac
elem = full
}
if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
- p.Internal.Build.BinDir = modload.BinDir(loaderstate)
+ p.Internal.Build.BinDir = modload.BinDir(ld)
}
if p.Internal.Build.BinDir != "" {
// Install to GOBIN or bin of GOPATH entry.
@@ -1936,7 +1936,7 @@ func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts Pac
// The linker loads implicit dependencies.
if p.Name == "main" && !p.Internal.ForceLibrary {
- ldDeps, err := LinkerDeps(loaderstate, p)
+ ldDeps, err := LinkerDeps(ld, p)
if err != nil {
setError(err)
return
@@ -1974,9 +1974,9 @@ func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts Pac
pkgPath = "command-line-arguments"
}
if cfg.ModulesEnabled {
- p.Module = modload.PackageModuleInfo(loaderstate, ctx, pkgPath)
+ p.Module = modload.PackageModuleInfo(ld, ctx, pkgPath)
}
- p.DefaultGODEBUG = defaultGODEBUG(loaderstate, p, nil, nil, nil)
+ p.DefaultGODEBUG = defaultGODEBUG(ld, p, nil, nil, nil)
if !opts.SuppressEmbedFiles {
p.EmbedFiles, p.Internal.Embed, err = resolveEmbed(p.Dir, p.EmbedPatterns)
@@ -2027,7 +2027,7 @@ func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts Pac
if path == "C" {
continue
}
- p1, err := loadImport(loaderstate, ctx, opts, nil, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
+ p1, err := loadImport(ld, ctx, opts, nil, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
if err != nil && p.Error == nil {
p.Error = err
p.Incomplete = true
@@ -2050,7 +2050,7 @@ func (p *Package) load(loaderstate *modload.State, ctx context.Context, opts Pac
// Consider starting this as a background goroutine and retrieving the result
// asynchronously when we're actually ready to build the package, or when we
// actually need to evaluate whether the package's metadata is stale.
- p.setBuildInfo(ctx, loaderstate.Fetcher(), opts.AutoVCS)
+ p.setBuildInfo(ctx, ld.Fetcher(), opts.AutoVCS)
}
// If cgo is not enabled, ignore cgo supporting sources
@@ -2636,7 +2636,7 @@ func SafeArg(name string) bool {
}
// LinkerDeps returns the list of linker-induced dependencies for main package p.
-func LinkerDeps(s *modload.State, p *Package) ([]string, error) {
+func LinkerDeps(s *modload.Loader, p *Package) ([]string, error) {
// Everything links runtime.
deps := []string{"runtime"}
@@ -2674,7 +2674,7 @@ func LinkerDeps(s *modload.State, p *Package) ([]string, error) {
// externalLinkingReason reports the reason external linking is required
// even for programs that do not use cgo, or the empty string if external
// linking is not required.
-func externalLinkingReason(s *modload.State, p *Package) (what string) {
+func externalLinkingReason(s *modload.Loader, p *Package) (what string) {
// Some targets must use external linking even inside GOROOT.
if platform.MustLinkExternal(cfg.Goos, cfg.Goarch, false) {
return cfg.Goos + "/" + cfg.Goarch
@@ -2798,7 +2798,7 @@ func PackageList(roots []*Package) []*Package {
// TestPackageList returns the list of packages in the dag rooted at roots
// as visited in a depth-first post-order traversal, including the test
// imports of the roots. This ignores errors in test packages.
-func TestPackageList(loaderstate *modload.State, ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
+func TestPackageList(ld *modload.Loader, ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
seen := map[*Package]bool{}
all := []*Package{}
var walk func(*Package)
@@ -2814,7 +2814,7 @@ func TestPackageList(loaderstate *modload.State, ctx context.Context, opts Packa
}
walkTest := func(root *Package, path string) {
var stk ImportStack
- p1, err := loadImport(loaderstate, ctx, opts, nil, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
+ p1, err := loadImport(ld, ctx, opts, nil, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
if err != nil && root.Error == nil {
// Assign error importing the package to the importer.
root.Error = err
@@ -2841,17 +2841,17 @@ func TestPackageList(loaderstate *modload.State, ctx context.Context, opts Packa
// dependencies (like sync/atomic for coverage).
// TODO(jayconrod): delete this function and set flags automatically
// in LoadImport instead.
-func LoadImportWithFlags(loaderstate *modload.State, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError) {
- p, err := loadImport(loaderstate, context.TODO(), PackageOpts{}, nil, path, srcDir, parent, stk, importPos, mode)
- setToolFlags(loaderstate, p)
+func LoadImportWithFlags(ld *modload.Loader, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError) {
+ p, err := loadImport(ld, context.TODO(), PackageOpts{}, nil, path, srcDir, parent, stk, importPos, mode)
+ setToolFlags(ld, p)
return p, err
}
// LoadPackageWithFlags is the same as LoadImportWithFlags but without a parent.
// It's then guaranteed to not return an error
-func LoadPackageWithFlags(loaderstate *modload.State, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
- p := LoadPackage(loaderstate, context.TODO(), PackageOpts{}, path, srcDir, stk, importPos, mode)
- setToolFlags(loaderstate, p)
+func LoadPackageWithFlags(ld *modload.Loader, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
+ p := LoadPackage(ld, context.TODO(), PackageOpts{}, path, srcDir, stk, importPos, mode)
+ setToolFlags(ld, p)
return p
}
@@ -2900,7 +2900,7 @@ type PackageOpts struct {
//
// To obtain a flat list of packages, use PackageList.
// To report errors loading packages, use ReportPackageErrors.
-func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts PackageOpts, patterns []string) []*Package {
+func PackagesAndErrors(ld *modload.Loader, ctx context.Context, opts PackageOpts, patterns []string) []*Package {
ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
defer span.Done()
@@ -2912,7 +2912,7 @@ func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts Pac
// We need to test whether the path is an actual Go file and not a
// package path or pattern ending in '.go' (see golang.org/issue/34653).
if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
- pkgs := []*Package{GoFilesPackage(loaderstate, ctx, opts, patterns)}
+ pkgs := []*Package{GoFilesPackage(ld, ctx, opts, patterns)}
setPGOProfilePath(pkgs)
return pkgs
}
@@ -2920,13 +2920,13 @@ func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts Pac
}
var matches []*search.Match
- if modload.Init(loaderstate); cfg.ModulesEnabled {
+ if modload.Init(ld); cfg.ModulesEnabled {
modOpts := modload.PackageOpts{
ResolveMissingImports: true,
LoadTests: opts.ModResolveTests,
SilencePackageErrors: true,
}
- matches, _ = modload.LoadPackages(loaderstate, ctx, modOpts, patterns...)
+ matches, _ = modload.LoadPackages(ld, ctx, modOpts, patterns...)
} else {
matches = search.ImportPaths(patterns)
}
@@ -2939,7 +2939,7 @@ func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts Pac
pre := newPreload()
defer pre.flush()
- pre.preloadMatches(loaderstate, ctx, opts, matches)
+ pre.preloadMatches(ld, ctx, opts, matches)
for _, m := range matches {
for _, pkg := range m.Pkgs {
@@ -2953,7 +2953,7 @@ func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts Pac
// a literal and also a non-literal pattern.
mode |= cmdlinePkgLiteral
}
- p, perr := loadImport(loaderstate, ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, mode)
+ p, perr := loadImport(ld, ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, mode)
if perr != nil {
base.Fatalf("internal error: loadImport of %q with nil parent returned an error", pkg)
}
@@ -2993,7 +2993,7 @@ func PackagesAndErrors(loaderstate *modload.State, ctx context.Context, opts Pac
// compute the effective flags for all loaded packages
// (not just the ones matching the patterns but also
// their dependencies).
- setToolFlags(loaderstate, pkgs...)
+ setToolFlags(ld, pkgs...)
setPGOProfilePath(pkgs)
@@ -3232,20 +3232,20 @@ func (e *mainPackageError) ImportPath() string {
return e.importPath
}
-func setToolFlags(loaderstate *modload.State, pkgs ...*Package) {
+func setToolFlags(ld *modload.Loader, pkgs ...*Package) {
for _, p := range PackageList(pkgs) {
- p.Internal.Asmflags = BuildAsmflags.For(loaderstate, p)
- p.Internal.Gcflags = BuildGcflags.For(loaderstate, p)
- p.Internal.Ldflags = BuildLdflags.For(loaderstate, p)
- p.Internal.Gccgoflags = BuildGccgoflags.For(loaderstate, p)
+ p.Internal.Asmflags = BuildAsmflags.For(ld, p)
+ p.Internal.Gcflags = BuildGcflags.For(ld, p)
+ p.Internal.Ldflags = BuildLdflags.For(ld, p)
+ p.Internal.Gccgoflags = BuildGccgoflags.For(ld, p)
}
}
// GoFilesPackage creates a package for building a collection of Go files
// (typically named on the command line). The target is named p.a for
// package p or named after the first Go file for package main.
-func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts PackageOpts, gofiles []string) *Package {
- modload.Init(loaderstate)
+func GoFilesPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, gofiles []string) *Package {
+ modload.Init(ld)
for _, f := range gofiles {
if !strings.HasSuffix(f, ".go") {
@@ -3290,7 +3290,7 @@ func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts Packag
ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil }
if cfg.ModulesEnabled {
- modload.ImportFromFiles(loaderstate, ctx, gofiles)
+ modload.ImportFromFiles(ld, ctx, gofiles)
}
var err error
@@ -3306,7 +3306,7 @@ func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts Packag
pkg := new(Package)
pkg.Internal.Local = true
pkg.Internal.CmdlineFiles = true
- pkg.load(loaderstate, ctx, opts, "command-line-arguments", &stk, nil, bp, err)
+ pkg.load(ld, ctx, opts, "command-line-arguments", &stk, nil, bp, err)
if !cfg.ModulesEnabled {
pkg.Internal.LocalPrefix = dirToImportPath(dir)
}
@@ -3320,7 +3320,7 @@ func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts Packag
if cfg.GOBIN != "" {
pkg.Target = filepath.Join(cfg.GOBIN, exe)
} else if cfg.ModulesEnabled {
- pkg.Target = filepath.Join(modload.BinDir(loaderstate), exe)
+ pkg.Target = filepath.Join(modload.BinDir(ld), exe)
}
}
@@ -3328,7 +3328,7 @@ func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts Packag
pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
pkg.Incomplete = true
}
- setToolFlags(loaderstate, pkg)
+ setToolFlags(ld, pkg)
return pkg
}
@@ -3348,11 +3348,11 @@ func GoFilesPackage(loaderstate *modload.State, ctx context.Context, opts Packag
// module, but its go.mod file (if it has one) must not contain directives that
// would cause it to be interpreted differently if it were the main module
// (replace, exclude).
-func PackagesAndErrorsOutsideModule(loaderstate *modload.State, ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
- if !loaderstate.ForceUseModules {
+func PackagesAndErrorsOutsideModule(ld *modload.Loader, ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
+ if !ld.ForceUseModules {
panic("modload.ForceUseModules must be true")
}
- if loaderstate.RootMode != modload.NoRoot {
+ if ld.RootMode != modload.NoRoot {
panic("modload.RootMode must be NoRoot")
}
@@ -3399,25 +3399,25 @@ func PackagesAndErrorsOutsideModule(loaderstate *modload.State, ctx context.Cont
// (first result). It's possible this module won't provide packages named by
// later arguments, and other modules would. Let's not try to be too
// magical though.
- allowed := loaderstate.CheckAllowed
+ allowed := ld.CheckAllowed
if modload.IsRevisionQuery(firstPath, version) {
// Don't check for retractions if a specific revision is requested.
allowed = nil
}
noneSelected := func(path string) (version string) { return "none" }
- qrs, err := modload.QueryPackages(loaderstate, ctx, patterns[0], version, noneSelected, allowed)
+ qrs, err := modload.QueryPackages(ld, ctx, patterns[0], version, noneSelected, allowed)
if err != nil {
return nil, fmt.Errorf("%s: %w", args[0], err)
}
rootMod := qrs[0].Mod
- deprecation, err := modload.CheckDeprecation(loaderstate, ctx, rootMod)
+ deprecation, err := modload.CheckDeprecation(ld, ctx, rootMod)
if err != nil {
return nil, fmt.Errorf("%s: %w", args[0], err)
}
if deprecation != "" {
fmt.Fprintf(os.Stderr, "go: module %s is deprecated: %s\n", rootMod.Path, modload.ShortMessage(deprecation, ""))
}
- data, err := loaderstate.Fetcher().GoMod(ctx, rootMod.Path, rootMod.Version)
+ data, err := ld.Fetcher().GoMod(ctx, rootMod.Path, rootMod.Version)
if err != nil {
return nil, fmt.Errorf("%s: %w", args[0], err)
}
@@ -3439,12 +3439,12 @@ func PackagesAndErrorsOutsideModule(loaderstate *modload.State, ctx context.Cont
// Since we are in NoRoot mode, the build list initially contains only
// the dummy command-line-arguments module. Add a requirement on the
// module that provides the packages named on the command line.
- if _, err := modload.EditBuildList(loaderstate, ctx, nil, []module.Version{rootMod}); err != nil {
+ if _, err := modload.EditBuildList(ld, ctx, nil, []module.Version{rootMod}); err != nil {
return nil, fmt.Errorf("%s: %w", args[0], err)
}
// Load packages for all arguments.
- pkgs := PackagesAndErrors(loaderstate, ctx, opts, patterns)
+ pkgs := PackagesAndErrors(ld, ctx, opts, patterns)
// Check that named packages are all provided by the same module.
for _, pkg := range pkgs {
@@ -3472,7 +3472,7 @@ func PackagesAndErrorsOutsideModule(loaderstate *modload.State, ctx context.Cont
}
// EnsureImport ensures that package p imports the named package.
-func EnsureImport(s *modload.State, p *Package, pkg string) {
+func EnsureImport(s *modload.Loader, p *Package, pkg string) {
for _, d := range p.Internal.Imports {
if d.Name == pkg {
return
@@ -3495,10 +3495,10 @@ func EnsureImport(s *modload.State, p *Package, pkg string) {
// "go test -cover"). It walks through the packages being built (and
// dependencies) and marks them for coverage instrumentation when
// appropriate, and possibly adding additional deps where needed.
-func PrepareForCoverageBuild(s *modload.State, pkgs []*Package) {
- var match []func(*modload.State, *Package) bool
+func PrepareForCoverageBuild(s *modload.Loader, pkgs []*Package) {
+ var match []func(*modload.Loader, *Package) bool
- matchMainModAndCommandLine := func(_ *modload.State, p *Package) bool {
+ matchMainModAndCommandLine := func(_ *modload.Loader, p *Package) bool {
// note that p.Standard implies p.Module == nil below.
return p.Internal.CmdlineFiles || p.Internal.CmdlinePkg || (p.Module != nil && p.Module.Main)
}
@@ -3506,7 +3506,7 @@ func PrepareForCoverageBuild(s *modload.State, pkgs []*Package) {
if len(cfg.BuildCoverPkg) != 0 {
// If -coverpkg has been specified, then we instrument only
// the specific packages selected by the user-specified pattern(s).
- match = make([]func(*modload.State, *Package) bool, len(cfg.BuildCoverPkg))
+ match = make([]func(*modload.Loader, *Package) bool, len(cfg.BuildCoverPkg))
for i := range cfg.BuildCoverPkg {
match[i] = MatchPackage(cfg.BuildCoverPkg[i], base.Cwd())
}
@@ -3514,7 +3514,7 @@ func PrepareForCoverageBuild(s *modload.State, pkgs []*Package) {
// Without -coverpkg, instrument only packages in the main module
// (if any), as well as packages/files specifically named on the
// command line.
- match = []func(*modload.State, *Package) bool{matchMainModAndCommandLine}
+ match = []func(*modload.Loader, *Package) bool{matchMainModAndCommandLine}
}
// Visit the packages being built or installed, along with all of
@@ -3523,7 +3523,7 @@ func PrepareForCoverageBuild(s *modload.State, pkgs []*Package) {
SelectCoverPackages(s, PackageList(pkgs), match, "build")
}
-func SelectCoverPackages(s *modload.State, roots []*Package, match []func(*modload.State, *Package) bool, op string) []*Package {
+func SelectCoverPackages(s *modload.Loader, roots []*Package, match []func(*modload.Loader, *Package) bool, op string) []*Package {
var warntag string
var includeMain bool
switch op {
diff --git a/src/cmd/go/internal/load/search.go b/src/cmd/go/internal/load/search.go
index 749a00e848..fe2a5a5770 100644
--- a/src/cmd/go/internal/load/search.go
+++ b/src/cmd/go/internal/load/search.go
@@ -14,7 +14,7 @@ import (
)
// MatchPackage(pattern, cwd)(p) reports whether package p matches pattern in the working directory cwd.
-func MatchPackage(pattern, cwd string) func(*modload.State, *Package) bool {
+func MatchPackage(pattern, cwd string) func(*modload.Loader, *Package) bool {
switch {
case search.IsRelativePath(pattern):
// Split pattern into leading pattern-free directory path
@@ -29,10 +29,10 @@ func MatchPackage(pattern, cwd string) func(*modload.State, *Package) bool {
}
dir = filepath.Join(cwd, dir)
if pattern == "" {
- return func(_ *modload.State, p *Package) bool { return p.Dir == dir }
+ return func(_ *modload.Loader, p *Package) bool { return p.Dir == dir }
}
matchPath := pkgpattern.MatchPattern(pattern)
- return func(_ *modload.State, p *Package) bool {
+ return func(_ *modload.Loader, p *Package) bool {
// Compute relative path to dir and see if it matches the pattern.
rel, err := filepath.Rel(dir, p.Dir)
if err != nil {
@@ -49,13 +49,13 @@ func MatchPackage(pattern, cwd string) func(*modload.State, *Package) bool {
// This is slightly inaccurate: it matches every package, which isn't the same
// as matching the "all" package pattern.
// TODO(matloob): Should we make this more accurate? Does anyone depend on this behavior?
- return func(_ *modload.State, p *Package) bool { return true }
+ return func(_ *modload.Loader, p *Package) bool { return true }
case pattern == "std":
- return func(_ *modload.State, p *Package) bool { return p.Standard }
+ return func(_ *modload.Loader, p *Package) bool { return p.Standard }
case pattern == "cmd":
- return func(_ *modload.State, p *Package) bool { return p.Standard && strings.HasPrefix(p.ImportPath, "cmd/") }
+ return func(_ *modload.Loader, p *Package) bool { return p.Standard && strings.HasPrefix(p.ImportPath, "cmd/") }
default:
- return func(s *modload.State, p *Package) bool {
+ return func(s *modload.Loader, p *Package) bool {
switch {
case pattern == "tool" && s.Enabled():
return s.MainModules.Tools()[p.ImportPath]
diff --git a/src/cmd/go/internal/load/test.go b/src/cmd/go/internal/load/test.go
index bb1bedd0d8..5c1ec603b5 100644
--- a/src/cmd/go/internal/load/test.go
+++ b/src/cmd/go/internal/load/test.go
@@ -48,8 +48,8 @@ type TestCover struct {
// the package containing an error if the test packages or
// their dependencies have errors.
// Only test packages without errors are returned.
-func TestPackagesFor(loaderstate *modload.State, ctx context.Context, opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest, perr *Package) {
- pmain, ptest, pxtest = TestPackagesAndErrors(loaderstate, ctx, nil, opts, p, cover)
+func TestPackagesFor(ld *modload.Loader, ctx context.Context, opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest, perr *Package) {
+ pmain, ptest, pxtest = TestPackagesAndErrors(ld, ctx, nil, opts, p, cover)
for _, p1 := range []*Package{ptest, pxtest, pmain} {
if p1 == nil {
// pxtest may be nil
@@ -99,7 +99,7 @@ func TestPackagesFor(loaderstate *modload.State, ctx context.Context, opts Packa
//
// The caller is expected to have checked that len(p.TestGoFiles)+len(p.XTestGoFiles) > 0,
// or else there's no point in any of this.
-func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done func(), opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package) {
+func TestPackagesAndErrors(ld *modload.Loader, ctx context.Context, done func(), opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package) {
ctx, span := trace.StartSpan(ctx, "load.TestPackagesAndErrors")
defer span.Done()
@@ -107,7 +107,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
defer pre.flush()
allImports := append([]string{}, p.TestImports...)
allImports = append(allImports, p.XTestImports...)
- pre.preloadImports(loaderstate, ctx, opts, allImports, p.Internal.Build)
+ pre.preloadImports(ld, ctx, opts, allImports, p.Internal.Build)
var ptestErr, pxtestErr *PackageError
var imports, ximports []*Package
@@ -117,7 +117,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
stk.Push(ImportInfo{Pkg: p.ImportPath + " (test)"})
rawTestImports := str.StringList(p.TestImports)
for i, path := range p.TestImports {
- p1, err := loadImport(loaderstate, ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], ResolveImport)
+ p1, err := loadImport(ld, ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], ResolveImport)
if err != nil && ptestErr == nil {
ptestErr = err
incomplete = true
@@ -146,7 +146,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
var pxtestIncomplete bool
rawXTestImports := str.StringList(p.XTestImports)
for i, path := range p.XTestImports {
- p1, err := loadImport(loaderstate, ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], ResolveImport)
+ p1, err := loadImport(ld, ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], ResolveImport)
if err != nil && pxtestErr == nil {
pxtestErr = err
}
@@ -293,7 +293,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
}
pb := p.Internal.Build
- pmain.DefaultGODEBUG = defaultGODEBUG(loaderstate, pmain, pb.Directives, pb.TestDirectives, pb.XTestDirectives)
+ pmain.DefaultGODEBUG = defaultGODEBUG(ld, pmain, pb.Directives, pb.TestDirectives, pb.XTestDirectives)
// The generated main also imports testing, regexp, and os.
// Also the linker introduces implicit dependencies reported by LinkerDeps.
@@ -302,7 +302,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
if cover != nil {
deps = append(deps, "internal/coverage/cfile")
}
- ldDeps, err := LinkerDeps(loaderstate, p)
+ ldDeps, err := LinkerDeps(ld, p)
if err != nil && pmain.Error == nil {
pmain.Error = &PackageError{Err: err}
}
@@ -313,7 +313,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
if dep == ptest.ImportPath {
pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
} else {
- p1, err := loadImport(loaderstate, ctx, opts, pre, dep, "", nil, &stk, nil, 0)
+ p1, err := loadImport(ld, ctx, opts, pre, dep, "", nil, &stk, nil, 0)
if err != nil && pmain.Error == nil {
pmain.Error = err
pmain.Incomplete = true
@@ -328,7 +328,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
allTestImports = append(allTestImports, pmain.Internal.Imports...)
allTestImports = append(allTestImports, imports...)
allTestImports = append(allTestImports, ximports...)
- setToolFlags(loaderstate, allTestImports...)
+ setToolFlags(ld, allTestImports...)
// Do initial scan for metadata needed for writing _testmain.go
// Use that metadata to update the list of imports for package main.
@@ -376,7 +376,7 @@ func TestPackagesAndErrors(loaderstate *modload.State, ctx context.Context, done
// build info because the test variants of packages can add
// packages from modules that don't already have transitive
// imports from p.
- pmain.setBuildInfo(ctx, loaderstate.Fetcher(), opts.AutoVCS)
+ pmain.setBuildInfo(ctx, ld.Fetcher(), opts.AutoVCS)
}
if cover != nil {
diff --git a/src/cmd/go/internal/modcmd/download.go b/src/cmd/go/internal/modcmd/download.go
index 62bb064eae..8f0d827b1c 100644
--- a/src/cmd/go/internal/modcmd/download.go
+++ b/src/cmd/go/internal/modcmd/download.go
@@ -109,19 +109,19 @@ type ModuleJSON struct {
}
func runDownload(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
// Check whether modules are enabled and whether we're in a module.
- moduleLoaderState.ForceUseModules = true
+ moduleLoader.ForceUseModules = true
modload.ExplicitWriteGoMod = true
haveExplicitArgs := len(args) > 0
- if moduleLoaderState.HasModRoot() || modload.WorkFilePath(moduleLoaderState) != "" {
- modload.LoadModFile(moduleLoaderState, ctx) // to fill MainModules
+ if moduleLoader.HasModRoot() || modload.WorkFilePath(moduleLoader) != "" {
+ modload.LoadModFile(moduleLoader, ctx) // to fill MainModules
if haveExplicitArgs {
- for _, mainModule := range moduleLoaderState.MainModules.Versions() {
+ for _, mainModule := range moduleLoader.MainModules.Versions() {
targetAtUpgrade := mainModule.Path + "@upgrade"
targetAtPatch := mainModule.Path + "@patch"
for _, arg := range args {
@@ -131,14 +131,14 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
}
}
- } else if modload.WorkFilePath(moduleLoaderState) != "" {
+ } else if modload.WorkFilePath(moduleLoader) != "" {
// TODO(#44435): Think about what the correct query is to download the
// right set of modules. Also see code review comment at
// https://go-review.googlesource.com/c/go/+/359794/comments/ce946a80_6cf53992.
args = []string{"all"}
} else {
- mainModule := moduleLoaderState.MainModules.Versions()[0]
- modFile := moduleLoaderState.MainModules.ModFile(mainModule)
+ mainModule := moduleLoader.MainModules.Versions()[0]
+ modFile := moduleLoader.MainModules.ModFile(mainModule)
if modFile.Go == nil || gover.Compare(modFile.Go.Version, gover.ExplicitIndirectVersion) < 0 {
if len(modFile.Require) > 0 {
args = []string{"all"}
@@ -154,12 +154,12 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// However, we also need to load the full module graph, to ensure that
// we have downloaded enough of the module graph to run 'go list all',
// 'go mod graph', and similar commands.
- _, err := modload.LoadModGraph(moduleLoaderState, ctx, "")
+ _, err := modload.LoadModGraph(moduleLoader, ctx, "")
if err != nil {
// TODO(#64008): call base.Fatalf instead of toolchain.SwitchOrFatal
// here, since we can only reach this point with an outdated toolchain
// if the go.mod file is inconsistent.
- toolchain.SwitchOrFatal(moduleLoaderState, ctx, err)
+ toolchain.SwitchOrFatal(moduleLoader, ctx, err)
}
for _, m := range modFile.Require {
@@ -170,7 +170,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
if len(args) == 0 {
- if moduleLoaderState.HasModRoot() {
+ if moduleLoader.HasModRoot() {
os.Stderr.WriteString("go: no module dependencies to download\n")
} else {
base.Errorf("go: no modules specified (see 'go help mod download')")
@@ -178,14 +178,14 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
base.Exit()
}
- if *downloadReuse != "" && moduleLoaderState.HasModRoot() {
+ if *downloadReuse != "" && moduleLoader.HasModRoot() {
base.Fatalf("go mod download -reuse cannot be used inside a module")
}
var mods []*ModuleJSON
type token struct{}
sem := make(chan token, runtime.GOMAXPROCS(0))
- infos, infosErr := modload.ListModules(moduleLoaderState, ctx, args, 0, *downloadReuse)
+ infos, infosErr := modload.ListModules(moduleLoader, ctx, args, 0, *downloadReuse)
// There is a bit of a chicken-and-egg problem here: ideally we need to know
// which Go version to switch to download the requested modules, but if we
@@ -212,7 +212,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// toolchain version) or only one module (as is used by the Go Module Proxy).
if infosErr != nil {
- sw := toolchain.NewSwitcher(moduleLoaderState)
+ sw := toolchain.NewSwitcher(moduleLoader)
sw.Error(infosErr)
if sw.NeedSwitch() {
sw.Switch(ctx)
@@ -221,7 +221,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// when we can.
}
- if !haveExplicitArgs && modload.WorkFilePath(moduleLoaderState) == "" {
+ if !haveExplicitArgs && modload.WorkFilePath(moduleLoader) == "" {
// 'go mod download' is sometimes run without arguments to pre-populate the
// module cache. In modules that aren't at go 1.17 or higher, it may fetch
// modules that aren't needed to build packages in the main module. This is
@@ -232,7 +232,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// TODO(#64008): In the future, report an error if go.mod or go.sum need to
// be updated after loading the build list. This may require setting
// the mode to "mod" or "readonly" depending on haveExplicitArgs.
- if err := modload.WriteGoMod(moduleLoaderState, ctx, modload.WriteOpts{}); err != nil {
+ if err := modload.WriteGoMod(moduleLoader, ctx, modload.WriteOpts{}); err != nil {
base.Fatal(err)
}
}
@@ -264,7 +264,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
sem <- token{}
go func() {
- err := DownloadModule(ctx, moduleLoaderState.Fetcher(), m)
+ err := DownloadModule(ctx, moduleLoader.Fetcher(), m)
if err != nil {
downloadErrs.Store(m, err)
m.Error = err.Error()
@@ -292,8 +292,8 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// with no arguments we download the module pattern "all",
// which may include dependencies that are normally pruned out
// of the individual modules in the workspace.
- if haveExplicitArgs || modload.WorkFilePath(moduleLoaderState) != "" {
- sw := toolchain.NewSwitcher(moduleLoaderState)
+ if haveExplicitArgs || modload.WorkFilePath(moduleLoader) != "" {
+ sw := toolchain.NewSwitcher(moduleLoader)
// Add errors to the Switcher in deterministic order so that they will be
// logged deterministically.
for _, m := range mods {
@@ -348,8 +348,8 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
//
// Don't save sums for 'go mod download' without arguments unless we're in
// workspace mode; see comment above.
- if haveExplicitArgs || modload.WorkFilePath(moduleLoaderState) != "" {
- if err := modload.WriteGoMod(moduleLoaderState, ctx, modload.WriteOpts{}); err != nil {
+ if haveExplicitArgs || modload.WorkFilePath(moduleLoader) != "" {
+ if err := modload.WriteGoMod(moduleLoader, ctx, modload.WriteOpts{}); err != nil {
base.Error(err)
}
}
diff --git a/src/cmd/go/internal/modcmd/edit.go b/src/cmd/go/internal/modcmd/edit.go
index 26d3640991..c25c04b59d 100644
--- a/src/cmd/go/internal/modcmd/edit.go
+++ b/src/cmd/go/internal/modcmd/edit.go
@@ -209,7 +209,7 @@ func init() {
}
func runEdit(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
anyFlags := *editModule != "" ||
*editGo != "" ||
*editToolchain != "" ||
@@ -233,7 +233,7 @@ func runEdit(ctx context.Context, cmd *base.Command, args []string) {
if len(args) == 1 {
gomod = args[0]
} else {
- gomod = moduleLoaderState.ModFilePath()
+ gomod = moduleLoader.ModFilePath()
}
if *editModule != "" {
diff --git a/src/cmd/go/internal/modcmd/graph.go b/src/cmd/go/internal/modcmd/graph.go
index 94fca1ad4e..1207227ca3 100644
--- a/src/cmd/go/internal/modcmd/graph.go
+++ b/src/cmd/go/internal/modcmd/graph.go
@@ -52,24 +52,24 @@ func init() {
}
func runGraph(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
if len(args) > 0 {
base.Fatalf("go: 'go mod graph' accepts no arguments")
}
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.RootMode = modload.NeedRoot
+ moduleLoader.ForceUseModules = true
+ moduleLoader.RootMode = modload.NeedRoot
goVersion := graphGo.String()
if goVersion != "" && gover.Compare(gover.Local(), goVersion) < 0 {
- toolchain.SwitchOrFatal(moduleLoaderState, ctx, &gover.TooNewError{
+ toolchain.SwitchOrFatal(moduleLoader, ctx, &gover.TooNewError{
What: "-go flag",
GoVersion: goVersion,
})
}
- mg, err := modload.LoadModGraph(moduleLoaderState, ctx, goVersion)
+ mg, err := modload.LoadModGraph(moduleLoader, ctx, goVersion)
if err != nil {
base.Fatal(err)
}
diff --git a/src/cmd/go/internal/modcmd/init.go b/src/cmd/go/internal/modcmd/init.go
index bfef9250a2..c1ff17a66a 100644
--- a/src/cmd/go/internal/modcmd/init.go
+++ b/src/cmd/go/internal/modcmd/init.go
@@ -35,7 +35,7 @@ func init() {
}
func runInit(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if len(args) > 1 {
base.Fatalf("go: 'go mod init' accepts at most one argument")
}
@@ -44,6 +44,6 @@ func runInit(ctx context.Context, cmd *base.Command, args []string) {
modPath = args[0]
}
- moduleLoaderState.ForceUseModules = true
- modload.CreateModFile(moduleLoaderState, ctx, modPath) // does all the hard work
+ moduleLoader.ForceUseModules = true
+ modload.CreateModFile(moduleLoader, ctx, modPath) // does all the hard work
}
diff --git a/src/cmd/go/internal/modcmd/tidy.go b/src/cmd/go/internal/modcmd/tidy.go
index 42df1c0f2e..532c991861 100644
--- a/src/cmd/go/internal/modcmd/tidy.go
+++ b/src/cmd/go/internal/modcmd/tidy.go
@@ -105,7 +105,7 @@ func (f *goVersionFlag) Set(s string) error {
}
func runTidy(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if len(args) > 0 {
base.Fatalf("go: 'go mod tidy' accepts no arguments")
}
@@ -120,18 +120,18 @@ func runTidy(ctx context.Context, cmd *base.Command, args []string) {
// those packages. In order to make 'go test' reproducible for the packages
// that are in 'all' but outside of the main module, we must explicitly
// request that their test dependencies be included.
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.RootMode = modload.NeedRoot
+ moduleLoader.ForceUseModules = true
+ moduleLoader.RootMode = modload.NeedRoot
goVersion := tidyGo.String()
if goVersion != "" && gover.Compare(gover.Local(), goVersion) < 0 {
- toolchain.SwitchOrFatal(moduleLoaderState, ctx, &gover.TooNewError{
+ toolchain.SwitchOrFatal(moduleLoader, ctx, &gover.TooNewError{
What: "-go flag",
GoVersion: goVersion,
})
}
- modload.LoadPackages(moduleLoaderState, ctx, modload.PackageOpts{
+ modload.LoadPackages(moduleLoader, ctx, modload.PackageOpts{
TidyGoVersion: tidyGo.String(),
Tags: imports.AnyTags(),
Tidy: true,
@@ -142,6 +142,6 @@ func runTidy(ctx context.Context, cmd *base.Command, args []string) {
LoadTests: true,
AllowErrors: tidyE,
SilenceMissingStdImports: true,
- Switcher: toolchain.NewSwitcher(moduleLoaderState),
+ Switcher: toolchain.NewSwitcher(moduleLoader),
}, "all")
}
diff --git a/src/cmd/go/internal/modcmd/vendor.go b/src/cmd/go/internal/modcmd/vendor.go
index 8f2269d4b8..1dc7282eb1 100644
--- a/src/cmd/go/internal/modcmd/vendor.go
+++ b/src/cmd/go/internal/modcmd/vendor.go
@@ -66,20 +66,20 @@ func init() {
}
func runVendor(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
- if modload.WorkFilePath(moduleLoaderState) != "" {
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
+ if modload.WorkFilePath(moduleLoader) != "" {
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.")
}
- RunVendor(moduleLoaderState, ctx, vendorE, vendorO, args)
+ RunVendor(moduleLoader, ctx, vendorE, vendorO, args)
}
-func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, vendorO string, args []string) {
+func RunVendor(ld *modload.Loader, ctx context.Context, vendorE bool, vendorO string, args []string) {
if len(args) != 0 {
base.Fatalf("go: 'go mod vendor' accepts no arguments")
}
- loaderstate.ForceUseModules = true
- loaderstate.RootMode = modload.NeedRoot
+ ld.ForceUseModules = true
+ ld.RootMode = modload.NeedRoot
loadOpts := modload.PackageOpts{
Tags: imports.AnyTags(),
@@ -89,7 +89,7 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
AllowErrors: vendorE,
SilenceMissingStdImports: true,
}
- _, pkgs := modload.LoadPackages(loaderstate, ctx, loadOpts, "all")
+ _, pkgs := modload.LoadPackages(ld, ctx, loadOpts, "all")
var vdir string
switch {
@@ -98,7 +98,7 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
case vendorO != "":
vdir = filepath.Join(base.Cwd(), vendorO)
default:
- vdir = filepath.Join(modload.VendorDir(loaderstate))
+ vdir = filepath.Join(modload.VendorDir(ld))
}
if err := os.RemoveAll(vdir); err != nil {
base.Fatal(err)
@@ -106,8 +106,8 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
modpkgs := make(map[module.Version][]string)
for _, pkg := range pkgs {
- m := loaderstate.PackageModule(pkg)
- if m.Path == "" || loaderstate.MainModules.Contains(m.Path) {
+ m := ld.PackageModule(pkg)
+ if m.Path == "" || ld.MainModules.Contains(m.Path) {
continue
}
modpkgs[m] = append(modpkgs[m], pkg)
@@ -117,13 +117,13 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
includeAllReplacements := false
includeGoVersions := false
isExplicit := map[module.Version]bool{}
- gv := loaderstate.MainModules.GoVersion(loaderstate)
- if gover.Compare(gv, "1.14") >= 0 && (loaderstate.FindGoWork(base.Cwd()) != "" || modload.ModFile(loaderstate).Go != nil) {
+ gv := ld.MainModules.GoVersion(ld)
+ if gover.Compare(gv, "1.14") >= 0 && (ld.FindGoWork(base.Cwd()) != "" || modload.ModFile(ld).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.
- for _, m := range loaderstate.MainModules.Versions() {
- if modFile := loaderstate.MainModules.ModFile(m); modFile != nil {
+ for _, m := range ld.MainModules.Versions() {
+ if modFile := ld.MainModules.ModFile(m); modFile != nil {
for _, r := range modFile.Require {
isExplicit[r.Mod] = true
}
@@ -157,20 +157,20 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
w = io.MultiWriter(&buf, os.Stderr)
}
- if loaderstate.MainModules.WorkFile() != nil {
+ if ld.MainModules.WorkFile() != nil {
fmt.Fprintf(w, "## workspace\n")
}
replacementWritten := make(map[module.Version]bool)
for _, m := range vendorMods {
- replacement := modload.Replacement(loaderstate, m)
+ replacement := modload.Replacement(ld, m)
line := moduleLine(m, replacement)
replacementWritten[m] = true
io.WriteString(w, line)
goVersion := ""
if includeGoVersions {
- goVersion = modload.ModuleInfo(loaderstate, ctx, m.Path).GoVersion
+ goVersion = modload.ModuleInfo(ld, ctx, m.Path).GoVersion
}
switch {
case isExplicit[m] && goVersion != "":
@@ -185,7 +185,7 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
sort.Strings(pkgs)
for _, pkg := range pkgs {
fmt.Fprintf(w, "%s\n", pkg)
- vendorPkg(loaderstate, vdir, pkg)
+ vendorPkg(ld, vdir, pkg)
}
}
@@ -193,8 +193,8 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
// Record unused and wildcard replacements at the end of the modules.txt file:
// without access to the complete build list, the consumer of the vendor
// directory can't otherwise determine that those replacements had no effect.
- for _, m := range loaderstate.MainModules.Versions() {
- if workFile := loaderstate.MainModules.WorkFile(); workFile != nil {
+ for _, m := range ld.MainModules.Versions() {
+ if workFile := ld.MainModules.WorkFile(); workFile != nil {
for _, r := range workFile.Replace {
if replacementWritten[r.Old] {
// We already recorded this replacement.
@@ -209,14 +209,14 @@ func RunVendor(loaderstate *modload.State, ctx context.Context, vendorE bool, ve
}
}
}
- if modFile := loaderstate.MainModules.ModFile(m); modFile != nil {
+ if modFile := ld.MainModules.ModFile(m); modFile != nil {
for _, r := range modFile.Replace {
if replacementWritten[r.Old] {
// We already recorded this replacement.
continue
}
replacementWritten[r.Old] = true
- rNew := modload.Replacement(loaderstate, r.Old)
+ rNew := modload.Replacement(ld, r.Old)
if rNew == (module.Version{}) {
// There is no replacement. Don't try to write it.
continue
@@ -269,7 +269,7 @@ func moduleLine(m, r module.Version) string {
return b.String()
}
-func vendorPkg(s *modload.State, vdir, pkg string) {
+func vendorPkg(s *modload.Loader, vdir, pkg string) {
src, realPath, _ := modload.Lookup(s, "", false, pkg)
if src == "" {
base.Errorf("internal error: no pkg for %s\n", pkg)
diff --git a/src/cmd/go/internal/modcmd/verify.go b/src/cmd/go/internal/modcmd/verify.go
index 5af5d93f77..a4f7642791 100644
--- a/src/cmd/go/internal/modcmd/verify.go
+++ b/src/cmd/go/internal/modcmd/verify.go
@@ -44,21 +44,21 @@ func init() {
}
func runVerify(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
if len(args) != 0 {
// NOTE(rsc): Could take a module pattern.
base.Fatalf("go: verify takes no arguments")
}
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.RootMode = modload.NeedRoot
+ moduleLoader.ForceUseModules = true
+ moduleLoader.RootMode = modload.NeedRoot
// Only verify up to GOMAXPROCS zips at once.
type token struct{}
sem := make(chan token, runtime.GOMAXPROCS(0))
- mg, err := modload.LoadModGraph(moduleLoaderState, ctx, "")
+ mg, err := modload.LoadModGraph(moduleLoader, ctx, "")
if err != nil {
base.Fatal(err)
}
@@ -72,7 +72,7 @@ func runVerify(ctx context.Context, cmd *base.Command, args []string) {
errsChans[i] = errsc
mod := mod // use a copy to avoid data races
go func() {
- errsc <- verifyMod(moduleLoaderState, ctx, mod)
+ errsc <- verifyMod(moduleLoader, ctx, mod)
<-sem
}()
}
@@ -90,12 +90,12 @@ func runVerify(ctx context.Context, cmd *base.Command, args []string) {
}
}
-func verifyMod(loaderstate *modload.State, ctx context.Context, mod module.Version) []error {
+func verifyMod(ld *modload.Loader, ctx context.Context, mod module.Version) []error {
if gover.IsToolchain(mod.Path) {
// "go" and "toolchain" have no disk footprint; nothing to verify.
return nil
}
- if loaderstate.MainModules.Contains(mod.Path) {
+ if ld.MainModules.Contains(mod.Path) {
return nil
}
var errs []error
diff --git a/src/cmd/go/internal/modcmd/why.go b/src/cmd/go/internal/modcmd/why.go
index 93a2d607ce..8a33f5c54d 100644
--- a/src/cmd/go/internal/modcmd/why.go
+++ b/src/cmd/go/internal/modcmd/why.go
@@ -63,10 +63,10 @@ func init() {
}
func runWhy(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.RootMode = modload.NeedRoot
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
+ moduleLoader.ForceUseModules = true
+ moduleLoader.RootMode = modload.NeedRoot
modload.ExplicitWriteGoMod = true // don't write go.mod in ListModules
loadOpts := modload.PackageOpts{
@@ -84,15 +84,15 @@ func runWhy(ctx context.Context, cmd *base.Command, args []string) {
}
}
- mods, err := modload.ListModules(moduleLoaderState, ctx, args, 0, "")
+ mods, err := modload.ListModules(moduleLoader, ctx, args, 0, "")
if err != nil {
base.Fatal(err)
}
byModule := make(map[string][]string)
- _, pkgs := modload.LoadPackages(moduleLoaderState, ctx, loadOpts, "all")
+ _, pkgs := modload.LoadPackages(moduleLoader, ctx, loadOpts, "all")
for _, path := range pkgs {
- m := moduleLoaderState.PackageModule(path)
+ m := moduleLoader.PackageModule(path)
if m.Path != "" {
byModule[m.Path] = append(byModule[m.Path], path)
}
@@ -102,13 +102,13 @@ func runWhy(ctx context.Context, cmd *base.Command, args []string) {
best := ""
bestDepth := 1000000000
for _, path := range byModule[m.Path] {
- d := moduleLoaderState.WhyDepth(path)
+ d := moduleLoader.WhyDepth(path)
if d > 0 && d < bestDepth {
best = path
bestDepth = d
}
}
- why := moduleLoaderState.Why(best)
+ why := moduleLoader.Why(best)
if why == "" {
vendoring := ""
if *whyVendor {
@@ -121,14 +121,14 @@ func runWhy(ctx context.Context, cmd *base.Command, args []string) {
}
} else {
// Resolve to packages.
- matches, _ := modload.LoadPackages(moduleLoaderState, ctx, loadOpts, args...)
+ matches, _ := modload.LoadPackages(moduleLoader, ctx, loadOpts, args...)
- modload.LoadPackages(moduleLoaderState, ctx, loadOpts, "all") // rebuild graph, from main module (not from named packages)
+ modload.LoadPackages(moduleLoader, ctx, loadOpts, "all") // rebuild graph, from main module (not from named packages)
sep := ""
for _, m := range matches {
for _, path := range m.Pkgs {
- why := moduleLoaderState.Why(path)
+ why := moduleLoader.Why(path)
if why == "" {
vendoring := ""
if *whyVendor {
diff --git a/src/cmd/go/internal/modget/get.go b/src/cmd/go/internal/modget/get.go
index 165d88a6b5..089ce6a2bd 100644
--- a/src/cmd/go/internal/modget/get.go
+++ b/src/cmd/go/internal/modget/get.go
@@ -274,7 +274,7 @@ func init() {
}
func runGet(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
switch getU.version {
case "", "upgrade", "patch":
// ok
@@ -300,7 +300,7 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
base.Fatalf("go: -insecure flag is no longer supported; use GOINSECURE instead")
}
- moduleLoaderState.ForceUseModules = true
+ moduleLoader.ForceUseModules = true
// Do not allow any updating of go.mod until we've applied
// all the requested changes and checked that the result matches
@@ -309,14 +309,14 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
// Allow looking up modules for import paths when outside of a module.
// 'go get' is expected to do this, unlike other commands.
- moduleLoaderState.AllowMissingModuleImports()
+ moduleLoader.AllowMissingModuleImports()
// 'go get' no longer builds or installs packages, so there's nothing to do
// if there's no go.mod file.
// TODO(#40775): make modload.Init return ErrNoModRoot instead of exiting.
// We could handle that here by printing a different message.
- modload.Init(moduleLoaderState)
- if !moduleLoaderState.HasModRoot() {
+ modload.Init(moduleLoader)
+ if !moduleLoader.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" +
@@ -325,7 +325,7 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
"\tor run 'go help get' or 'go help install'.")
}
- dropToolchain, queries := parseArgs(moduleLoaderState, ctx, args)
+ dropToolchain, queries := parseArgs(moduleLoader, ctx, args)
opts := modload.WriteOpts{
DropToolchain: dropToolchain,
}
@@ -335,17 +335,17 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
}
}
- r := newResolver(moduleLoaderState, ctx, queries)
- r.performLocalQueries(moduleLoaderState, ctx)
- r.performPathQueries(moduleLoaderState, ctx)
- r.performToolQueries(moduleLoaderState, ctx)
- r.performWorkQueries(moduleLoaderState, ctx)
+ r := newResolver(moduleLoader, ctx, queries)
+ r.performLocalQueries(moduleLoader, ctx)
+ r.performPathQueries(moduleLoader, ctx)
+ r.performToolQueries(moduleLoader, ctx)
+ r.performWorkQueries(moduleLoader, ctx)
for {
- r.performWildcardQueries(moduleLoaderState, ctx)
- r.performPatternAllQueries(moduleLoaderState, ctx)
+ r.performWildcardQueries(moduleLoader, ctx)
+ r.performPatternAllQueries(moduleLoader, ctx)
- if changed := r.resolveQueries(moduleLoaderState, ctx, queries); changed {
+ if changed := r.resolveQueries(moduleLoader, ctx, queries); changed {
// 'go get' arguments can be (and often are) package patterns rather than
// (just) modules. A package can be provided by any module with a prefix
// of its import path, and a wildcard can even match packages in modules
@@ -381,20 +381,20 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
//
// - ambiguous import errors.
// TODO(#27899): Try to resolve ambiguous import errors automatically.
- upgrades := r.findAndUpgradeImports(moduleLoaderState, ctx, queries)
- if changed := r.applyUpgrades(moduleLoaderState, ctx, upgrades); changed {
+ upgrades := r.findAndUpgradeImports(moduleLoader, ctx, queries)
+ if changed := r.applyUpgrades(moduleLoader, ctx, upgrades); changed {
continue
}
- r.findMissingWildcards(moduleLoaderState, ctx)
- if changed := r.resolveQueries(moduleLoaderState, ctx, r.wildcardQueries); changed {
+ r.findMissingWildcards(moduleLoader, ctx)
+ if changed := r.resolveQueries(moduleLoader, ctx, r.wildcardQueries); changed {
continue
}
break
}
- r.checkWildcardVersions(moduleLoaderState, ctx)
+ r.checkWildcardVersions(moduleLoader, ctx)
var pkgPatterns []string
for _, q := range queries {
@@ -404,37 +404,37 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
}
if *getTool {
- updateTools(moduleLoaderState, ctx, r, queries, &opts)
+ updateTools(moduleLoader, ctx, r, queries, &opts)
}
// If a workspace applies, checkPackageProblems will switch to the workspace
// using modload.EnterWorkspace when doing the final load, and then switch back.
- r.checkPackageProblems(moduleLoaderState, ctx, pkgPatterns)
+ r.checkPackageProblems(moduleLoader, ctx, pkgPatterns)
// Everything succeeded. Update go.mod.
- oldReqs := reqsFromGoMod(modload.ModFile(moduleLoaderState))
+ oldReqs := reqsFromGoMod(modload.ModFile(moduleLoader))
- if err := modload.WriteGoMod(moduleLoaderState, ctx, opts); err != nil {
+ if err := modload.WriteGoMod(moduleLoader, ctx, opts); err != nil {
// A TooNewError can happen for 'go get go@newversion'
// when all the required modules are old enough
// but the command line is not.
// TODO(bcmills): modload.EditBuildList should catch this instead,
// and then this can be changed to base.Fatal(err).
- toolchain.SwitchOrFatal(moduleLoaderState, ctx, err)
+ toolchain.SwitchOrFatal(moduleLoader, ctx, err)
}
- newReqs := reqsFromGoMod(modload.ModFile(moduleLoaderState))
+ newReqs := reqsFromGoMod(modload.ModFile(moduleLoader))
r.reportChanges(oldReqs, newReqs)
- if gowork := moduleLoaderState.FindGoWork(base.Cwd()); gowork != "" {
+ if gowork := moduleLoader.FindGoWork(base.Cwd()); gowork != "" {
wf, err := modload.ReadWorkFile(gowork)
- if err == nil && modload.UpdateWorkGoVersion(wf, moduleLoaderState.MainModules.GoVersion(moduleLoaderState)) {
+ if err == nil && modload.UpdateWorkGoVersion(wf, moduleLoader.MainModules.GoVersion(moduleLoader)) {
modload.WriteWorkFile(gowork, wf)
}
}
}
-func updateTools(loaderstate *modload.State, ctx context.Context, r *resolver, queries []*query, opts *modload.WriteOpts) {
+func updateTools(ld *modload.Loader, ctx context.Context, r *resolver, queries []*query, opts *modload.WriteOpts) {
pkgOpts := modload.PackageOpts{
VendorModulesInGOROOTSrc: true,
LoadTests: *getT,
@@ -450,7 +450,7 @@ func updateTools(loaderstate *modload.State, ctx context.Context, r *resolver, q
patterns = append(patterns, q.pattern)
}
- matches, _ := modload.LoadPackages(loaderstate, ctx, pkgOpts, patterns...)
+ matches, _ := modload.LoadPackages(ld, ctx, pkgOpts, patterns...)
for i, m := range matches {
if queries[i].version == "none" {
opts.DropTools = append(opts.DropTools, m.Pkgs...)
@@ -459,9 +459,9 @@ func updateTools(loaderstate *modload.State, ctx context.Context, r *resolver, q
}
}
- mg, err := modload.LoadModGraph(loaderstate, ctx, "")
+ mg, err := modload.LoadModGraph(ld, ctx, "")
if err != nil {
- toolchain.SwitchOrFatal(loaderstate, ctx, err)
+ toolchain.SwitchOrFatal(ld, ctx, err)
}
r.buildList = mg.BuildList()
r.buildListVersion = make(map[string]string, len(r.buildList))
@@ -474,11 +474,11 @@ func updateTools(loaderstate *modload.State, ctx context.Context, r *resolver, q
//
// The command-line arguments are of the form path@version or simply path, with
// implicit @upgrade. path@none is "downgrade away".
-func parseArgs(loaderstate *modload.State, ctx context.Context, rawArgs []string) (dropToolchain bool, queries []*query) {
+func parseArgs(ld *modload.Loader, ctx context.Context, rawArgs []string) (dropToolchain bool, queries []*query) {
defer base.ExitIfErrors()
for _, arg := range search.CleanPatterns(rawArgs) {
- q, err := newQuery(loaderstate, arg)
+ q, err := newQuery(ld, arg)
if err != nil {
base.Error(err)
continue
@@ -565,12 +565,12 @@ type matchInModuleKey struct {
m module.Version
}
-func newResolver(loaderstate *modload.State, ctx context.Context, queries []*query) *resolver {
+func newResolver(ld *modload.Loader, ctx context.Context, queries []*query) *resolver {
// LoadModGraph also sets modload.Target, which is needed by various resolver
// methods.
- mg, err := modload.LoadModGraph(loaderstate, ctx, "")
+ mg, err := modload.LoadModGraph(ld, ctx, "")
if err != nil {
- toolchain.SwitchOrFatal(loaderstate, ctx, err)
+ toolchain.SwitchOrFatal(ld, ctx, err)
}
buildList := mg.BuildList()
@@ -586,7 +586,7 @@ func newResolver(loaderstate *modload.State, ctx context.Context, queries []*que
buildListVersion: initialVersion,
initialVersion: initialVersion,
nonesByPath: map[string]*query{},
- workspace: loadWorkspace(loaderstate.FindGoWork(base.Cwd())),
+ workspace: loadWorkspace(ld.FindGoWork(base.Cwd())),
}
for _, q := range queries {
@@ -655,9 +655,9 @@ func (r *resolver) noneForPath(mPath string) (nq *query, found bool) {
// queryModule wraps modload.Query, substituting r.checkAllowedOr to decide
// allowed versions.
-func (r *resolver) queryModule(loaderstate *modload.State, ctx context.Context, mPath, query string, selected func(string) string) (module.Version, error) {
+func (r *resolver) queryModule(ld *modload.Loader, ctx context.Context, mPath, query string, selected func(string) string) (module.Version, error) {
current := r.initialSelected(mPath)
- rev, err := modload.Query(loaderstate, ctx, mPath, query, current, r.checkAllowedOr(loaderstate, query, selected))
+ rev, err := modload.Query(ld, ctx, mPath, query, current, r.checkAllowedOr(ld, query, selected))
if err != nil {
return module.Version{}, err
}
@@ -666,8 +666,8 @@ func (r *resolver) queryModule(loaderstate *modload.State, ctx context.Context,
// queryPackages wraps modload.QueryPackage, substituting r.checkAllowedOr to
// decide allowed versions.
-func (r *resolver) queryPackages(loaderstate *modload.State, ctx context.Context, pattern, query string, selected func(string) string) (pkgMods []module.Version, err error) {
- results, err := modload.QueryPackages(loaderstate, ctx, pattern, query, selected, r.checkAllowedOr(loaderstate, query, selected))
+func (r *resolver) queryPackages(ld *modload.Loader, ctx context.Context, pattern, query string, selected func(string) string) (pkgMods []module.Version, err error) {
+ results, err := modload.QueryPackages(ld, ctx, pattern, query, selected, r.checkAllowedOr(ld, query, selected))
if len(results) > 0 {
pkgMods = make([]module.Version, 0, len(results))
for _, qr := range results {
@@ -679,8 +679,8 @@ func (r *resolver) queryPackages(loaderstate *modload.State, ctx context.Context
// queryPattern wraps modload.QueryPattern, substituting r.checkAllowedOr to
// decide allowed versions.
-func (r *resolver) queryPattern(loaderstate *modload.State, ctx context.Context, pattern, query string, selected func(string) string) (pkgMods []module.Version, mod module.Version, err error) {
- results, modOnly, err := modload.QueryPattern(loaderstate, ctx, pattern, query, selected, r.checkAllowedOr(loaderstate, query, selected))
+func (r *resolver) queryPattern(ld *modload.Loader, ctx context.Context, pattern, query string, selected func(string) string) (pkgMods []module.Version, mod module.Version, err error) {
+ results, modOnly, err := modload.QueryPattern(ld, ctx, pattern, query, selected, r.checkAllowedOr(ld, query, selected))
if len(results) > 0 {
pkgMods = make([]module.Version, 0, len(results))
for _, qr := range results {
@@ -695,7 +695,7 @@ func (r *resolver) queryPattern(loaderstate *modload.State, ctx context.Context,
// checkAllowedOr is like modload.CheckAllowed, but it always allows the requested
// and current versions (even if they are retracted or otherwise excluded).
-func (r *resolver) checkAllowedOr(s *modload.State, requested string, selected func(string) string) modload.AllowedFunc {
+func (r *resolver) checkAllowedOr(s *modload.Loader, requested string, selected func(string) string) modload.AllowedFunc {
return func(ctx context.Context, m module.Version) error {
if m.Version == requested {
return s.CheckExclusions(ctx, m)
@@ -708,9 +708,9 @@ func (r *resolver) checkAllowedOr(s *modload.State, requested string, selected f
}
// matchInModule is a caching wrapper around modload.MatchInModule.
-func (r *resolver) matchInModule(loaderstate *modload.State, ctx context.Context, pattern string, m module.Version) (packages []string, err error) {
+func (r *resolver) matchInModule(ld *modload.Loader, ctx context.Context, pattern string, m module.Version) (packages []string, err error) {
return r.matchInModuleCache.Do(matchInModuleKey{pattern, m}, func() ([]string, error) {
- match := modload.MatchInModule(loaderstate, ctx, pattern, m, imports.AnyTags())
+ match := modload.MatchInModule(ld, ctx, pattern, m, imports.AnyTags())
if len(match.Errs) > 0 {
return match.Pkgs, match.Errs[0]
}
@@ -726,15 +726,15 @@ func (r *resolver) matchInModule(loaderstate *modload.State, ctx context.Context
// modules second. However, no module exists at version "none", and therefore no
// package exists at that version either: we know that the argument cannot match
// any packages, and thus it must match modules instead.
-func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q *query) {
+func (r *resolver) queryNone(ld *modload.Loader, ctx context.Context, q *query) {
if search.IsMetaPackage(q.pattern) {
panic(fmt.Sprintf("internal error: queryNone called with pattern %q", q.pattern))
}
if !q.isWildcard() {
q.pathOnce(q.pattern, func() pathSet {
- hasModRoot := loaderstate.HasModRoot()
- if hasModRoot && loaderstate.MainModules.Contains(q.pattern) {
+ hasModRoot := ld.HasModRoot()
+ if hasModRoot && ld.MainModules.Contains(q.pattern) {
v := module.Version{Path: q.pattern}
// The user has explicitly requested to downgrade their own module to
// version "none". This is not an entirely unreasonable request: it
@@ -750,7 +750,7 @@ func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q
MainModules: []module.Version{v},
Pattern: q.pattern,
Query: q.version,
- PatternIsModule: loaderstate.MainModules.Contains(q.pattern),
+ PatternIsModule: ld.MainModules.Contains(q.pattern),
})
}
@@ -763,12 +763,12 @@ func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q
continue
}
q.pathOnce(curM.Path, func() pathSet {
- if loaderstate.HasModRoot() && curM.Version == "" && loaderstate.MainModules.Contains(curM.Path) {
+ if ld.HasModRoot() && curM.Version == "" && ld.MainModules.Contains(curM.Path) {
return errSet(&modload.QueryMatchesMainModulesError{
MainModules: []module.Version{curM},
Pattern: q.pattern,
Query: q.version,
- PatternIsModule: loaderstate.MainModules.Contains(q.pattern),
+ PatternIsModule: ld.MainModules.Contains(q.pattern),
})
}
return pathSet{mod: module.Version{Path: curM.Path, Version: "none"}}
@@ -776,7 +776,7 @@ func (r *resolver) queryNone(loaderstate *modload.State, ctx context.Context, q
}
}
-func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performLocalQueries(ld *modload.Loader, ctx context.Context) {
for _, q := range r.localQueries {
q.pathOnce(q.pattern, func() pathSet {
absDetail := ""
@@ -788,13 +788,13 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
// Absolute paths like C:\foo and relative paths like ../foo... are
// restricted to matching packages in the main module.
- pkgPattern, mainModule := loaderstate.MainModules.DirImportPath(loaderstate, ctx, q.pattern)
+ pkgPattern, mainModule := ld.MainModules.DirImportPath(ld, ctx, q.pattern)
if pkgPattern == "." {
- loaderstate.MustHaveModRoot()
- versions := loaderstate.MainModules.Versions()
+ ld.MustHaveModRoot()
+ versions := ld.MainModules.Versions()
modRoots := make([]string, 0, len(versions))
for _, m := range versions {
- modRoots = append(modRoots, loaderstate.MainModules.ModRoot(m))
+ modRoots = append(modRoots, ld.MainModules.ModRoot(m))
}
var plural string
if len(modRoots) != 1 {
@@ -803,7 +803,7 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
return errSet(fmt.Errorf("%s%s is not within module%s rooted at %s", q.pattern, absDetail, plural, strings.Join(modRoots, ", ")))
}
- match := modload.MatchInModule(loaderstate, ctx, pkgPattern, mainModule, imports.AnyTags())
+ match := modload.MatchInModule(ld, ctx, pkgPattern, mainModule, imports.AnyTags())
if len(match.Errs) > 0 {
return pathSet{err: match.Errs[0]}
}
@@ -813,8 +813,8 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
return errSet(fmt.Errorf("no package to get in current directory"))
}
if !q.isWildcard() {
- loaderstate.MustHaveModRoot()
- return errSet(fmt.Errorf("%s%s is not a package in module rooted at %s", q.pattern, absDetail, loaderstate.MainModules.ModRoot(mainModule)))
+ ld.MustHaveModRoot()
+ return errSet(fmt.Errorf("%s%s is not a package in module rooted at %s", q.pattern, absDetail, ld.MainModules.ModRoot(mainModule)))
}
search.WarnUnmatched([]*search.Match{match})
return pathSet{}
@@ -833,14 +833,14 @@ func (r *resolver) performLocalQueries(loaderstate *modload.State, ctx context.C
// of modules may be expanded by other queries, so wildcard queries need to be
// re-evaluated whenever a potentially-matching module path is added to the
// build list.
-func (r *resolver) performWildcardQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performWildcardQueries(ld *modload.Loader, ctx context.Context) {
for _, q := range r.wildcardQueries {
q := q
r.work.Add(func() {
if q.version == "none" {
- r.queryNone(loaderstate, ctx, q)
+ r.queryNone(ld, ctx, q)
} else {
- r.queryWildcard(loaderstate, ctx, q)
+ r.queryWildcard(ld, ctx, q)
}
})
}
@@ -852,7 +852,7 @@ func (r *resolver) performWildcardQueries(loaderstate *modload.State, ctx contex
// - that module exists at some version matching q.version, and
// - either the module path itself matches q.pattern, or some package within
// the module at q.version matches q.pattern.
-func (r *resolver) queryWildcard(loaderstate *modload.State, ctx context.Context, q *query) {
+func (r *resolver) queryWildcard(ld *modload.Loader, ctx context.Context, q *query) {
// For wildcard patterns, modload.QueryPattern only identifies modules
// matching the prefix of the path before the wildcard. However, the build
// list may already contain other modules with matching packages, and we
@@ -870,17 +870,17 @@ func (r *resolver) queryWildcard(loaderstate *modload.State, ctx context.Context
return pathSet{}
}
- if loaderstate.MainModules.Contains(curM.Path) && !versionOkForMainModule(q.version) {
+ if ld.MainModules.Contains(curM.Path) && !versionOkForMainModule(q.version) {
if q.matchesPath(curM.Path) {
return errSet(&modload.QueryMatchesMainModulesError{
MainModules: []module.Version{curM},
Pattern: q.pattern,
Query: q.version,
- PatternIsModule: loaderstate.MainModules.Contains(q.pattern),
+ PatternIsModule: ld.MainModules.Contains(q.pattern),
})
}
- packages, err := r.matchInModule(loaderstate, ctx, q.pattern, curM)
+ packages, err := r.matchInModule(ld, ctx, q.pattern, curM)
if err != nil {
return errSet(err)
}
@@ -892,10 +892,10 @@ func (r *resolver) queryWildcard(loaderstate *modload.State, ctx context.Context
})
}
- return r.tryWildcard(loaderstate, ctx, q, curM)
+ return r.tryWildcard(ld, ctx, q, curM)
}
- m, err := r.queryModule(loaderstate, ctx, curM.Path, q.version, r.initialSelected)
+ m, err := r.queryModule(ld, ctx, curM.Path, q.version, r.initialSelected)
if err != nil {
if !isNoSuchModuleVersion(err) {
// We can't tell whether a matching version exists.
@@ -917,7 +917,7 @@ func (r *resolver) queryWildcard(loaderstate *modload.State, ctx context.Context
return pathSet{}
}
- return r.tryWildcard(loaderstate, ctx, q, m)
+ return r.tryWildcard(ld, ctx, q, m)
})
}
@@ -928,9 +928,9 @@ func (r *resolver) queryWildcard(loaderstate *modload.State, ctx context.Context
// tryWildcard returns a pathSet for module m matching query q.
// If m does not actually match q, tryWildcard returns an empty pathSet.
-func (r *resolver) tryWildcard(loaderstate *modload.State, ctx context.Context, q *query, m module.Version) pathSet {
+func (r *resolver) tryWildcard(ld *modload.Loader, ctx context.Context, q *query, m module.Version) pathSet {
mMatches := q.matchesPath(m.Path)
- packages, err := r.matchInModule(loaderstate, ctx, q.pattern, m)
+ packages, err := r.matchInModule(ld, ctx, q.pattern, m)
if err != nil {
return errSet(err)
}
@@ -945,14 +945,14 @@ func (r *resolver) tryWildcard(loaderstate *modload.State, ctx context.Context,
// findMissingWildcards adds a candidate set for each query in r.wildcardQueries
// that has not yet resolved to any version containing packages.
-func (r *resolver) findMissingWildcards(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) findMissingWildcards(ld *modload.Loader, ctx context.Context) {
for _, q := range r.wildcardQueries {
if q.version == "none" || q.matchesPackages {
continue // q is not “missing”
}
r.work.Add(func() {
q.pathOnce(q.pattern, func() pathSet {
- pkgMods, mod, err := r.queryPattern(loaderstate, ctx, q.pattern, q.version, r.initialSelected)
+ pkgMods, mod, err := r.queryPattern(ld, ctx, q.pattern, q.version, r.initialSelected)
if err != nil {
if isNoSuchPackageVersion(err) && len(q.resolved) > 0 {
// q already resolved one or more modules but matches no packages.
@@ -973,7 +973,7 @@ func (r *resolver) findMissingWildcards(loaderstate *modload.State, ctx context.
// checkWildcardVersions reports an error if any module in the build list has a
// path (or contains a package) matching a query with a wildcard pattern, but
// has a selected version that does *not* match the query.
-func (r *resolver) checkWildcardVersions(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) checkWildcardVersions(ld *modload.Loader, ctx context.Context) {
defer base.ExitIfErrors()
for _, q := range r.wildcardQueries {
@@ -982,7 +982,7 @@ func (r *resolver) checkWildcardVersions(loaderstate *modload.State, ctx context
continue
}
if !q.matchesPath(curM.Path) {
- packages, err := r.matchInModule(loaderstate, ctx, q.pattern, curM)
+ packages, err := r.matchInModule(ld, ctx, q.pattern, curM)
if len(packages) == 0 {
if err != nil {
reportError(q, err)
@@ -991,7 +991,7 @@ func (r *resolver) checkWildcardVersions(loaderstate *modload.State, ctx context
}
}
- rev, err := r.queryModule(loaderstate, ctx, curM.Path, q.version, r.initialSelected)
+ rev, err := r.queryModule(ld, ctx, curM.Path, q.version, r.initialSelected)
if err != nil {
reportError(q, err)
continue
@@ -1002,7 +1002,7 @@ func (r *resolver) checkWildcardVersions(loaderstate *modload.State, ctx context
if !q.matchesPath(curM.Path) {
m := module.Version{Path: curM.Path, Version: rev.Version}
- packages, err := r.matchInModule(loaderstate, ctx, q.pattern, m)
+ packages, err := r.matchInModule(ld, ctx, q.pattern, m)
if err != nil {
reportError(q, err)
continue
@@ -1036,14 +1036,14 @@ func (r *resolver) checkWildcardVersions(loaderstate *modload.State, ctx context
// The candidate packages and modules for path literals depend only on the
// initial build list, not the current build list, so we only need to query path
// literals once.
-func (r *resolver) performPathQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performPathQueries(ld *modload.Loader, ctx context.Context) {
for _, q := range r.pathQueries {
q := q
r.work.Add(func() {
if q.version == "none" {
- r.queryNone(loaderstate, ctx, q)
+ r.queryNone(ld, ctx, q)
} else {
- r.queryPath(loaderstate, ctx, q)
+ r.queryPath(ld, ctx, q)
}
})
}
@@ -1054,7 +1054,7 @@ func (r *resolver) performPathQueries(loaderstate *modload.State, ctx context.Co
// The candidate set consists of all modules that could provide q.pattern
// and have a version matching q, plus (if it exists) the module whose path
// is itself q.pattern (at a matching version).
-func (r *resolver) queryPath(loaderstate *modload.State, ctx context.Context, q *query) {
+func (r *resolver) queryPath(ld *modload.Loader, ctx context.Context, q *query) {
q.pathOnce(q.pattern, func() pathSet {
if search.IsMetaPackage(q.pattern) || q.isWildcard() {
panic(fmt.Sprintf("internal error: queryPath called with pattern %q", q.pattern))
@@ -1065,7 +1065,7 @@ func (r *resolver) queryPath(loaderstate *modload.State, ctx context.Context, q
if search.IsStandardImportPath(q.pattern) {
stdOnly := module.Version{}
- packages, _ := r.matchInModule(loaderstate, ctx, q.pattern, stdOnly)
+ packages, _ := r.matchInModule(ld, ctx, q.pattern, stdOnly)
if len(packages) > 0 {
if q.rawVersion != "" {
return errSet(fmt.Errorf("can't request explicit version %q of standard library package %s", q.version, q.pattern))
@@ -1076,7 +1076,7 @@ func (r *resolver) queryPath(loaderstate *modload.State, ctx context.Context, q
}
}
- pkgMods, mod, err := r.queryPattern(loaderstate, ctx, q.pattern, q.version, r.initialSelected)
+ pkgMods, mod, err := r.queryPattern(ld, ctx, q.pattern, q.version, r.initialSelected)
if err != nil {
return errSet(err)
}
@@ -1086,11 +1086,11 @@ func (r *resolver) queryPath(loaderstate *modload.State, ctx context.Context, q
// performToolQueries populates the candidates for each query whose
// pattern is "tool".
-func (r *resolver) performToolQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performToolQueries(ld *modload.Loader, ctx context.Context) {
for _, q := range r.toolQueries {
- for tool := range loaderstate.MainModules.Tools() {
+ for tool := range ld.MainModules.Tools() {
q.pathOnce(tool, func() pathSet {
- pkgMods, err := r.queryPackages(loaderstate, ctx, tool, q.version, r.initialSelected)
+ pkgMods, err := r.queryPackages(ld, ctx, tool, q.version, r.initialSelected)
return pathSet{pkgMods: pkgMods, err: err}
})
}
@@ -1099,22 +1099,22 @@ func (r *resolver) performToolQueries(loaderstate *modload.State, ctx context.Co
// performWorkQueries populates the candidates for each query whose pattern is "work".
// The candidate module to resolve the work pattern is exactly the single main module.
-func (r *resolver) performWorkQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performWorkQueries(ld *modload.Loader, ctx context.Context) {
for _, q := range r.workQueries {
q.pathOnce(q.pattern, func() pathSet {
// TODO(matloob): Maybe export MainModules.mustGetSingleMainModule and call that.
// There are a few other places outside the modload package where we expect
// a single main module.
- if len(loaderstate.MainModules.Versions()) != 1 {
+ if len(ld.MainModules.Versions()) != 1 {
panic("internal error: number of main modules is not exactly one in resolution phase of go get")
}
- mainModule := loaderstate.MainModules.Versions()[0]
+ mainModule := ld.MainModules.Versions()[0]
// We know what the result is going to be, assuming the main module is not
// empty, (it's the main module itself) but first check to see that there
// are packages in the main module, so that if there aren't any, we can
// return the expected warning that the pattern matched no packages.
- match := modload.MatchInModule(loaderstate, ctx, q.pattern, mainModule, imports.AnyTags())
+ match := modload.MatchInModule(ld, ctx, q.pattern, mainModule, imports.AnyTags())
if len(match.Errs) > 0 {
return pathSet{err: match.Errs[0]}
}
@@ -1136,7 +1136,7 @@ func (r *resolver) performWorkQueries(loaderstate *modload.State, ctx context.Co
// know which candidate is selected — and that selection may depend on the
// results of other queries. We need to re-evaluate the "all" queries whenever
// the module for one or more packages in "all" are resolved.
-func (r *resolver) performPatternAllQueries(loaderstate *modload.State, ctx context.Context) {
+func (r *resolver) performPatternAllQueries(ld *modload.Loader, ctx context.Context) {
if len(r.patternAllQueries) == 0 {
return
}
@@ -1145,7 +1145,7 @@ func (r *resolver) performPatternAllQueries(loaderstate *modload.State, ctx cont
versionOk = true
for _, q := range r.patternAllQueries {
q.pathOnce(path, func() pathSet {
- pkgMods, err := r.queryPackages(loaderstate, ctx, path, q.version, r.initialSelected)
+ pkgMods, err := r.queryPackages(ld, ctx, path, q.version, r.initialSelected)
if len(pkgMods) != 1 || pkgMods[0] != m {
// There are candidates other than m for the given path, so we can't
// be certain that m will actually be the module selected to provide
@@ -1160,7 +1160,7 @@ func (r *resolver) performPatternAllQueries(loaderstate *modload.State, ctx cont
return versionOk
}
- r.loadPackages(loaderstate, ctx, []string{"all"}, findPackage)
+ r.loadPackages(ld, ctx, []string{"all"}, findPackage)
// Since we built up the candidate lists concurrently, they may be in a
// nondeterministic order. We want 'go get' to be fully deterministic,
@@ -1180,7 +1180,7 @@ func (r *resolver) performPatternAllQueries(loaderstate *modload.State, ctx cont
// If the getU flag ("-u") is set, findAndUpgradeImports also returns a
// pathSet for each module that is not constrained by any other
// command-line argument and has an available matching upgrade.
-func (r *resolver) findAndUpgradeImports(loaderstate *modload.State, ctx context.Context, queries []*query) (upgrades []pathSet) {
+func (r *resolver) findAndUpgradeImports(ld *modload.Loader, ctx context.Context, queries []*query) (upgrades []pathSet) {
patterns := make([]string, 0, len(queries))
for _, q := range queries {
if q.matchesPackages {
@@ -1221,7 +1221,7 @@ func (r *resolver) findAndUpgradeImports(loaderstate *modload.State, ctx context
// - The "-u" flag, unlike other arguments, does not cause version
// conflicts with other queries. (The other query always wins.)
- pkgMods, err := r.queryPackages(loaderstate, ctx, path, version, r.selected)
+ pkgMods, err := r.queryPackages(ld, ctx, path, version, r.selected)
for _, u := range pkgMods {
if u == m {
// The selected package version is already upgraded appropriately; there
@@ -1252,7 +1252,7 @@ func (r *resolver) findAndUpgradeImports(loaderstate *modload.State, ctx context
return false
}
- r.loadPackages(loaderstate, ctx, patterns, findPackage)
+ r.loadPackages(ld, ctx, patterns, findPackage)
// Since we built up the candidate lists concurrently, they may be in a
// nondeterministic order. We want 'go get' to be fully deterministic,
@@ -1276,14 +1276,14 @@ func (r *resolver) findAndUpgradeImports(loaderstate *modload.State, ctx context
// loadPackages also invokes the findPackage function for each imported package
// that is neither present in the standard library nor in any module in the
// build list.
-func (r *resolver) loadPackages(loaderstate *modload.State, ctx context.Context, patterns []string, findPackage func(ctx context.Context, path string, m module.Version) (versionOk bool)) {
+func (r *resolver) loadPackages(ld *modload.Loader, ctx context.Context, patterns []string, findPackage func(ctx context.Context, path string, m module.Version) (versionOk bool)) {
opts := modload.PackageOpts{
Tags: imports.AnyTags(),
VendorModulesInGOROOTSrc: true,
LoadTests: *getT,
AssumeRootsImported: true, // After 'go get foo', imports of foo should build.
SilencePackageErrors: true, // May be fixed by subsequent upgrades or downgrades.
- Switcher: toolchain.NewSwitcher(loaderstate),
+ Switcher: toolchain.NewSwitcher(ld),
}
opts.AllowPackage = func(ctx context.Context, path string, m module.Version) error {
@@ -1298,13 +1298,13 @@ func (r *resolver) loadPackages(loaderstate *modload.State, ctx context.Context,
return nil
}
- _, pkgs := modload.LoadPackages(loaderstate, ctx, opts, patterns...)
+ _, pkgs := modload.LoadPackages(ld, ctx, opts, patterns...)
for _, pkgPath := range pkgs {
const (
parentPath = ""
parentIsStd = false
)
- _, _, err := modload.Lookup(loaderstate, parentPath, parentIsStd, pkgPath)
+ _, _, err := modload.Lookup(ld, parentPath, parentIsStd, pkgPath)
if err == nil {
continue
}
@@ -1350,7 +1350,7 @@ var errVersionChange = errors.New("version change needed")
//
// If all pathSets are resolved without any changes to the build list,
// resolveQueries returns with changed=false.
-func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Context, queries []*query) (changed bool) {
+func (r *resolver) resolveQueries(ld *modload.Loader, ctx context.Context, queries []*query) (changed bool) {
defer base.ExitIfErrors()
// Note: this is O(N²) with the number of pathSets in the worst case.
@@ -1369,7 +1369,7 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
// If we found modules that were too new, find the max of the required versions
// and then try to switch to a newer toolchain.
- sw := toolchain.NewSwitcher(loaderstate)
+ sw := toolchain.NewSwitcher(ld)
for _, q := range queries {
for _, cs := range q.candidates {
sw.Error(cs.err)
@@ -1394,7 +1394,7 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
continue
}
- filtered, isPackage, m, unique := r.disambiguate(loaderstate, cs)
+ filtered, isPackage, m, unique := r.disambiguate(ld, cs)
if !unique {
unresolved = append(unresolved, filtered)
continue
@@ -1408,7 +1408,7 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
if isPackage {
q.matchesPackages = true
}
- r.resolve(loaderstate, q, m)
+ r.resolve(ld, q, m)
resolved++
}
@@ -1422,7 +1422,7 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
}
if resolved > 0 {
- if changed = r.updateBuildList(loaderstate, ctx, nil); changed {
+ if changed = r.updateBuildList(ld, ctx, nil); changed {
// The build list has changed, so disregard any remaining ambiguous queries:
// they might now be determined by requirements in the build list, which we
// would prefer to use instead of arbitrary versions.
@@ -1444,12 +1444,12 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
if isPackage {
q.matchesPackages = true
}
- r.resolve(loaderstate, q, m)
+ r.resolve(ld, q, m)
resolvedArbitrarily++
}
}
if resolvedArbitrarily > 0 {
- changed = r.updateBuildList(loaderstate, ctx, nil)
+ changed = r.updateBuildList(ld, ctx, nil)
}
return changed
}
@@ -1465,7 +1465,7 @@ func (r *resolver) resolveQueries(loaderstate *modload.State, ctx context.Contex
//
// If all pathSets are resolved without any changes to the build list,
// applyUpgrades returns with changed=false.
-func (r *resolver) applyUpgrades(loaderstate *modload.State, ctx context.Context, upgrades []pathSet) (changed bool) {
+func (r *resolver) applyUpgrades(ld *modload.Loader, ctx context.Context, upgrades []pathSet) (changed bool) {
defer base.ExitIfErrors()
// Arbitrarily add a "latest" version that provides each missing package, but
@@ -1478,7 +1478,7 @@ func (r *resolver) applyUpgrades(loaderstate *modload.State, ctx context.Context
continue
}
- filtered, _, m, unique := r.disambiguate(loaderstate, cs)
+ filtered, _, m, unique := r.disambiguate(ld, cs)
if !unique {
_, m = r.chooseArbitrarily(filtered)
}
@@ -1491,7 +1491,7 @@ func (r *resolver) applyUpgrades(loaderstate *modload.State, ctx context.Context
}
base.ExitIfErrors()
- changed = r.updateBuildList(loaderstate, ctx, tentative)
+ changed = r.updateBuildList(ld, ctx, tentative)
return changed
}
@@ -1505,7 +1505,7 @@ func (r *resolver) applyUpgrades(loaderstate *modload.State, ctx context.Context
// In the vast majority of cases, we expect only one module per pathSet,
// but we want to give some minimal additional tools so that users can add an
// extra argument or two on the command line to resolve simple ambiguities.
-func (r *resolver) disambiguate(s *modload.State, cs pathSet) (filtered pathSet, isPackage bool, m module.Version, unique bool) {
+func (r *resolver) disambiguate(s *modload.Loader, cs pathSet) (filtered pathSet, isPackage bool, m module.Version, unique bool) {
if len(cs.pkgMods) == 0 && cs.mod.Path == "" {
panic("internal error: resolveIfUnambiguous called with empty pathSet")
}
@@ -1622,7 +1622,7 @@ func (r *resolver) chooseArbitrarily(cs pathSet) (isPackage bool, m module.Versi
// We skip missing-package errors earlier in the process, since we want to
// resolve pathSets ourselves, but at that point, we don't have enough context
// to log the package-import chains leading to each error.
-func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.Context, pkgPatterns []string) {
+func (r *resolver) checkPackageProblems(ld *modload.Loader, ctx context.Context, pkgPatterns []string) {
defer base.ExitIfErrors()
// Enter workspace mode, if the current main module would belong to it, when
@@ -1633,16 +1633,16 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
// info, but switch back to single module mode when fetching sums so that we update
// the single module's go.sum file.
var exitWorkspace func()
- if r.workspace != nil && r.workspace.hasModule(loaderstate.MainModules.Versions()[0].Path) {
+ if r.workspace != nil && r.workspace.hasModule(ld.MainModules.Versions()[0].Path) {
var err error
- exitWorkspace, err = modload.EnterWorkspace(loaderstate, ctx)
+ exitWorkspace, err = modload.EnterWorkspace(ld, ctx)
if err != nil {
// A TooNewError can happen for
// go get go@newversion when all the required modules
// are old enough but the go command itself is not new
// enough. See the related comment on the SwitchOrFatal
// in runGet when WriteGoMod returns an error.
- toolchain.SwitchOrFatal(loaderstate, ctx, err)
+ toolchain.SwitchOrFatal(ld, ctx, err)
}
}
@@ -1674,7 +1674,7 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
AllowErrors: true,
SilenceNoGoErrors: true,
}
- matches, pkgs := modload.LoadPackages(loaderstate, ctx, pkgOpts, pkgPatterns...)
+ matches, pkgs := modload.LoadPackages(ld, ctx, pkgOpts, pkgPatterns...)
for _, m := range matches {
if len(m.Errs) > 0 {
base.SetExitStatus(1)
@@ -1682,7 +1682,7 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
}
}
for _, pkg := range pkgs {
- if dir, _, err := modload.Lookup(loaderstate, "", false, pkg); err != nil {
+ if dir, _, err := modload.Lookup(ld, "", false, pkg); err != nil {
if dir != "" && errors.Is(err, imports.ErrNoGo) {
// Since dir is non-empty, we must have located source files
// associated with either the package or its test — ErrNoGo must
@@ -1701,19 +1701,19 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
}
}
}
- if m := loaderstate.PackageModule(pkg); m.Path != "" {
+ if m := ld.PackageModule(pkg); m.Path != "" {
relevantMods[m] |= hasPkg
}
}
for _, match := range matches {
for _, pkg := range match.Pkgs {
- m := loaderstate.PackageModule(pkg)
+ m := ld.PackageModule(pkg)
relevantMods[m] |= named
}
}
}
- reqs := modload.LoadModFile(loaderstate, ctx)
+ reqs := modload.LoadModFile(ld, ctx)
for m := range relevantMods {
if reqs.IsDirect(m.Path) {
relevantMods[m] |= direct
@@ -1737,7 +1737,7 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
for i := range retractions {
i := i
r.work.Add(func() {
- err := loaderstate.CheckRetractions(ctx, retractions[i].m)
+ err := ld.CheckRetractions(ctx, retractions[i].m)
if _, ok := errors.AsType[*modload.ModuleRetractedError](err); ok {
retractions[i].message = err.Error()
}
@@ -1758,7 +1758,7 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
for i := range deprecations {
i := i
r.work.Add(func() {
- deprecation, err := modload.CheckDeprecation(loaderstate, ctx, deprecations[i].m)
+ deprecation, err := modload.CheckDeprecation(ld, ctx, deprecations[i].m)
if err != nil || deprecation == "" {
return
}
@@ -1788,7 +1788,7 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
i := i
m := r.buildList[i]
mActual := m
- if mRepl := modload.Replacement(loaderstate, m); mRepl.Path != "" {
+ if mRepl := modload.Replacement(ld, m); mRepl.Path != "" {
mActual = mRepl
}
old := module.Version{Path: m.Path, Version: r.initialVersion[m.Path]}
@@ -1796,14 +1796,14 @@ func (r *resolver) checkPackageProblems(loaderstate *modload.State, ctx context.
continue
}
oldActual := old
- if oldRepl := modload.Replacement(loaderstate, old); oldRepl.Path != "" {
+ if oldRepl := modload.Replacement(ld, old); oldRepl.Path != "" {
oldActual = oldRepl
}
- if mActual == oldActual || mActual.Version == "" || !modfetch.HaveSum(loaderstate.Fetcher(), oldActual) {
+ if mActual == oldActual || mActual.Version == "" || !modfetch.HaveSum(ld.Fetcher(), oldActual) {
continue
}
r.work.Add(func() {
- if _, err := loaderstate.Fetcher().DownloadZip(ctx, mActual); err != nil {
+ if _, err := ld.Fetcher().DownloadZip(ctx, mActual); err != nil {
verb := "upgraded"
if gover.ModCompare(m.Path, m.Version, old.Version) < 0 {
verb = "downgraded"
@@ -1967,7 +1967,7 @@ func (r *resolver) reportChanges(oldReqs, newReqs []module.Version) {
// resolve records that module m must be at its indicated version (which may be
// "none") due to query q. If some other query forces module m to be at a
// different version, resolve reports a conflict error.
-func (r *resolver) resolve(s *modload.State, q *query, m module.Version) {
+func (r *resolver) resolve(s *modload.Loader, q *query, m module.Version) {
if m.Path == "" {
panic("internal error: resolving a module.Version with an empty path")
}
@@ -2000,20 +2000,20 @@ func (r *resolver) resolve(s *modload.State, q *query, m module.Version) {
//
// If the resulting build list is the same as the one resulting from the last
// call to updateBuildList, updateBuildList returns with changed=false.
-func (r *resolver) updateBuildList(loaderstate *modload.State, ctx context.Context, additions []module.Version) (changed bool) {
+func (r *resolver) updateBuildList(ld *modload.Loader, ctx context.Context, additions []module.Version) (changed bool) {
defer base.ExitIfErrors()
resolved := make([]module.Version, 0, len(r.resolvedVersion))
for mPath, rv := range r.resolvedVersion {
- if !loaderstate.MainModules.Contains(mPath) {
+ if !ld.MainModules.Contains(mPath) {
resolved = append(resolved, module.Version{Path: mPath, Version: rv.version})
}
}
- changed, err := modload.EditBuildList(loaderstate, ctx, additions, resolved)
+ changed, err := modload.EditBuildList(ld, ctx, additions, resolved)
if err != nil {
if errors.Is(err, gover.ErrTooNew) {
- toolchain.SwitchOrFatal(loaderstate, ctx, err)
+ toolchain.SwitchOrFatal(ld, ctx, err)
}
constraint, ok := errors.AsType[*modload.ConstraintError](err)
@@ -2057,9 +2057,9 @@ func (r *resolver) updateBuildList(loaderstate *modload.State, ctx context.Conte
return false
}
- mg, err := modload.LoadModGraph(loaderstate, ctx, "")
+ mg, err := modload.LoadModGraph(ld, ctx, "")
if err != nil {
- toolchain.SwitchOrFatal(loaderstate, ctx, err)
+ toolchain.SwitchOrFatal(ld, ctx, err)
}
r.buildList = mg.BuildList()
diff --git a/src/cmd/go/internal/modget/query.go b/src/cmd/go/internal/modget/query.go
index e9807edda5..6919cb53ea 100644
--- a/src/cmd/go/internal/modget/query.go
+++ b/src/cmd/go/internal/modget/query.go
@@ -139,7 +139,7 @@ func errSet(err error) pathSet { return pathSet{err: err} }
// newQuery returns a new query parsed from the raw argument,
// which must be either path or path@version.
-func newQuery(loaderstate *modload.State, raw string) (*query, error) {
+func newQuery(ld *modload.Loader, raw string) (*query, error) {
pattern, rawVers, found, err := modload.ParsePathVersion(raw)
if err != nil {
return nil, err
@@ -170,14 +170,14 @@ func newQuery(loaderstate *modload.State, raw string) (*query, error) {
q.matchWildcard = pkgpattern.MatchPattern(q.pattern)
q.canMatchWildcardInModule = pkgpattern.TreeCanMatchPattern(q.pattern)
}
- if err := q.validate(loaderstate); err != nil {
+ if err := q.validate(ld); err != nil {
return q, err
}
return q, nil
}
// validate reports a non-nil error if q is not sensible and well-formed.
-func (q *query) validate(loaderstate *modload.State) error {
+func (q *query) validate(ld *modload.Loader) error {
if q.patternIsLocal {
if q.rawVersion != "" {
return fmt.Errorf("can't request explicit version %q of path %q in main module", q.rawVersion, q.pattern)
@@ -187,15 +187,15 @@ func (q *query) validate(loaderstate *modload.State) error {
if q.pattern == "all" {
// If there is no main module, "all" is not meaningful.
- if !loaderstate.HasModRoot() {
- return fmt.Errorf(`cannot match "all": %v`, modload.NewNoMainModulesError(loaderstate))
+ if !ld.HasModRoot() {
+ return fmt.Errorf(`cannot match "all": %v`, modload.NewNoMainModulesError(ld))
}
if !versionOkForMainModule(q.version) {
// TODO(bcmills): "all@none" seems like a totally reasonable way to
// request that we remove all module requirements, leaving only the main
// module and standard library. Perhaps we should implement that someday.
return &modload.QueryUpgradesAllError{
- MainModules: loaderstate.MainModules.Versions(),
+ MainModules: ld.MainModules.Versions(),
Query: q.version,
}
}
diff --git a/src/cmd/go/internal/modload/build.go b/src/cmd/go/internal/modload/build.go
index e19becf5cc..518e544e49 100644
--- a/src/cmd/go/internal/modload/build.go
+++ b/src/cmd/go/internal/modload/build.go
@@ -50,40 +50,40 @@ func findStandardImportPath(path string) string {
// 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 PackageModuleInfo(loaderstate *State, ctx context.Context, pkgpath string) *modinfo.ModulePublic {
- if isStandardImportPath(pkgpath) || !loaderstate.Enabled() {
+func PackageModuleInfo(ld *Loader, ctx context.Context, pkgpath string) *modinfo.ModulePublic {
+ if isStandardImportPath(pkgpath) || !ld.Enabled() {
return nil
}
- m, ok := findModule(loaderstate.pkgLoader, pkgpath)
+ m, ok := findModule(ld.pkgLoader, pkgpath)
if !ok {
return nil
}
- rs := LoadModFile(loaderstate, ctx)
- return moduleInfo(loaderstate, ctx, rs, m, 0, nil)
+ rs := LoadModFile(ld, ctx)
+ return moduleInfo(ld, ctx, rs, m, 0, nil)
}
// PackageModRoot returns the module root directory for 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, the empty string is returned.
-func PackageModRoot(loaderstate *State, ctx context.Context, pkgpath string) string {
- if isStandardImportPath(pkgpath) || !loaderstate.Enabled() || cfg.BuildMod == "vendor" {
+func PackageModRoot(ld *Loader, ctx context.Context, pkgpath string) string {
+ if isStandardImportPath(pkgpath) || !ld.Enabled() || cfg.BuildMod == "vendor" {
return ""
}
- m, ok := findModule(loaderstate.pkgLoader, pkgpath)
+ m, ok := findModule(ld.pkgLoader, pkgpath)
if !ok {
return ""
}
- root, _, err := fetch(loaderstate, ctx, m)
+ root, _, err := fetch(ld, ctx, m)
if err != nil {
return ""
}
return root
}
-func ModuleInfo(loaderstate *State, ctx context.Context, path string) *modinfo.ModulePublic {
- if !loaderstate.Enabled() {
+func ModuleInfo(ld *Loader, ctx context.Context, path string) *modinfo.ModulePublic {
+ if !ld.Enabled() {
return nil
}
@@ -98,20 +98,20 @@ func ModuleInfo(loaderstate *State, ctx context.Context, path string) *modinfo.M
}
if found {
m := module.Version{Path: path, Version: vers}
- return moduleInfo(loaderstate, ctx, nil, m, 0, nil)
+ return moduleInfo(ld, ctx, nil, m, 0, nil)
}
- rs := LoadModFile(loaderstate, ctx)
+ rs := LoadModFile(ld, ctx)
var (
v string
ok bool
)
if rs.pruning == pruned {
- v, ok = rs.rootSelected(loaderstate, path)
+ v, ok = rs.rootSelected(ld, path)
}
if !ok {
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
base.Fatal(err)
}
@@ -127,16 +127,16 @@ func ModuleInfo(loaderstate *State, ctx context.Context, path string) *modinfo.M
}
}
- return moduleInfo(loaderstate, ctx, rs, module.Version{Path: path, Version: v}, 0, nil)
+ return moduleInfo(ld, ctx, rs, module.Version{Path: path, Version: v}, 0, nil)
}
// addUpdate fills in m.Update if an updated version is available.
-func addUpdate(loaderstate *State, ctx context.Context, m *modinfo.ModulePublic) {
+func addUpdate(ld *Loader, ctx context.Context, m *modinfo.ModulePublic) {
if m.Version == "" {
return
}
- info, err := Query(loaderstate, ctx, m.Path, "upgrade", m.Version, loaderstate.CheckAllowed)
+ info, err := Query(ld, ctx, m.Path, "upgrade", m.Version, ld.CheckAllowed)
if _, ok := errors.AsType[*NoMatchingVersionError](err); ok ||
errors.Is(err, fs.ErrNotExist) ||
errors.Is(err, ErrDisallowed) {
@@ -226,16 +226,16 @@ func mergeOrigin(m1, m2 *codehost.Origin) *codehost.Origin {
// addVersions fills in m.Versions with the list of known versions.
// Excluded versions will be omitted. If listRetracted is false, retracted
// versions will also be omitted.
-func addVersions(loaderstate *State, ctx context.Context, m *modinfo.ModulePublic, listRetracted bool) {
+func addVersions(ld *Loader, ctx context.Context, m *modinfo.ModulePublic, listRetracted bool) {
// TODO(bcmills): Would it make sense to check for reuse here too?
// Perhaps that doesn't buy us much, though: we would always have to fetch
// all of the version tags to list the available versions anyway.
- allowed := loaderstate.CheckAllowed
+ allowed := ld.CheckAllowed
if listRetracted {
- allowed = loaderstate.CheckExclusions
+ allowed = ld.CheckExclusions
}
- v, origin, err := versions(loaderstate, ctx, m.Path, allowed)
+ v, origin, err := versions(ld, ctx, m.Path, allowed)
if err != nil && m.Error == nil {
m.Error = &modinfo.ModuleError{Err: err.Error()}
}
@@ -245,12 +245,12 @@ func addVersions(loaderstate *State, ctx context.Context, m *modinfo.ModulePubli
// addRetraction fills in m.Retracted if the module was retracted by its author.
// m.Error is set if there's an error loading retraction information.
-func addRetraction(loaderstate *State, ctx context.Context, m *modinfo.ModulePublic) {
+func addRetraction(ld *Loader, ctx context.Context, m *modinfo.ModulePublic) {
if m.Version == "" {
return
}
- err := loaderstate.CheckRetractions(ctx, module.Version{Path: m.Path, Version: m.Version})
+ err := ld.CheckRetractions(ctx, module.Version{Path: m.Path, Version: m.Version})
if err == nil {
return
} else if _, ok := errors.AsType[*NoMatchingVersionError](err); ok || errors.Is(err, fs.ErrNotExist) {
@@ -276,8 +276,8 @@ func addRetraction(loaderstate *State, ctx context.Context, m *modinfo.ModulePub
// addDeprecation fills in m.Deprecated if the module was deprecated by its
// author. m.Error is set if there's an error loading deprecation information.
-func addDeprecation(loaderstate *State, ctx context.Context, m *modinfo.ModulePublic) {
- deprecation, err := CheckDeprecation(loaderstate, ctx, module.Version{Path: m.Path, Version: m.Version})
+func addDeprecation(ld *Loader, ctx context.Context, m *modinfo.ModulePublic) {
+ deprecation, err := CheckDeprecation(ld, ctx, module.Version{Path: m.Path, Version: m.Version})
if _, ok := errors.AsType[*NoMatchingVersionError](err); ok || errors.Is(err, fs.ErrNotExist) {
// Ignore "no matching version" and "not found" errors.
// This means the proxy has no matching version or no versions at all.
@@ -301,8 +301,8 @@ func addDeprecation(loaderstate *State, ctx context.Context, m *modinfo.ModulePu
// moduleInfo returns information about module m, loaded from the requirements
// in rs (which may be nil to indicate that m was not loaded from a requirement
// graph).
-func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m module.Version, mode ListMode, reuse map[module.Version]*modinfo.ModulePublic) *modinfo.ModulePublic {
- if m.Version == "" && loaderstate.MainModules.Contains(m.Path) {
+func moduleInfo(ld *Loader, ctx context.Context, rs *Requirements, m module.Version, mode ListMode, reuse map[module.Version]*modinfo.ModulePublic) *modinfo.ModulePublic {
+ if m.Version == "" && ld.MainModules.Contains(m.Path) {
info := &modinfo.ModulePublic{
Path: m.Path,
Version: m.Version,
@@ -313,7 +313,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
} else {
panic("internal error: GoVersion not set for main module")
}
- if modRoot := loaderstate.MainModules.ModRoot(m); modRoot != "" {
+ if modRoot := ld.MainModules.ModRoot(m); modRoot != "" {
info.Dir = modRoot
info.GoMod = modFilePath(modRoot)
}
@@ -336,15 +336,15 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
}
checksumOk := func(suffix string) bool {
- return rs == nil || m.Version == "" || !mustHaveSums(loaderstate) ||
- modfetch.HaveSum(loaderstate.Fetcher(), module.Version{Path: m.Path, Version: m.Version + suffix})
+ return rs == nil || m.Version == "" || !mustHaveSums(ld) ||
+ modfetch.HaveSum(ld.Fetcher(), module.Version{Path: m.Path, Version: m.Version + suffix})
}
mod := module.Version{Path: m.Path, Version: m.Version}
if m.Version != "" {
if old := reuse[mod]; old != nil {
- if err := checkReuse(loaderstate, ctx, mod, old.Origin); err == nil {
+ if err := checkReuse(ld, ctx, mod, old.Origin); err == nil {
*m = *old
m.Query = ""
m.Dir = ""
@@ -352,7 +352,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
}
}
- if q, err := Query(loaderstate, ctx, m.Path, m.Version, "", nil); err != nil {
+ if q, err := Query(ld, ctx, m.Path, m.Version, "", nil); err != nil {
m.Error = &modinfo.ModuleError{Err: err.Error()}
} else {
m.Version = q.Version
@@ -363,7 +363,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
if m.GoVersion == "" && checksumOk("/go.mod") {
// Load the go.mod file to determine the Go version, since it hasn't
// already been populated from rawGoVersion.
- if summary, err := rawGoModSummary(loaderstate, mod); err == nil && summary.goVersion != "" {
+ if summary, err := rawGoModSummary(ld, mod); err == nil && summary.goVersion != "" {
m.GoVersion = summary.goVersion
}
}
@@ -376,7 +376,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
m.GoMod = gomod
}
}
- if gomodsum, ok := loaderstate.fetcher.RecordedSum(modkey(mod)); ok {
+ if gomodsum, ok := ld.fetcher.RecordedSum(modkey(mod)); ok {
m.GoModSum = gomodsum
}
}
@@ -385,13 +385,13 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
if err == nil {
m.Dir = dir
}
- if sum, ok := loaderstate.fetcher.RecordedSum(mod); ok {
+ if sum, ok := ld.fetcher.RecordedSum(mod); ok {
m.Sum = sum
}
}
if mode&ListRetracted != 0 {
- addRetraction(loaderstate, ctx, m)
+ addRetraction(ld, ctx, m)
}
}
}
@@ -403,7 +403,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
return info
}
- r := Replacement(loaderstate, m)
+ r := Replacement(ld, m)
if r.Path == "" {
if cfg.BuildMod == "vendor" {
// It's tempting to fill in the "Dir" field to point within the vendor
@@ -432,7 +432,7 @@ func moduleInfo(loaderstate *State, ctx context.Context, rs *Requirements, m mod
if filepath.IsAbs(r.Path) {
info.Replace.Dir = r.Path
} else {
- info.Replace.Dir = filepath.Join(replaceRelativeTo(loaderstate), r.Path)
+ info.Replace.Dir = filepath.Join(replaceRelativeTo(ld), r.Path)
}
info.Replace.GoMod = filepath.Join(info.Replace.Dir, "go.mod")
}
diff --git a/src/cmd/go/internal/modload/buildlist.go b/src/cmd/go/internal/modload/buildlist.go
index 37c2a6c759..a17626e3f5 100644
--- a/src/cmd/go/internal/modload/buildlist.go
+++ b/src/cmd/go/internal/modload/buildlist.go
@@ -104,21 +104,21 @@ func mustHaveGoRoot(roots []module.Version) {
//
// If vendoring is in effect, the caller must invoke initVendor on the returned
// *Requirements before any other method.
-func newRequirements(loaderstate *State, pruning modPruning, rootModules []module.Version, direct map[string]bool) *Requirements {
+func newRequirements(ld *Loader, pruning modPruning, rootModules []module.Version, direct map[string]bool) *Requirements {
mustHaveGoRoot(rootModules)
if pruning != workspace {
- if loaderstate.workFilePath != "" {
+ if ld.workFilePath != "" {
panic("in workspace mode, but pruning is not workspace in newRequirements")
}
}
if pruning != workspace {
- if loaderstate.workFilePath != "" {
+ if ld.workFilePath != "" {
panic("in workspace mode, but pruning is not workspace in newRequirements")
}
for i, m := range rootModules {
- if m.Version == "" && loaderstate.MainModules.Contains(m.Path) {
+ if m.Version == "" && ld.MainModules.Contains(m.Path) {
panic(fmt.Sprintf("newRequirements called with untrimmed build list: rootModules[%v] is a main module", i))
}
if m.Path == "" || m.Version == "" {
@@ -162,10 +162,10 @@ func (rs *Requirements) String() string {
// initVendor initializes rs.graph from the given list of vendored module
// dependencies, overriding the graph that would normally be loaded from module
// requirements.
-func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Version) {
+func (rs *Requirements) initVendor(ld *Loader, vendorList []module.Version) {
rs.graphOnce.Do(func() {
- roots := loaderstate.MainModules.Versions()
- if loaderstate.inWorkspaceMode() {
+ roots := ld.MainModules.Versions()
+ if ld.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.
@@ -176,7 +176,7 @@ func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Versi
}
if rs.pruning == pruned {
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
// The roots of a single pruned module should already include every module in the
// vendor list, because the vendored modules are the same as those needed
// for graph pruning.
@@ -184,7 +184,7 @@ func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Versi
// Just to be sure, we'll double-check that here.
inconsistent := false
for _, m := range vendorList {
- if v, ok := rs.rootSelected(loaderstate, m.Path); !ok || v != m.Version {
+ if v, ok := rs.rootSelected(ld, m.Path); !ok || v != m.Version {
base.Errorf("go: vendored module %v should be required explicitly in go.mod", m)
inconsistent = true
}
@@ -208,15 +208,15 @@ 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 loaderstate.inWorkspaceMode() {
- for _, m := range loaderstate.MainModules.Versions() {
- reqs, _ := rootsFromModFile(loaderstate, m, loaderstate.MainModules.ModFile(m), omitToolchainRoot)
+ if ld.inWorkspaceMode() {
+ for _, m := range ld.MainModules.Versions() {
+ reqs, _ := rootsFromModFile(ld, m, ld.MainModules.ModFile(m), omitToolchainRoot)
mg.g.Require(m, append(reqs, vendorMod))
}
mg.g.Require(vendorMod, vendorList)
} else {
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
mg.g.Require(mainModule, append(rs.rootModules, vendorMod))
mg.g.Require(vendorMod, vendorList)
}
@@ -227,8 +227,8 @@ func (rs *Requirements) initVendor(loaderstate *State, vendorList []module.Versi
}
// GoVersion returns the Go language version for the Requirements.
-func (rs *Requirements) GoVersion(loaderstate *State) string {
- v, _ := rs.rootSelected(loaderstate, "go")
+func (rs *Requirements) GoVersion(ld *Loader) string {
+ v, _ := rs.rootSelected(ld, "go")
if v == "" {
panic("internal error: missing go version in modload.Requirements")
}
@@ -238,8 +238,8 @@ func (rs *Requirements) GoVersion(loaderstate *State) string {
// rootSelected returns the version of the root dependency with the given module
// path, or the zero module.Version and ok=false if the module is not a root
// dependency.
-func (rs *Requirements) rootSelected(loaderstate *State, path string) (version string, ok bool) {
- if loaderstate.MainModules.Contains(path) {
+func (rs *Requirements) rootSelected(ld *Loader, path string) (version string, ok bool) {
+ if ld.MainModules.Contains(path) {
return "", true
}
if v, ok := rs.maxRootVersion[path]; ok {
@@ -252,9 +252,9 @@ func (rs *Requirements) rootSelected(loaderstate *State, path string) (version s
// of the same module or a requirement on any version of the main module.
// Redundant requirements should be pruned, but they may influence version
// selection.
-func (rs *Requirements) hasRedundantRoot(loaderstate *State) bool {
+func (rs *Requirements) hasRedundantRoot(ld *Loader) bool {
for i, m := range rs.rootModules {
- if loaderstate.MainModules.Contains(m.Path) || (i > 0 && m.Path == rs.rootModules[i-1].Path) {
+ if ld.MainModules.Contains(m.Path) || (i > 0 && m.Path == rs.rootModules[i-1].Path) {
return true
}
}
@@ -269,9 +269,9 @@ func (rs *Requirements) hasRedundantRoot(loaderstate *State) bool {
//
// If the requirements of any relevant module fail to load, Graph also
// returns a non-nil error of type *mvs.BuildListError.
-func (rs *Requirements) Graph(loaderstate *State, ctx context.Context) (*ModuleGraph, error) {
+func (rs *Requirements) Graph(ld *Loader, ctx context.Context) (*ModuleGraph, error) {
rs.graphOnce.Do(func() {
- mg, mgErr := readModGraph(loaderstate, ctx, rs.pruning, rs.rootModules, nil)
+ mg, mgErr := readModGraph(ld, ctx, rs.pruning, rs.rootModules, nil)
rs.graph.Store(&cachedGraph{mg, mgErr})
})
cached := rs.graph.Load()
@@ -307,7 +307,7 @@ var readModGraphDebugOnce sync.Once
//
// Unlike LoadModGraph, readModGraph does not attempt to diagnose or update
// inconsistent roots.
-func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, roots []module.Version, unprune map[module.Version]bool) (*ModuleGraph, error) {
+func readModGraph(ld *Loader, ctx context.Context, pruning modPruning, roots []module.Version, unprune map[module.Version]bool) (*ModuleGraph, error) {
mustHaveGoRoot(roots)
if pruning == pruned {
// Enable diagnostics for lazy module loading
@@ -333,10 +333,10 @@ func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, r
}
var graphRoots []module.Version
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
graphRoots = roots
} else {
- graphRoots = loaderstate.MainModules.Versions()
+ graphRoots = ld.MainModules.Versions()
}
var (
mu sync.Mutex // guards mg.g and hasError during loading
@@ -347,10 +347,10 @@ func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, r
)
if pruning != workspace {
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
panic("pruning is not workspace in workspace mode")
}
- mg.g.Require(loaderstate.MainModules.mustGetSingleMainModule(loaderstate), roots)
+ mg.g.Require(ld.MainModules.mustGetSingleMainModule(ld), roots)
}
type dedupKey struct {
@@ -367,7 +367,7 @@ func readModGraph(loaderstate *State, ctx context.Context, pruning modPruning, r
// m's go.mod file indicates that it supports graph pruning.
loadOne := func(m module.Version) (*modFileSummary, error) {
return mg.loadCache.Do(m, func() (*modFileSummary, error) {
- summary, err := goModSummary(loaderstate, m)
+ summary, err := goModSummary(ld, m)
mu.Lock()
if err == nil {
@@ -527,12 +527,12 @@ func (mg *ModuleGraph) findError() error {
return nil
}
-func (mg *ModuleGraph) allRootsSelected(loaderstate *State) bool {
+func (mg *ModuleGraph) allRootsSelected(ld *Loader) bool {
var roots []module.Version
- if loaderstate.inWorkspaceMode() {
- roots = loaderstate.MainModules.Versions()
+ if ld.inWorkspaceMode() {
+ roots = ld.MainModules.Versions()
} else {
- roots, _ = mg.g.RequiredBy(loaderstate.MainModules.mustGetSingleMainModule(loaderstate))
+ roots, _ = mg.g.RequiredBy(ld.MainModules.mustGetSingleMainModule(ld))
}
for _, m := range roots {
if mg.Selected(m.Path) != m.Version {
@@ -552,14 +552,14 @@ func (mg *ModuleGraph) allRootsSelected(loaderstate *State) bool {
// 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 LoadModGraph(loaderstate *State, ctx context.Context, goVersion string) (*ModuleGraph, error) {
- rs, err := loadModFile(loaderstate, ctx, nil)
+func LoadModGraph(ld *Loader, ctx context.Context, goVersion string) (*ModuleGraph, error) {
+ rs, err := loadModFile(ld, ctx, nil)
if err != nil {
return nil, err
}
if goVersion != "" {
- v, _ := rs.rootSelected(loaderstate, "go")
+ v, _ := rs.rootSelected(ld, "go")
if gover.Compare(v, gover.GoStrictVersion) >= 0 && gover.Compare(goVersion, v) < 0 {
return nil, fmt.Errorf("requested Go version %s cannot load module graph (requires Go >= %s)", goVersion, v)
}
@@ -569,17 +569,17 @@ func LoadModGraph(loaderstate *State, ctx context.Context, goVersion string) (*M
// Use newRequirements instead of convertDepth because convertDepth
// also updates roots; here, we want to report the unmodified roots
// even though they may seem inconsistent.
- rs = newRequirements(loaderstate, unpruned, rs.rootModules, rs.direct)
+ rs = newRequirements(ld, unpruned, rs.rootModules, rs.direct)
}
- return rs.Graph(loaderstate, ctx)
+ return rs.Graph(ld, ctx)
}
- rs, mg, err := expandGraph(loaderstate, ctx, rs)
+ rs, mg, err := expandGraph(ld, ctx, rs)
if err != nil {
return nil, err
}
- loaderstate.requirements = rs
+ ld.requirements = rs
return mg, nil
}
@@ -594,22 +594,22 @@ func LoadModGraph(loaderstate *State, ctx context.Context, goVersion string) (*M
// from those roots and any error encountered while loading that graph.
// expandGraph returns non-nil requirements and a non-nil graph regardless of
// errors. On error, the roots might not be updated to be consistent.
-func expandGraph(loaderstate *State, ctx context.Context, rs *Requirements) (*Requirements, *ModuleGraph, error) {
- mg, mgErr := rs.Graph(loaderstate, ctx)
+func expandGraph(ld *Loader, ctx context.Context, rs *Requirements) (*Requirements, *ModuleGraph, error) {
+ mg, mgErr := rs.Graph(ld, ctx)
if mgErr != nil {
// Without the graph, we can't update the roots: we don't know which
// versions of transitive dependencies would be selected.
return rs, mg, mgErr
}
- if !mg.allRootsSelected(loaderstate) {
+ if !mg.allRootsSelected(ld) {
// The roots of rs are not consistent with the rest of the graph. Update
// them. In an unpruned module this is a no-op for the build list as a whole —
// it just promotes what were previously transitive requirements to be
// roots — but in a pruned module it may pull in previously-irrelevant
// transitive dependencies.
- newRS, rsErr := updateRoots(loaderstate, ctx, rs.direct, rs, nil, nil, false)
+ newRS, rsErr := updateRoots(ld, ctx, rs.direct, rs, nil, nil, false)
if rsErr != nil {
// Failed to update roots, perhaps because of an error in a transitive
// dependency needed for the update. Return the original Requirements
@@ -617,7 +617,7 @@ func expandGraph(loaderstate *State, ctx context.Context, rs *Requirements) (*Re
return rs, mg, rsErr
}
rs = newRS
- mg, mgErr = rs.Graph(loaderstate, ctx)
+ mg, mgErr = rs.Graph(ld, ctx)
}
return rs, mg, mgErr
@@ -639,16 +639,16 @@ func expandGraph(loaderstate *State, ctx context.Context, rs *Requirements) (*Re
// 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 EditBuildList(loaderstate *State, ctx context.Context, add, mustSelect []module.Version) (changed bool, err error) {
- rs, changed, err := editRequirements(loaderstate, ctx, LoadModFile(loaderstate, ctx), add, mustSelect)
+func EditBuildList(ld *Loader, ctx context.Context, add, mustSelect []module.Version) (changed bool, err error) {
+ rs, changed, err := editRequirements(ld, ctx, LoadModFile(ld, ctx), add, mustSelect)
if err != nil {
return false, err
}
- loaderstate.requirements = rs
+ ld.requirements = rs
return changed, nil
}
-func overrideRoots(loaderstate *State, ctx context.Context, rs *Requirements, replace []module.Version) *Requirements {
+func overrideRoots(ld *Loader, ctx context.Context, rs *Requirements, replace []module.Version) *Requirements {
drop := make(map[string]bool)
for _, m := range replace {
drop[m.Path] = true
@@ -661,7 +661,7 @@ func overrideRoots(loaderstate *State, ctx context.Context, rs *Requirements, re
}
roots = append(roots, replace...)
gover.ModSort(roots)
- return newRequirements(loaderstate, rs.pruning, roots, rs.direct)
+ return newRequirements(ld, rs.pruning, roots, rs.direct)
}
// A ConstraintError describes inconsistent constraints in EditBuildList
@@ -765,28 +765,28 @@ func (c Conflict) String() string {
// tidyRoots trims the root dependencies to the minimal requirements needed to
// both retain the same versions of all packages in pkgs and satisfy the
// graph-pruning invariants (if applicable).
-func tidyRoots(loaderstate *State, ctx context.Context, rs *Requirements, pkgs []*loadPkg) (*Requirements, error) {
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
+func tidyRoots(ld *Loader, ctx context.Context, rs *Requirements, pkgs []*loadPkg) (*Requirements, error) {
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
if rs.pruning == unpruned {
- return tidyUnprunedRoots(loaderstate, ctx, mainModule, rs, pkgs)
+ return tidyUnprunedRoots(ld, ctx, mainModule, rs, pkgs)
}
- return tidyPrunedRoots(loaderstate, ctx, mainModule, rs, pkgs)
+ return tidyPrunedRoots(ld, ctx, mainModule, rs, pkgs)
}
-func updateRoots(loaderstate *State, ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
+func updateRoots(ld *Loader, ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
switch rs.pruning {
case unpruned:
- return updateUnprunedRoots(loaderstate, ctx, direct, rs, add)
+ return updateUnprunedRoots(ld, ctx, direct, rs, add)
case pruned:
- return updatePrunedRoots(loaderstate, ctx, direct, rs, pkgs, add, rootsImported)
+ return updatePrunedRoots(ld, ctx, direct, rs, pkgs, add, rootsImported)
case workspace:
- return updateWorkspaceRoots(loaderstate, ctx, direct, rs, add)
+ return updateWorkspaceRoots(ld, ctx, direct, rs, add)
default:
panic(fmt.Sprintf("unsupported pruning mode: %v", rs.pruning))
}
}
-func updateWorkspaceRoots(loaderstate *State, ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
+func updateWorkspaceRoots(ld *Loader, ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
if len(add) != 0 {
// add should be empty in workspace mode because workspace mode implies
// -mod=readonly, which in turn implies no new requirements. The code path
@@ -797,7 +797,7 @@ func updateWorkspaceRoots(loaderstate *State, ctx context.Context, direct map[st
// return an error.
panic("add is not empty")
}
- return newRequirements(loaderstate, workspace, rs.rootModules, direct), nil
+ return newRequirements(ld, workspace, rs.rootModules, direct), nil
}
// tidyPrunedRoots returns a minimal set of root requirements that maintains the
@@ -816,16 +816,16 @@ func updateWorkspaceRoots(loaderstate *State, ctx context.Context, direct map[st
// To ensure that the loading process eventually converges, the caller should
// add any needed roots from the tidy root set (without removing existing untidy
// roots) until the set of roots has converged.
-func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.Version, old *Requirements, pkgs []*loadPkg) (*Requirements, error) {
+func tidyPrunedRoots(ld *Loader, ctx context.Context, mainModule module.Version, old *Requirements, pkgs []*loadPkg) (*Requirements, error) {
var (
roots []module.Version
pathIsRoot = map[string]bool{mainModule.Path: true}
)
- if v, ok := old.rootSelected(loaderstate, "go"); ok {
+ if v, ok := old.rootSelected(ld, "go"); ok {
roots = append(roots, module.Version{Path: "go", Version: v})
pathIsRoot["go"] = true
}
- if v, ok := old.rootSelected(loaderstate, "toolchain"); ok {
+ if v, ok := old.rootSelected(ld, "toolchain"); ok {
roots = append(roots, module.Version{Path: "toolchain", Version: v})
pathIsRoot["toolchain"] = true
}
@@ -847,7 +847,7 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
if !pkg.flags.has(pkgInAll) {
continue
}
- if pkg.fromExternalModule(loaderstate) && !pathIsRoot[pkg.mod.Path] {
+ if pkg.fromExternalModule(ld) && !pathIsRoot[pkg.mod.Path] {
roots = append(roots, pkg.mod)
pathIsRoot[pkg.mod.Path] = true
}
@@ -855,11 +855,11 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
queued[pkg] = true
}
gover.ModSort(roots)
- tidy := newRequirements(loaderstate, pruned, roots, old.direct)
+ tidy := newRequirements(ld, pruned, roots, old.direct)
for len(queue) > 0 {
roots = tidy.rootModules
- mg, err := tidy.Graph(loaderstate, ctx)
+ mg, err := tidy.Graph(ld, ctx)
if err != nil {
return nil, err
}
@@ -892,12 +892,12 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
if len(roots) > len(tidy.rootModules) {
gover.ModSort(roots)
- tidy = newRequirements(loaderstate, pruned, roots, tidy.direct)
+ tidy = newRequirements(ld, pruned, roots, tidy.direct)
}
}
roots = tidy.rootModules
- _, err := tidy.Graph(loaderstate, ctx)
+ _, err := tidy.Graph(ld, ctx)
if err != nil {
return nil, err
}
@@ -921,7 +921,7 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
pkg := pkg
q.Add(func() {
skipModFile := true
- _, _, _, _, err := importFromModules(loaderstate, ctx, pkg.path, tidy, nil, skipModFile)
+ _, _, _, _, err := importFromModules(ld, ctx, pkg.path, tidy, nil, skipModFile)
if _, ok := errors.AsType[*AmbiguousImportError](err); ok {
disambiguateRoot.Store(pkg.mod, true)
}
@@ -938,8 +938,8 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
if len(roots) > len(tidy.rootModules) {
module.Sort(roots)
- tidy = newRequirements(loaderstate, pruned, roots, tidy.direct)
- _, err = tidy.Graph(loaderstate, ctx)
+ tidy = newRequirements(ld, pruned, roots, tidy.direct)
+ _, err = tidy.Graph(ld, ctx)
if err != nil {
return nil, err
}
@@ -999,7 +999,7 @@ func tidyPrunedRoots(loaderstate *State, ctx context.Context, mainModule module.
//
// (See https://golang.org/design/36460-lazy-module-loading#invariants for more
// detail.)
-func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
+func updatePrunedRoots(ld *Loader, ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
roots := rs.rootModules
rootsUpgraded := false
@@ -1009,7 +1009,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
// either pkgInAll or pkgIsRoot is included as a root.”
needSort := false
for _, pkg := range pkgs {
- if !pkg.fromExternalModule(loaderstate) {
+ if !pkg.fromExternalModule(ld) {
// pkg was not loaded from a module dependency, so we don't need
// to do anything special to maintain that dependency.
continue
@@ -1058,7 +1058,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
continue
}
- if _, ok := rs.rootSelected(loaderstate, pkg.mod.Path); ok {
+ if _, ok := rs.rootSelected(ld, pkg.mod.Path); ok {
// It is possible that the main module's go.mod file is incomplete or
// otherwise erroneous — for example, perhaps the author forgot to 'git
// add' their updated go.mod file after adding a new package import, or
@@ -1094,7 +1094,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
}
for _, m := range add {
- if v, ok := rs.rootSelected(loaderstate, m.Path); !ok || gover.ModCompare(m.Path, v, m.Version) < 0 {
+ if v, ok := rs.rootSelected(ld, m.Path); !ok || gover.ModCompare(m.Path, v, m.Version) < 0 {
roots = append(roots, m)
rootsUpgraded = true
needSort = true
@@ -1111,7 +1111,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
// We've added or upgraded one or more roots, so load the full module
// graph so that we can update those roots to be consistent with other
// requirements.
- if mustHaveCompleteRequirements(loaderstate) {
+ if mustHaveCompleteRequirements(ld) {
// Our changes to the roots may have moved dependencies into or out of
// the graph-pruning horizon, which could in turn change the selected
// versions of other modules. (For pruned modules adding or removing an
@@ -1119,9 +1119,9 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
return rs, errGoModDirty
}
- rs = newRequirements(loaderstate, pruned, roots, direct)
+ rs = newRequirements(ld, pruned, roots, direct)
var err error
- mg, err = rs.Graph(loaderstate, ctx)
+ mg, err = rs.Graph(ld, ctx)
if err != nil {
return rs, err
}
@@ -1135,20 +1135,20 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
// We've already loaded the full module graph, which includes the
// requirements of all of the root modules — even the transitive
// requirements, if they are unpruned!
- mg, _ = rs.Graph(loaderstate, ctx)
+ mg, _ = rs.Graph(ld, ctx)
} else if cfg.BuildMod == "vendor" {
// We can't spot-check the requirements of other modules because we
// don't in general have their go.mod files available in the vendor
// directory. (Fortunately this case is impossible, because mg.graph is
// always non-nil in vendor mode!)
panic("internal error: rs.graph is unexpectedly nil with -mod=vendor")
- } else if !spotCheckRoots(loaderstate, ctx, rs, spotCheckRoot) {
+ } else if !spotCheckRoots(ld, ctx, rs, spotCheckRoot) {
// We spot-checked the explicit requirements of the roots that are
// relevant to the packages we've loaded. Unfortunately, they're
// inconsistent in some way; we need to load the full module graph
// so that we can fix the roots properly.
var err error
- mg, err = rs.Graph(loaderstate, ctx)
+ mg, err = rs.Graph(ld, ctx)
if err != nil {
return rs, err
}
@@ -1158,7 +1158,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
roots = make([]module.Version, 0, len(rs.rootModules))
rootsUpgraded = false
inRootPaths := make(map[string]bool, len(rs.rootModules)+1)
- for _, mm := range loaderstate.MainModules.Versions() {
+ for _, mm := range ld.MainModules.Versions() {
inRootPaths[mm.Path] = true
}
for _, m := range rs.rootModules {
@@ -1184,7 +1184,7 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
var v string
if mg == nil {
- v, _ = rs.rootSelected(loaderstate, m.Path)
+ v, _ = rs.rootSelected(ld, m.Path)
} else {
v = mg.Selected(m.Path)
}
@@ -1218,12 +1218,12 @@ func updatePrunedRoots(loaderstate *State, ctx context.Context, direct map[strin
// preserve its cached ModuleGraph (if any).
return rs, nil
}
- return newRequirements(loaderstate, pruned, roots, direct), nil
+ return newRequirements(ld, pruned, roots, direct), nil
}
// spotCheckRoots reports whether the versions of the roots in rs satisfy the
// explicit requirements of the modules in mods.
-func spotCheckRoots(loaderstate *State, ctx context.Context, rs *Requirements, mods map[module.Version]bool) bool {
+func spotCheckRoots(ld *Loader, ctx context.Context, rs *Requirements, mods map[module.Version]bool) bool {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@@ -1235,14 +1235,14 @@ func spotCheckRoots(loaderstate *State, ctx context.Context, rs *Requirements, m
return
}
- summary, err := goModSummary(loaderstate, m)
+ summary, err := goModSummary(ld, m)
if err != nil {
cancel()
return
}
for _, r := range summary.require {
- if v, ok := rs.rootSelected(loaderstate, r.Path); ok && gover.ModCompare(r.Path, v, r.Version) < 0 {
+ if v, ok := rs.rootSelected(ld, r.Path); ok && gover.ModCompare(r.Path, v, r.Version) < 0 {
cancel()
return
}
@@ -1264,7 +1264,7 @@ func spotCheckRoots(loaderstate *State, ctx context.Context, rs *Requirements, m
// the selected version of every module that provided or lexically could have
// provided a package in pkgs, and includes the selected version of every such
// module in direct as a root.
-func tidyUnprunedRoots(loaderstate *State, ctx context.Context, mainModule module.Version, old *Requirements, pkgs []*loadPkg) (*Requirements, error) {
+func tidyUnprunedRoots(ld *Loader, ctx context.Context, mainModule module.Version, old *Requirements, pkgs []*loadPkg) (*Requirements, error) {
var (
// keep is a set of modules that provide packages or are needed to
// disambiguate imports.
@@ -1292,16 +1292,16 @@ func tidyUnprunedRoots(loaderstate *State, ctx context.Context, mainModule modul
// without its sum. See #47738.
altMods = map[string]string{}
)
- if v, ok := old.rootSelected(loaderstate, "go"); ok {
+ if v, ok := old.rootSelected(ld, "go"); ok {
keep = append(keep, module.Version{Path: "go", Version: v})
keptPath["go"] = true
}
- if v, ok := old.rootSelected(loaderstate, "toolchain"); ok {
+ if v, ok := old.rootSelected(ld, "toolchain"); ok {
keep = append(keep, module.Version{Path: "toolchain", Version: v})
keptPath["toolchain"] = true
}
for _, pkg := range pkgs {
- if !pkg.fromExternalModule(loaderstate) {
+ if !pkg.fromExternalModule(ld) {
continue
}
if m := pkg.mod; !keptPath[m.Path] {
@@ -1319,7 +1319,7 @@ func tidyUnprunedRoots(loaderstate *State, ctx context.Context, mainModule modul
// Construct a build list with a minimal set of roots.
// This may remove or downgrade modules in altMods.
- reqs := &mvsReqs{loaderstate: loaderstate, roots: keep}
+ reqs := &mvsReqs{ld: ld, roots: keep}
min, err := mvs.Req(mainModule, rootPaths, reqs)
if err != nil {
return nil, err
@@ -1350,7 +1350,7 @@ func tidyUnprunedRoots(loaderstate *State, ctx context.Context, mainModule modul
}
}
- return newRequirements(loaderstate, unpruned, min, old.direct), nil
+ return newRequirements(ld, unpruned, min, old.direct), nil
}
// updateUnprunedRoots returns a set of root requirements that includes the selected
@@ -1367,8 +1367,8 @@ func tidyUnprunedRoots(loaderstate *State, ctx context.Context, mainModule modul
// by a dependency in add.
// 4. Every version in add is selected at its given version unless upgraded by
// (the dependencies of) an existing root or another module in add.
-func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
- mg, err := rs.Graph(loaderstate, ctx)
+func updateUnprunedRoots(ld *Loader, ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
// We can't ignore errors in the module graph even if the user passed the -e
// flag to try to push past them. If we can't load the complete module
@@ -1376,7 +1376,7 @@ func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[str
return rs, err
}
- if mustHaveCompleteRequirements(loaderstate) {
+ if mustHaveCompleteRequirements(ld) {
// Instead of actually updating the requirements, just check that no updates
// are needed.
if rs == nil {
@@ -1396,7 +1396,7 @@ func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[str
}
}
for mPath := range direct {
- if _, ok := rs.rootSelected(loaderstate, mPath); !ok {
+ if _, ok := rs.rootSelected(ld, mPath); !ok {
// Module m is supposed to be listed explicitly, but isn't.
//
// Note that this condition is also detected (and logged with more
@@ -1435,7 +1435,7 @@ func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[str
// This is only for convenience and clarity for end users: in an unpruned module,
// the choice of explicit vs. implicit dependency has no impact on MVS
// selection (for itself or any other module).
- keep := append(mg.BuildList()[loaderstate.MainModules.Len():], add...)
+ keep := append(mg.BuildList()[ld.MainModules.Len():], add...)
for _, m := range keep {
if direct[m.Path] && !inRootPaths[m.Path] {
rootPaths = append(rootPaths, m.Path)
@@ -1444,14 +1444,14 @@ func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[str
}
var roots []module.Version
- for _, mainModule := range loaderstate.MainModules.Versions() {
- min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{loaderstate: loaderstate, roots: keep})
+ for _, mainModule := range ld.MainModules.Versions() {
+ min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{ld: ld, roots: keep})
if err != nil {
return rs, err
}
roots = append(roots, min...)
}
- if loaderstate.MainModules.Len() > 1 {
+ if ld.MainModules.Len() > 1 {
gover.ModSort(roots)
}
if rs.pruning == unpruned && slices.Equal(roots, rs.rootModules) && maps.Equal(direct, rs.direct) {
@@ -1460,12 +1460,12 @@ func updateUnprunedRoots(loaderstate *State, ctx context.Context, direct map[str
return rs, nil
}
- return newRequirements(loaderstate, unpruned, roots, direct), nil
+ return newRequirements(ld, unpruned, roots, direct), nil
}
// convertPruning returns a version of rs with the given pruning behavior.
// If rs already has the given pruning, convertPruning returns rs unmodified.
-func convertPruning(loaderstate *State, ctx context.Context, rs *Requirements, pruning modPruning) (*Requirements, error) {
+func convertPruning(ld *Loader, ctx context.Context, rs *Requirements, pruning modPruning) (*Requirements, error) {
if rs.pruning == pruning {
return rs, nil
} else if rs.pruning == workspace || pruning == workspace {
@@ -1477,7 +1477,7 @@ func convertPruning(loaderstate *State, ctx context.Context, rs *Requirements, p
// pruned module graph are a superset of the roots of an unpruned one, so
// we don't need to add any new roots — we just need to drop the ones that
// are redundant, which is exactly what updateUnprunedRoots does.
- return updateUnprunedRoots(loaderstate, ctx, rs.direct, rs, nil)
+ return updateUnprunedRoots(ld, ctx, rs.direct, rs, nil)
}
// We are converting an unpruned module to a pruned one.
@@ -1487,9 +1487,9 @@ func convertPruning(loaderstate *State, ctx context.Context, rs *Requirements, p
// root set! “Include the transitive dependencies of every module in the build
// list” is exactly what happens in a pruned module if we promote every module
// in the build list to a root.
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
return rs, err
}
- return newRequirements(loaderstate, pruned, mg.BuildList()[loaderstate.MainModules.Len():], rs.direct), nil
+ return newRequirements(ld, pruned, mg.BuildList()[ld.MainModules.Len():], rs.direct), nil
}
diff --git a/src/cmd/go/internal/modload/edit.go b/src/cmd/go/internal/modload/edit.go
index 8038a77b0b..a631afc094 100644
--- a/src/cmd/go/internal/modload/edit.go
+++ b/src/cmd/go/internal/modload/edit.go
@@ -43,7 +43,7 @@ import (
// If pruning is enabled, the roots of the edited requirements include an
// explicit entry for each module path in tryUpgrade, mustSelect, and the roots
// of rs, unless the selected version for the module path is "none".
-func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements, tryUpgrade, mustSelect []module.Version) (edited *Requirements, changed bool, err error) {
+func editRequirements(ld *Loader, ctx context.Context, rs *Requirements, tryUpgrade, mustSelect []module.Version) (edited *Requirements, changed bool, err error) {
if rs.pruning == workspace {
panic("editRequirements cannot edit workspace requirements")
}
@@ -83,7 +83,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
}
if rootPruning != rs.pruning {
- rs, err = convertPruning(loaderstate, ctx, rs, rootPruning)
+ rs, err = convertPruning(ld, ctx, rs, rootPruning)
if err != nil {
return orig, false, err
}
@@ -101,13 +101,13 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// dependencies, so we need to treat everything in the build list as
// potentially relevant — that is, as what would be a “root” in a module
// with graph pruning enabled.
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
// If we couldn't load the graph, we don't know what its requirements were
// to begin with, so we can't edit those requirements in a coherent way.
return orig, false, err
}
- bl := mg.BuildList()[loaderstate.MainModules.Len():]
+ bl := mg.BuildList()[ld.MainModules.Len():]
selectedRoot = make(map[string]string, len(bl))
for _, m := range bl {
selectedRoot[m.Path] = m.Version
@@ -225,7 +225,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// of every root. The upgraded roots are in addition to the original
// roots, so we will have enough information to trace a path to each
// conflict we discover from one or more of the original roots.
- mg, upgradedRoots, err := extendGraph(loaderstate, ctx, rootPruning, roots, selectedRoot)
+ mg, upgradedRoots, err := extendGraph(ld, ctx, rootPruning, roots, selectedRoot)
if err != nil {
if mg == nil {
return orig, false, err
@@ -392,7 +392,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// the edit. We want to make sure we consider keeping it as-is,
// even if it wouldn't normally be included. (For example, it might
// be a pseudo-version or pre-release.)
- origMG, _ := orig.Graph(loaderstate, ctx)
+ origMG, _ := orig.Graph(ld, ctx)
origV := origMG.Selected(m.Path)
if conflict.Err != nil && origV == m.Version {
@@ -416,7 +416,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
rejectedRoot[m] = true
prev := m
for {
- prev, err = previousVersion(loaderstate, ctx, prev)
+ prev, err = previousVersion(ld, ctx, prev)
if gover.ModCompare(m.Path, m.Version, origV) > 0 && (gover.ModCompare(m.Path, prev.Version, origV) < 0 || err != nil) {
// previousVersion skipped over origV. Insert it into the order.
prev.Version = origV
@@ -516,13 +516,13 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// The modules in mustSelect are always promoted to be explicit.
for _, m := range mustSelect {
- if m.Version != "none" && !loaderstate.MainModules.Contains(m.Path) {
+ if m.Version != "none" && !ld.MainModules.Contains(m.Path) {
rootPaths = append(rootPaths, m.Path)
}
}
for _, m := range roots {
- if v, ok := rs.rootSelected(loaderstate, m.Path); ok && (v == m.Version || rs.direct[m.Path]) {
+ if v, ok := rs.rootSelected(ld, m.Path); ok && (v == m.Version || rs.direct[m.Path]) {
// m.Path was formerly a root, and either its version hasn't changed or
// we believe that it provides a package directly imported by a package
// or test in the main module. For now we'll assume that it is still
@@ -533,7 +533,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
}
}
- roots, err = mvs.Req(loaderstate.MainModules.mustGetSingleMainModule(loaderstate), rootPaths, &mvsReqs{loaderstate: loaderstate, roots: roots})
+ roots, err = mvs.Req(ld.MainModules.mustGetSingleMainModule(ld), rootPaths, &mvsReqs{ld: ld, roots: roots})
if err != nil {
return nil, false, err
}
@@ -564,7 +564,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
direct[m.Path] = true
}
}
- edited = newRequirements(loaderstate, rootPruning, roots, direct)
+ edited = newRequirements(ld, rootPruning, roots, direct)
// If we ended up adding a dependency that upgrades our go version far enough
// to activate pruning, we must convert the edited Requirements in order to
@@ -579,7 +579,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// those two modules will never be downgraded due to a conflict with any other
// constraint.
if rootPruning == unpruned {
- if v, ok := edited.rootSelected(loaderstate, "go"); ok && pruningForGoVersion(v) == pruned {
+ if v, ok := edited.rootSelected(ld, "go"); ok && pruningForGoVersion(v) == pruned {
// Since we computed the edit with the unpruned graph, and the pruned
// graph is a strict subset of the unpruned graph, this conversion
// preserves the exact (edited) build list that we already computed.
@@ -588,7 +588,7 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// the graph. 'go get' will check for that sort of transition and log a
// message reminding the user how to clean up this mess we're about to
// make. 😅
- edited, err = convertPruning(loaderstate, ctx, edited, pruned)
+ edited, err = convertPruning(ld, ctx, edited, pruned)
if err != nil {
return orig, false, err
}
@@ -608,9 +608,9 @@ func editRequirements(loaderstate *State, ctx context.Context, rs *Requirements,
// The extended graph is useful for diagnosing version conflicts: for each
// selected module version, it can provide a complete path of requirements from
// some root to that version.
-func extendGraph(loaderstate *State, ctx context.Context, rootPruning modPruning, roots []module.Version, selectedRoot map[string]string) (mg *ModuleGraph, upgradedRoot map[module.Version]bool, err error) {
+func extendGraph(ld *Loader, ctx context.Context, rootPruning modPruning, roots []module.Version, selectedRoot map[string]string) (mg *ModuleGraph, upgradedRoot map[module.Version]bool, err error) {
for {
- mg, err = readModGraph(loaderstate, ctx, rootPruning, roots, upgradedRoot)
+ mg, err = readModGraph(ld, ctx, rootPruning, roots, upgradedRoot)
// We keep on going even if err is non-nil until we reach a steady state.
// (Note that readModGraph returns a non-nil *ModuleGraph even in case of
// errors.) The caller may be able to fix the errors by adjusting versions,
diff --git a/src/cmd/go/internal/modload/import.go b/src/cmd/go/internal/modload/import.go
index 04e95b7a8d..98f17ccff1 100644
--- a/src/cmd/go/internal/modload/import.go
+++ b/src/cmd/go/internal/modload/import.go
@@ -267,7 +267,7 @@ func (e *invalidImportError) Unwrap() error {
// (https://go.dev/issue/56222) for modules with 'go' versions between 1.17 and
// 1.20, preventing unnecessary go.sum churn and network access in those
// modules.
-func importFromModules(loaderstate *State, ctx context.Context, path string, rs *Requirements, mg *ModuleGraph, skipModFile bool) (m module.Version, modroot, dir string, altMods []module.Version, err error) {
+func importFromModules(ld *Loader, ctx context.Context, path string, rs *Requirements, mg *ModuleGraph, skipModFile bool) (m module.Version, modroot, dir string, altMods []module.Version, err error) {
invalidf := func(format string, args ...any) (module.Version, string, string, []module.Version, error) {
return module.Version{}, "", "", nil, &invalidImportError{
importPath: path,
@@ -304,12 +304,12 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
// Is the package in the standard library?
pathIsStd := search.IsStandardImportPath(path)
if pathIsStd && modindex.IsStandardPackage(cfg.GOROOT, cfg.BuildContext.Compiler, path) {
- for _, mainModule := range loaderstate.MainModules.Versions() {
- if loaderstate.MainModules.InGorootSrc(mainModule) {
- if dir, ok, err := dirInModule(path, loaderstate.MainModules.PathPrefix(mainModule), loaderstate.MainModules.ModRoot(mainModule), true); err != nil {
- return module.Version{}, loaderstate.MainModules.ModRoot(mainModule), dir, nil, err
+ for _, mainModule := range ld.MainModules.Versions() {
+ if ld.MainModules.InGorootSrc(mainModule) {
+ if dir, ok, err := dirInModule(path, ld.MainModules.PathPrefix(mainModule), ld.MainModules.ModRoot(mainModule), true); err != nil {
+ return module.Version{}, ld.MainModules.ModRoot(mainModule), dir, nil, err
} else if ok {
- return mainModule, loaderstate.MainModules.ModRoot(mainModule), dir, nil, nil
+ return mainModule, ld.MainModules.ModRoot(mainModule), dir, nil, nil
}
}
}
@@ -326,10 +326,10 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
// Everything must be in the main modules or the main module's or workspace's vendor directory.
if cfg.BuildMod == "vendor" {
var mainErr error
- for _, mainModule := range loaderstate.MainModules.Versions() {
- modRoot := loaderstate.MainModules.ModRoot(mainModule)
+ for _, mainModule := range ld.MainModules.Versions() {
+ modRoot := ld.MainModules.ModRoot(mainModule)
if modRoot != "" {
- dir, mainOK, err := dirInModule(path, loaderstate.MainModules.PathPrefix(mainModule), modRoot, true)
+ dir, mainOK, err := dirInModule(path, ld.MainModules.PathPrefix(mainModule), modRoot, true)
if mainErr == nil {
mainErr = err
}
@@ -341,8 +341,8 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
}
}
- if loaderstate.HasModRoot() {
- vendorDir := VendorDir(loaderstate)
+ if ld.HasModRoot() {
+ vendorDir := VendorDir(ld)
dir, inVendorDir, _ := dirInModule(path, "", vendorDir, false)
if inVendorDir {
readVendorList(vendorDir)
@@ -350,13 +350,13 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
// vendor/modules.txt does not exist or the user manually added directories to the vendor directory.
// Go 1.23 and later require vendored packages to be present in modules.txt to be imported.
_, ok := vendorPkgModule[path]
- if ok || (gover.Compare(loaderstate.MainModules.GoVersion(loaderstate), gover.ExplicitModulesTxtImportVersion) < 0) {
+ if ok || (gover.Compare(ld.MainModules.GoVersion(ld), gover.ExplicitModulesTxtImportVersion) < 0) {
mods = append(mods, vendorPkgModule[path])
dirs = append(dirs, dir)
roots = append(roots, vendorDir)
} else {
subCommand := "mod"
- if loaderstate.inWorkspaceMode() {
+ if ld.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)
@@ -375,8 +375,8 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
if len(mods) == 0 {
return module.Version{}, "", "", nil, &ImportMissingError{
Path: path,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
@@ -408,7 +408,7 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
ok bool
)
if mg == nil {
- v, ok = rs.rootSelected(loaderstate, prefix)
+ v, ok = rs.rootSelected(ld, prefix)
} else {
v, ok = mg.Selected(prefix), true
}
@@ -417,7 +417,7 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
}
m := module.Version{Path: prefix, Version: v}
- root, isLocal, err := fetch(loaderstate, ctx, m)
+ root, isLocal, err := fetch(ld, ctx, m)
if err != nil {
if _, ok := errors.AsType[*sumMissingError](err); ok {
// We are missing a sum needed to fetch a module in the build list.
@@ -480,8 +480,8 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
// If the module graph is pruned and this is a test-only dependency
// of a package in "all", we didn't necessarily load that file
// when we read the module graph, so do it now to be sure.
- if !skipModFile && cfg.BuildMod != "vendor" && mods[0].Path != "" && !loaderstate.MainModules.Contains(mods[0].Path) {
- if _, err := goModSummary(loaderstate, mods[0]); err != nil {
+ if !skipModFile && cfg.BuildMod != "vendor" && mods[0].Path != "" && !ld.MainModules.Contains(mods[0].Path) {
+ if _, err := goModSummary(ld, mods[0]); err != nil {
return module.Version{}, "", "", nil, err
}
}
@@ -492,21 +492,21 @@ 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 !loaderstate.HasModRoot() {
- queryErr = NewNoMainModulesError(loaderstate)
+ if !ld.HasModRoot() {
+ queryErr = NewNoMainModulesError(ld)
}
return module.Version{}, "", "", nil, &ImportMissingError{
Path: path,
QueryErr: queryErr,
isStd: pathIsStd,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
// So far we've checked the root dependencies.
// Load the full module graph and try again.
- mg, err = rs.Graph(loaderstate, ctx)
+ mg, err = rs.Graph(ld, ctx)
if err != nil {
// We might be missing one or more transitive (implicit) dependencies from
// the module graph, so we can't return an ImportMissingError here — one
@@ -522,12 +522,12 @@ func importFromModules(loaderstate *State, ctx context.Context, path string, rs
//
// Unlike QueryPattern, queryImport prefers to add a replaced version of a
// module *before* checking the proxies for a version to add.
-func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requirements) (module.Version, error) {
+func queryImport(ld *Loader, ctx context.Context, path string, rs *Requirements) (module.Version, error) {
// To avoid spurious remote fetches, try the latest replacement for each
// module (golang.org/issue/26241).
var mods []module.Version
- if loaderstate.MainModules != nil { // TODO(#48912): Ensure MainModules exists at this point, and remove the check.
- for mp, mv := range loaderstate.MainModules.HighestReplaced() {
+ if ld.MainModules != nil { // TODO(#48912): Ensure MainModules exists at this point, and remove the check.
+ for mp, mv := range ld.MainModules.HighestReplaced() {
if !maybeInModule(path, mp) {
continue
}
@@ -543,7 +543,7 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
mv = module.ZeroPseudoVersion("v0")
}
}
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
return module.Version{}, err
}
@@ -562,7 +562,7 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
return len(mods[i].Path) > len(mods[j].Path)
})
for _, m := range mods {
- root, isLocal, err := fetch(loaderstate, ctx, m)
+ root, isLocal, err := fetch(ld, ctx, m)
if err != nil {
if _, ok := errors.AsType[*sumMissingError](err); ok {
return module.Version{}, &ImportMissingSumError{importPath: path}
@@ -576,8 +576,8 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
return module.Version{}, &ImportMissingError{
Path: path,
replaced: m,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
return m, nil
@@ -587,7 +587,7 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
// The package path is not valid to fetch remotely,
// so it can only exist in a replaced module,
// and we know from the above loop that it is not.
- replacement := Replacement(loaderstate, mods[0])
+ replacement := Replacement(ld, mods[0])
return module.Version{}, &PackageNotInModuleError{
Mod: mods[0],
Query: "latest",
@@ -607,12 +607,12 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
return module.Version{}, &ImportMissingError{
Path: path,
isStd: true,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
- if (cfg.BuildMod == "readonly" || cfg.BuildMod == "vendor") && !loaderstate.allowMissingModuleImports {
+ if (cfg.BuildMod == "readonly" || cfg.BuildMod == "vendor") && !ld.allowMissingModuleImports {
// In readonly mode, we can't write go.mod, so we shouldn't try to look up
// the module. If readonly mode was enabled explicitly, include that in
// the error message.
@@ -627,8 +627,8 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
return module.Version{}, &ImportMissingError{
Path: path,
QueryErr: queryErr,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
@@ -637,12 +637,12 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
// and return m, dir, ImportMissingError.
fmt.Fprintf(os.Stderr, "go: finding module for package %s\n", path)
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
return module.Version{}, err
}
- candidates, err := QueryPackages(loaderstate, ctx, path, "latest", mg.Selected, loaderstate.CheckAllowed)
+ candidates, err := QueryPackages(ld, ctx, path, "latest", mg.Selected, ld.CheckAllowed)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// Return "cannot find module providing package […]" instead of whatever
@@ -650,8 +650,8 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
return module.Version{}, &ImportMissingError{
Path: path,
QueryErr: err,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
} else {
return module.Version{}, err
@@ -680,8 +680,8 @@ func queryImport(loaderstate *State, ctx context.Context, path string, rs *Requi
Path: path,
Module: candidates[0].Mod,
newMissingVersion: candidate0MissingVersion,
- modContainingCWD: loaderstate.MainModules.ModContainingCWD(),
- allowMissingModuleImports: loaderstate.allowMissingModuleImports,
+ modContainingCWD: ld.MainModules.ModContainingCWD(),
+ allowMissingModuleImports: ld.allowMissingModuleImports,
}
}
@@ -784,15 +784,15 @@ func dirInModule(path, mpath, mdir string, isLocal bool) (dir string, haveGoFile
//
// The isLocal return value reports whether the replacement,
// if any, is local to the filesystem.
-func fetch(loaderstate *State, ctx context.Context, mod module.Version) (dir string, isLocal bool, err error) {
- if modRoot := loaderstate.MainModules.ModRoot(mod); modRoot != "" {
+func fetch(ld *Loader, ctx context.Context, mod module.Version) (dir string, isLocal bool, err error) {
+ if modRoot := ld.MainModules.ModRoot(mod); modRoot != "" {
return modRoot, true, nil
}
- if r := Replacement(loaderstate, mod); r.Path != "" {
+ if r := Replacement(ld, mod); r.Path != "" {
if r.Version == "" {
dir = r.Path
if !filepath.IsAbs(dir) {
- dir = filepath.Join(replaceRelativeTo(loaderstate), dir)
+ dir = filepath.Join(replaceRelativeTo(ld), dir)
}
// Ensure that the replacement directory actually exists:
// dirInModule does not report errors for missing modules,
@@ -817,18 +817,18 @@ func fetch(loaderstate *State, ctx context.Context, mod module.Version) (dir str
mod = r
}
- if mustHaveSums(loaderstate) && !modfetch.HaveSum(loaderstate.Fetcher(), mod) {
+ if mustHaveSums(ld) && !modfetch.HaveSum(ld.Fetcher(), mod) {
return "", false, module.VersionError(mod, &sumMissingError{})
}
- dir, err = loaderstate.Fetcher().Download(ctx, mod)
+ dir, err = ld.Fetcher().Download(ctx, mod)
return dir, false, err
}
// 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 loaderstate.HasModRoot() && cfg.BuildMod == "readonly" && !loaderstate.inWorkspaceMode()
+func mustHaveSums(ld *Loader) bool {
+ return ld.HasModRoot() && cfg.BuildMod == "readonly" && !ld.inWorkspaceMode()
}
type sumMissingError struct {
diff --git a/src/cmd/go/internal/modload/import_test.go b/src/cmd/go/internal/modload/import_test.go
index 820fb87b59..5dd9890de0 100644
--- a/src/cmd/go/internal/modload/import_test.go
+++ b/src/cmd/go/internal/modload/import_test.go
@@ -56,20 +56,20 @@ var importTests = []struct {
}
func TestQueryImport(t *testing.T) {
- loaderstate := NewState()
- loaderstate.RootMode = NoRoot
- loaderstate.AllowMissingModuleImports()
+ ld := NewLoader()
+ ld.RootMode = NoRoot
+ ld.AllowMissingModuleImports()
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExecPath(t, "git")
ctx := context.Background()
- rs := LoadModFile(loaderstate, ctx)
+ rs := LoadModFile(ld, ctx)
for _, tt := range importTests {
t.Run(strings.ReplaceAll(tt.path, "/", "_"), func(t *testing.T) {
// Note that there is no build list, so Import should always fail.
- m, err := queryImport(loaderstate, ctx, tt.path, rs)
+ m, err := queryImport(ld, ctx, tt.path, rs)
if tt.err == "" {
if err != nil {
diff --git a/src/cmd/go/internal/modload/init.go b/src/cmd/go/internal/modload/init.go
index 65daa8a26c..f44b67b510 100644
--- a/src/cmd/go/internal/modload/init.go
+++ b/src/cmd/go/internal/modload/init.go
@@ -56,43 +56,43 @@ var (
)
// EnterModule resets MainModules and requirements to refer to just this one module.
-func EnterModule(loaderstate *State, ctx context.Context, enterModroot string) {
- loaderstate.MainModules = nil // reset MainModules
- loaderstate.requirements = nil
- loaderstate.workFilePath = "" // Force module mode
- loaderstate.Fetcher().Reset()
+func EnterModule(ld *Loader, ctx context.Context, enterModroot string) {
+ ld.MainModules = nil // reset MainModules
+ ld.requirements = nil
+ ld.workFilePath = "" // Force module mode
+ ld.Fetcher().Reset()
- loaderstate.modRoots = []string{enterModroot}
- LoadModFile(loaderstate, ctx)
+ ld.modRoots = []string{enterModroot}
+ LoadModFile(ld, ctx)
}
// EnterWorkspace enters workspace mode from module mode, applying the updated requirements to the main
// module to that module in the workspace. There should be no calls to any of the exported
// functions of the modload package running concurrently with a call to EnterWorkspace as
// EnterWorkspace will modify the global state they depend on in a non-thread-safe way.
-func EnterWorkspace(loaderstate *State, ctx context.Context) (exit func(), err error) {
+func EnterWorkspace(ld *Loader, ctx context.Context) (exit func(), err error) {
// Find the identity of the main module that will be updated before we reset modload state.
- mm := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
+ mm := ld.MainModules.mustGetSingleMainModule(ld)
// Get the updated modfile we will use for that module.
- _, _, updatedmodfile, err := UpdateGoModFromReqs(loaderstate, ctx, WriteOpts{})
+ _, _, updatedmodfile, err := UpdateGoModFromReqs(ld, ctx, WriteOpts{})
if err != nil {
return nil, err
}
// Reset the state to a clean state.
- oldstate := loaderstate.setState(NewState())
- loaderstate.ForceUseModules = true
+ oldstate := ld.setState(NewLoader())
+ ld.ForceUseModules = true
// Load in workspace mode.
- loaderstate.InitWorkfile()
- LoadModFile(loaderstate, ctx)
+ ld.InitWorkfile()
+ LoadModFile(ld, ctx)
// Update the content of the previous main module, and recompute the requirements.
- *loaderstate.MainModules.ModFile(mm) = *updatedmodfile
- loaderstate.requirements = requirementsFromModFiles(loaderstate, ctx, loaderstate.MainModules.workFile, slices.Collect(maps.Values(loaderstate.MainModules.modFiles)), nil)
+ *ld.MainModules.ModFile(mm) = *updatedmodfile
+ ld.requirements = requirementsFromModFiles(ld, ctx, ld.MainModules.workFile, slices.Collect(maps.Values(ld.MainModules.modFiles)), nil)
return func() {
- loaderstate.setState(oldstate)
+ ld.setState(oldstate)
}, nil
}
@@ -181,20 +181,20 @@ func (mms *MainModuleSet) InGorootSrc(m module.Version) bool {
return mms.inGorootSrc[m]
}
-func (mms *MainModuleSet) mustGetSingleMainModule(loaderstate *State) module.Version {
- mm, err := mms.getSingleMainModule(loaderstate)
+func (mms *MainModuleSet) mustGetSingleMainModule(ld *Loader) module.Version {
+ mm, err := mms.getSingleMainModule(ld)
if err != nil {
panic(err)
}
return mm
}
-func (mms *MainModuleSet) getSingleMainModule(loaderstate *State) (module.Version, error) {
+func (mms *MainModuleSet) getSingleMainModule(ld *Loader) (module.Version, error) {
if mms == nil || len(mms.versions) == 0 {
return module.Version{}, errors.New("internal error: mustGetSingleMainModule called in context with no main modules")
}
if len(mms.versions) != 1 {
- if loaderstate.inWorkspaceMode() {
+ if ld.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")
@@ -203,14 +203,14 @@ func (mms *MainModuleSet) getSingleMainModule(loaderstate *State) (module.Versio
return mms.versions[0], nil
}
-func (mms *MainModuleSet) GetSingleIndexOrNil(loaderstate *State) *modFileIndex {
+func (mms *MainModuleSet) GetSingleIndexOrNil(ld *Loader) *modFileIndex {
if mms == nil {
return nil
}
if len(mms.versions) == 0 {
return nil
}
- return mms.indices[mms.mustGetSingleMainModule(loaderstate)]
+ return mms.indices[mms.mustGetSingleMainModule(ld)]
}
func (mms *MainModuleSet) Index(m module.Version) *modFileIndex {
@@ -253,12 +253,12 @@ 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 loaderstate.inWorkspaceMode() {
+func (mms *MainModuleSet) GoVersion(ld *Loader) string {
+ if ld.inWorkspaceMode() {
return gover.FromGoWork(mms.workFile)
}
if mms != nil && len(mms.versions) == 1 {
- f := mms.ModFile(mms.mustGetSingleMainModule(loaderstate))
+ f := mms.ModFile(mms.mustGetSingleMainModule(ld))
if f == nil {
// Special case: we are outside a module, like 'go run x.go'.
// Assume the local Go version.
@@ -273,15 +273,15 @@ func (mms *MainModuleSet) GoVersion(loaderstate *State) string {
// Godebugs returns the godebug lines set on the single module, in module mode,
// 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 loaderstate.inWorkspaceMode() {
+func (mms *MainModuleSet) Godebugs(ld *Loader) []*modfile.Godebug {
+ if ld.inWorkspaceMode() {
if mms.workFile != nil {
return mms.workFile.Godebug
}
return nil
}
if mms != nil && len(mms.versions) == 1 {
- f := mms.ModFile(mms.mustGetSingleMainModule(loaderstate))
+ f := mms.ModFile(mms.mustGetSingleMainModule(ld))
if f == nil {
// Special case: we are outside a module, like 'go run x.go'.
return nil
@@ -321,17 +321,17 @@ const (
// 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 ModFile(loaderstate *State) *modfile.File {
- Init(loaderstate)
- modFile := loaderstate.MainModules.ModFile(loaderstate.MainModules.mustGetSingleMainModule(loaderstate))
+func ModFile(ld *Loader) *modfile.File {
+ Init(ld)
+ modFile := ld.MainModules.ModFile(ld.MainModules.mustGetSingleMainModule(ld))
if modFile == nil {
- die(loaderstate)
+ die(ld)
}
return modFile
}
-func BinDir(loaderstate *State) string {
- Init(loaderstate)
+func BinDir(ld *Loader) string {
+ Init(ld)
if cfg.GOBIN != "" {
return cfg.GOBIN
}
@@ -344,13 +344,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 (loaderstate *State) InitWorkfile() {
+func (ld *Loader) 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 = loaderstate.FindGoWork(base.Cwd())
+ ld.workFilePath = ld.FindGoWork(base.Cwd())
}
// FindGoWork returns the name of the go.work file for this command,
@@ -358,8 +358,8 @@ func (loaderstate *State) InitWorkfile() {
// 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 (loaderstate *State) FindGoWork(wd string) string {
- if loaderstate.RootMode == NoRoot {
+func (ld *Loader) FindGoWork(wd string) string {
+ if ld.RootMode == NoRoot {
return ""
}
@@ -378,45 +378,45 @@ func (loaderstate *State) FindGoWork(wd string) string {
// WorkFilePath returns the absolute path of the go.work file, or "" if not in
// workspace mode. WorkFilePath must be called after InitWorkfile.
-func WorkFilePath(loaderstate *State) string {
- return loaderstate.workFilePath
+func WorkFilePath(ld *Loader) string {
+ return ld.workFilePath
}
// Reset clears all the initialized, cached state about the use of modules,
// so that we can start over.
-func (s *State) Reset() {
- s.setState(NewState())
+func (ld *Loader) Reset() {
+ ld.setState(NewLoader())
}
-func (s *State) setState(new *State) (old *State) {
- old = &State{
- initialized: s.initialized,
- ForceUseModules: s.ForceUseModules,
- RootMode: s.RootMode,
- modRoots: s.modRoots,
+func (ld *Loader) setState(new *Loader) (old *Loader) {
+ old = &Loader{
+ initialized: ld.initialized,
+ ForceUseModules: ld.ForceUseModules,
+ RootMode: ld.RootMode,
+ modRoots: ld.modRoots,
modulesEnabled: cfg.ModulesEnabled,
- MainModules: s.MainModules,
- requirements: s.requirements,
- workFilePath: s.workFilePath,
- fetcher: s.fetcher,
+ MainModules: ld.MainModules,
+ requirements: ld.requirements,
+ workFilePath: ld.workFilePath,
+ fetcher: ld.fetcher,
}
- s.initialized = new.initialized
- s.ForceUseModules = new.ForceUseModules
- s.RootMode = new.RootMode
- s.modRoots = new.modRoots
+ ld.initialized = new.initialized
+ ld.ForceUseModules = new.ForceUseModules
+ ld.RootMode = new.RootMode
+ ld.modRoots = new.modRoots
cfg.ModulesEnabled = new.modulesEnabled
- s.MainModules = new.MainModules
- s.requirements = new.requirements
- s.workFilePath = new.workFilePath
+ ld.MainModules = new.MainModules
+ ld.requirements = new.requirements
+ ld.workFilePath = new.workFilePath
// The modfetch package's global state is used to compute
// the go.sum file, so save and restore it along with the
// modload state.
- old.fetcher = s.fetcher.SetState(new.fetcher)
+ old.fetcher = ld.fetcher.SetState(new.fetcher)
return old
}
-type State struct {
+type Loader struct {
initialized bool
allowMissingModuleImports bool
@@ -462,30 +462,30 @@ type State struct {
fetcher *modfetch.Fetcher
}
-func NewState() *State {
- s := new(State)
+func NewLoader() *Loader {
+ s := new(Loader)
s.fetcher = modfetch.NewFetcher()
return s
}
-func NewDisabledState() *State {
+func NewDisabledState() *Loader {
fips140.Init()
- return &State{initialized: true, modulesEnabled: false}
+ return &Loader{initialized: true, modulesEnabled: false}
}
-func (s *State) Fetcher() *modfetch.Fetcher {
- return s.fetcher
+func (ld *Loader) Fetcher() *modfetch.Fetcher {
+ return ld.fetcher
}
// 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 Init(loaderstate *State) {
- if loaderstate.initialized {
+func Init(ld *Loader) {
+ if ld.initialized {
return
}
- loaderstate.initialized = true
+ ld.initialized = true
fips140.Init()
@@ -498,11 +498,11 @@ func Init(loaderstate *State) {
default:
base.Fatalf("go: unknown environment setting GO111MODULE=%s", env)
case "auto":
- mustUseModules = loaderstate.ForceUseModules
+ mustUseModules = ld.ForceUseModules
case "on", "":
mustUseModules = true
case "off":
- if loaderstate.ForceUseModules {
+ if ld.ForceUseModules {
base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
}
mustUseModules = false
@@ -526,15 +526,15 @@ func Init(loaderstate *State) {
if os.Getenv("GCM_INTERACTIVE") == "" {
os.Setenv("GCM_INTERACTIVE", "never")
}
- if loaderstate.modRoots != nil {
+ if ld.modRoots != nil {
// modRoot set before Init was called ("go mod init" does this).
// No need to search for go.mod.
- } else if loaderstate.RootMode == NoRoot {
+ } else if ld.RootMode == NoRoot {
if cfg.ModFile != "" && !base.InGOFLAGS("-modfile") {
base.Fatalf("go: -modfile cannot be used with commands that ignore the current module")
}
- loaderstate.modRoots = nil
- } else if loaderstate.workFilePath != "" {
+ ld.modRoots = nil
+ } else if ld.workFilePath != "" {
// We're in workspace mode, which implies module mode.
if cfg.ModFile != "" {
base.Fatalf("go: -modfile cannot be used in workspace mode")
@@ -544,8 +544,8 @@ func Init(loaderstate *State) {
if cfg.ModFile != "" {
base.Fatalf("go: cannot find main module, but -modfile was set.\n\t-modfile cannot be used to set the module root directory.")
}
- if loaderstate.RootMode == NeedRoot {
- base.Fatal(NewNoMainModulesError(loaderstate))
+ if ld.RootMode == NeedRoot {
+ base.Fatal(NewNoMainModulesError(ld))
}
if !mustUseModules {
// GO111MODULE is 'auto', and we can't find a module root.
@@ -559,14 +559,14 @@ func Init(loaderstate *State) {
// It's a bit of a peculiar thing to disallow but quite mysterious
// when it happens. See golang.org/issue/26708.
fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in system temp root %v\n", os.TempDir())
- if loaderstate.RootMode == NeedRoot {
- base.Fatal(NewNoMainModulesError(loaderstate))
+ if ld.RootMode == NeedRoot {
+ base.Fatal(NewNoMainModulesError(ld))
}
if !mustUseModules {
return
}
} else {
- loaderstate.modRoots = []string{modRoot}
+ ld.modRoots = []string{modRoot}
}
}
if cfg.ModFile != "" && !strings.HasSuffix(cfg.ModFile, ".mod") {
@@ -575,14 +575,14 @@ func Init(loaderstate *State) {
// We're in module mode. Set any global variables that need to be set.
cfg.ModulesEnabled = true
- setDefaultBuildMod(loaderstate)
+ setDefaultBuildMod(ld)
list := filepath.SplitList(cfg.BuildContext.GOPATH)
if len(list) > 0 && list[0] != "" {
gopath = list[0]
if _, err := fsys.Stat(filepath.Join(gopath, "go.mod")); err == nil {
fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in $GOPATH %v\n", gopath)
- if loaderstate.RootMode == NeedRoot {
- base.Fatal(NewNoMainModulesError(loaderstate))
+ if ld.RootMode == NeedRoot {
+ base.Fatal(NewNoMainModulesError(ld))
}
if !mustUseModules {
return
@@ -600,12 +600,12 @@ 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 (loaderstate *State) WillBeEnabled() bool {
- if loaderstate.modRoots != nil || cfg.ModulesEnabled {
+func (ld *Loader) WillBeEnabled() bool {
+ if ld.modRoots != nil || cfg.ModulesEnabled {
// Already enabled.
return true
}
- if loaderstate.initialized {
+ if ld.initialized {
// Initialized, not enabled.
return false
}
@@ -622,7 +622,7 @@ func (loaderstate *State) WillBeEnabled() bool {
return false
}
- return FindGoMod(base.Cwd()) != "" || loaderstate.FindGoWork(base.Cwd()) != ""
+ return FindGoMod(base.Cwd()) != "" || ld.FindGoWork(base.Cwd()) != ""
}
// FindGoMod returns the name of the go.mod file for this command,
@@ -652,77 +652,77 @@ 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 (loaderstate *State) Enabled() bool {
- Init(loaderstate)
- return loaderstate.modRoots != nil || cfg.ModulesEnabled
+func (ld *Loader) Enabled() bool {
+ Init(ld)
+ return ld.modRoots != nil || cfg.ModulesEnabled
}
-func (s *State) vendorDir() (string, error) {
- if s.inWorkspaceMode() {
- return filepath.Join(filepath.Dir(WorkFilePath(s)), "vendor"), nil
+func (ld *Loader) vendorDir() (string, error) {
+ if ld.inWorkspaceMode() {
+ return filepath.Join(filepath.Dir(WorkFilePath(ld)), "vendor"), nil
}
- mainModule, err := s.MainModules.getSingleMainModule(s)
+ mainModule, err := ld.MainModules.getSingleMainModule(ld)
if err != nil {
return "", err
}
// Even if -mod=vendor, we could be operating with no mod root (and thus no
// vendor directory). As long as there are no dependencies that is expected
// to work. See script/vendor_outside_module.txt.
- modRoot := s.MainModules.ModRoot(mainModule)
+ modRoot := ld.MainModules.ModRoot(mainModule)
if modRoot == "" {
return "", errors.New("vendor directory does not exist when in single module mode outside of a module")
}
return filepath.Join(modRoot, "vendor"), nil
}
-func (s *State) VendorDirOrEmpty() string {
- dir, err := s.vendorDir()
+func (ld *Loader) VendorDirOrEmpty() string {
+ dir, err := ld.vendorDir()
if err != nil {
return ""
}
return dir
}
-func VendorDir(loaderstate *State) string {
- dir, err := loaderstate.vendorDir()
+func VendorDir(ld *Loader) string {
+ dir, err := ld.vendorDir()
if err != nil {
panic(err)
}
return dir
}
-func (loaderstate *State) inWorkspaceMode() bool {
- if !loaderstate.initialized {
+func (ld *Loader) inWorkspaceMode() bool {
+ if !ld.initialized {
panic("inWorkspaceMode called before modload.Init called")
}
- if !loaderstate.Enabled() {
+ if !ld.Enabled() {
return false
}
- return loaderstate.workFilePath != ""
+ return ld.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 (loaderstate *State) HasModRoot() bool {
- Init(loaderstate)
- return loaderstate.modRoots != nil
+func (ld *Loader) HasModRoot() bool {
+ Init(ld)
+ return ld.modRoots != nil
}
// MustHaveModRoot checks that a main module or main modules are present,
// and calls base.Fatalf if there are no main modules.
-func (loaderstate *State) MustHaveModRoot() {
- Init(loaderstate)
- if !loaderstate.HasModRoot() {
- die(loaderstate)
+func (ld *Loader) MustHaveModRoot() {
+ Init(ld)
+ if !ld.HasModRoot() {
+ die(ld)
}
}
// 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 (loaderstate *State) ModFilePath() string {
- loaderstate.MustHaveModRoot()
+func (ld *Loader) ModFilePath() string {
+ ld.MustHaveModRoot()
return modFilePath(findModuleRoot(base.Cwd()))
}
@@ -736,11 +736,11 @@ func modFilePath(modRoot string) string {
return filepath.Join(modRoot, "go.mod")
}
-func die(loaderstate *State) {
+func die(ld *Loader) {
if cfg.Getenv("GO111MODULE") == "off" {
base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
}
- if !loaderstate.inWorkspaceMode() {
+ if !ld.inWorkspaceMode() {
if dir, name := findAltConfig(base.Cwd()); dir != "" {
rel, err := filepath.Rel(base.Cwd(), dir)
if err != nil {
@@ -753,7 +753,7 @@ func die(loaderstate *State) {
base.Fatalf("go: cannot find main module, but found %s in %s\n\tto create a module there, run:\n\t%sgo mod init", name, dir, cdCmd)
}
}
- base.Fatal(NewNoMainModulesError(loaderstate))
+ base.Fatal(NewNoMainModulesError(ld))
}
var ErrNoModRoot = errors.New("no module root")
@@ -775,9 +775,9 @@ func (e noMainModulesError) Unwrap() error {
return ErrNoModRoot
}
-func NewNoMainModulesError(s *State) noMainModulesError {
+func NewNoMainModulesError(ld *Loader) noMainModulesError {
return noMainModulesError{
- inWorkspaceMode: s.inWorkspaceMode(),
+ inWorkspaceMode: ld.inWorkspaceMode(),
}
}
@@ -930,33 +930,33 @@ func UpdateWorkFile(wf *modfile.WorkFile) {
// 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 LoadModFile(loaderstate *State, ctx context.Context) *Requirements {
- rs, err := loadModFile(loaderstate, ctx, nil)
+func LoadModFile(ld *Loader, ctx context.Context) *Requirements {
+ rs, err := loadModFile(ld, ctx, nil)
if err != nil {
base.Fatal(err)
}
return rs
}
-func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*Requirements, error) {
- if loaderstate.requirements != nil {
- return loaderstate.requirements, nil
+func loadModFile(ld *Loader, ctx context.Context, opts *PackageOpts) (*Requirements, error) {
+ if ld.requirements != nil {
+ return ld.requirements, nil
}
- Init(loaderstate)
+ Init(ld)
var workFile *modfile.WorkFile
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
var err error
- workFile, loaderstate.modRoots, err = LoadWorkFile(loaderstate.workFilePath)
+ workFile, ld.modRoots, err = LoadWorkFile(ld.workFilePath)
if err != nil {
return nil, err
}
- for _, modRoot := range loaderstate.modRoots {
+ for _, modRoot := range ld.modRoots {
sumFile := strings.TrimSuffix(modFilePath(modRoot), ".mod") + ".sum"
- loaderstate.Fetcher().AddWorkspaceGoSumFile(sumFile)
+ ld.Fetcher().AddWorkspaceGoSumFile(sumFile)
}
- loaderstate.Fetcher().SetGoSumFile(loaderstate.workFilePath + ".sum")
- } else if len(loaderstate.modRoots) == 0 {
+ ld.Fetcher().SetGoSumFile(ld.workFilePath + ".sum")
+ } else if len(ld.modRoots) == 0 {
// We're in module mode, but not inside a module.
//
// Commands like 'go build', 'go run', 'go list' have no go.mod file to
@@ -975,25 +975,25 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
//
// See golang.org/issue/32027.
} else {
- loaderstate.Fetcher().SetGoSumFile(strings.TrimSuffix(modFilePath(loaderstate.modRoots[0]), ".mod") + ".sum")
+ ld.Fetcher().SetGoSumFile(strings.TrimSuffix(modFilePath(ld.modRoots[0]), ".mod") + ".sum")
}
- if len(loaderstate.modRoots) == 0 {
+ if len(ld.modRoots) == 0 {
// TODO(#49228): Instead of creating a fake module with an empty modroot,
// make MainModules.Len() == 0 mean that we're in module mode but not inside
// any module.
mainModule := module.Version{Path: "command-line-arguments"}
- loaderstate.MainModules = makeMainModules(loaderstate, []module.Version{mainModule}, []string{""}, []*modfile.File{nil}, []*modFileIndex{nil}, nil)
+ ld.MainModules = makeMainModules(ld, []module.Version{mainModule}, []string{""}, []*modfile.File{nil}, []*modFileIndex{nil}, nil)
var (
goVersion string
pruning modPruning
roots []module.Version
direct = map[string]bool{"go": true}
)
- if loaderstate.inWorkspaceMode() {
+ if ld.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.
- goVersion = loaderstate.MainModules.GoVersion(loaderstate)
+ goVersion = ld.MainModules.GoVersion(ld)
pruning = workspace
roots = []module.Version{
mainModule,
@@ -1009,26 +1009,26 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
}
}
rawGoVersion.Store(mainModule, goVersion)
- loaderstate.requirements = newRequirements(loaderstate, pruning, roots, direct)
+ ld.requirements = newRequirements(ld, pruning, roots, direct)
if cfg.BuildMod == "vendor" {
// For issue 56536: Some users may have GOFLAGS=-mod=vendor set.
// Make sure it behaves as though the fake module is vendored
// with no dependencies.
- loaderstate.requirements.initVendor(loaderstate, nil)
+ ld.requirements.initVendor(ld, nil)
}
- return loaderstate.requirements, nil
+ return ld.requirements, nil
}
var modFiles []*modfile.File
var mainModules []module.Version
var indices []*modFileIndex
var errs []error
- for _, modroot := range loaderstate.modRoots {
+ for _, modroot := range ld.modRoots {
gomod := modFilePath(modroot)
var fixed bool
- data, f, err := ReadModFile(gomod, fixVersion(loaderstate, ctx, &fixed))
+ data, f, err := ReadModFile(gomod, fixVersion(ld, ctx, &fixed))
if err != nil {
- if loaderstate.inWorkspaceMode() {
+ if ld.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'
@@ -1043,7 +1043,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
errs = append(errs, err)
continue
}
- if loaderstate.inWorkspaceMode() && !strings.HasPrefix(cfg.CmdName, "work ") {
+ if ld.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.
@@ -1055,7 +1055,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
}
}
- if !loaderstate.inWorkspaceMode() {
+ if !ld.inWorkspaceMode() {
ok := true
for _, g := range f.Godebug {
if err := CheckGodebug("godebug", g.Key, g.Value); err != nil {
@@ -1084,45 +1084,45 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
return nil, errors.Join(errs...)
}
- loaderstate.MainModules = makeMainModules(loaderstate, mainModules, loaderstate.modRoots, modFiles, indices, workFile)
- setDefaultBuildMod(loaderstate) // possibly enable automatic vendoring
- rs := requirementsFromModFiles(loaderstate, ctx, workFile, modFiles, opts)
+ ld.MainModules = makeMainModules(ld, mainModules, ld.modRoots, modFiles, indices, workFile)
+ setDefaultBuildMod(ld) // possibly enable automatic vendoring
+ rs := requirementsFromModFiles(ld, ctx, workFile, modFiles, opts)
if cfg.BuildMod == "vendor" {
- readVendorList(VendorDir(loaderstate))
- versions := loaderstate.MainModules.Versions()
+ readVendorList(VendorDir(ld))
+ versions := ld.MainModules.Versions()
indexes := make([]*modFileIndex, 0, len(versions))
modFiles := make([]*modfile.File, 0, len(versions))
modRoots := make([]string, 0, len(versions))
for _, m := range versions {
- indexes = append(indexes, loaderstate.MainModules.Index(m))
- modFiles = append(modFiles, loaderstate.MainModules.ModFile(m))
- modRoots = append(modRoots, loaderstate.MainModules.ModRoot(m))
+ indexes = append(indexes, ld.MainModules.Index(m))
+ modFiles = append(modFiles, ld.MainModules.ModFile(m))
+ modRoots = append(modRoots, ld.MainModules.ModRoot(m))
}
- checkVendorConsistency(loaderstate, indexes, modFiles, modRoots)
- rs.initVendor(loaderstate, vendorList)
+ checkVendorConsistency(ld, indexes, modFiles, modRoots)
+ rs.initVendor(ld, vendorList)
}
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
// We don't need to update the mod file so return early.
- loaderstate.requirements = rs
+ ld.requirements = rs
return rs, nil
}
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
- if rs.hasRedundantRoot(loaderstate) {
+ if rs.hasRedundantRoot(ld) {
// If any module path appears more than once in the roots, we know that the
// go.mod file needs to be updated even though we have not yet loaded any
// transitive dependencies.
var err error
- rs, err = updateRoots(loaderstate, ctx, rs.direct, rs, nil, nil, false)
+ rs, err = updateRoots(ld, ctx, rs.direct, rs, nil, nil, false)
if err != nil {
return nil, err
}
}
- if loaderstate.MainModules.Index(mainModule).goVersion == "" && rs.pruning != workspace {
+ if ld.MainModules.Index(mainModule).goVersion == "" && rs.pruning != workspace {
// TODO(#45551): Do something more principled instead of checking
// cfg.CmdName directly here.
if cfg.BuildMod == "mod" && cfg.CmdName != "mod graph" && cfg.CmdName != "mod why" {
@@ -1131,8 +1131,8 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
if opts != nil && opts.TidyGoVersion != "" {
v = opts.TidyGoVersion
}
- addGoStmt(loaderstate.MainModules.ModFile(mainModule), mainModule, v)
- rs = overrideRoots(loaderstate, ctx, rs, []module.Version{{Path: "go", Version: v}})
+ addGoStmt(ld.MainModules.ModFile(mainModule), mainModule, v)
+ rs = overrideRoots(ld, ctx, rs, []module.Version{{Path: "go", Version: v}})
// We need to add a 'go' version to the go.mod file, but we must assume
// that its existing contents match something between Go 1.11 and 1.16.
@@ -1141,7 +1141,7 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
// requirements to support pruning.
if gover.Compare(v, gover.ExplicitIndirectVersion) >= 0 {
var err error
- rs, err = convertPruning(loaderstate, ctx, rs, pruned)
+ rs, err = convertPruning(ld, ctx, rs, pruned)
if err != nil {
return nil, err
}
@@ -1151,8 +1151,8 @@ func loadModFile(loaderstate *State, ctx context.Context, opts *PackageOpts) (*R
}
}
- loaderstate.requirements = rs
- return loaderstate.requirements, nil
+ ld.requirements = rs
+ return ld.requirements, nil
}
func errWorkTooOld(gomod string, wf *modfile.WorkFile, goVers string) error {
@@ -1185,10 +1185,10 @@ func CheckReservedModulePath(path string) error {
// 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 CreateModFile(loaderstate *State, ctx context.Context, modPath string) {
+func CreateModFile(ld *Loader, ctx context.Context, modPath string) {
modRoot := base.Cwd()
- loaderstate.modRoots = []string{modRoot}
- Init(loaderstate)
+ ld.modRoots = []string{modRoot}
+ Init(ld)
modFilePath := modFilePath(modRoot)
if _, err := fsys.Stat(modFilePath); err == nil {
base.Fatalf("go: %s already exists", modFilePath)
@@ -1206,16 +1206,16 @@ func CreateModFile(loaderstate *State, ctx context.Context, modPath string) {
fmt.Fprintf(os.Stderr, "go: creating new go.mod: module %s\n", modPath)
modFile := new(modfile.File)
modFile.AddModuleStmt(modPath)
- loaderstate.MainModules = makeMainModules(loaderstate, []module.Version{modFile.Module.Mod}, []string{modRoot}, []*modfile.File{modFile}, []*modFileIndex{nil}, nil)
+ ld.MainModules = makeMainModules(ld, []module.Version{modFile.Module.Mod}, []string{modRoot}, []*modfile.File{modFile}, []*modFileIndex{nil}, nil)
addGoStmt(modFile, modFile.Module.Mod, gover.Local()) // Add the go directive before converted module requirements.
- rs := requirementsFromModFiles(loaderstate, ctx, nil, []*modfile.File{modFile}, nil)
- rs, err := updateRoots(loaderstate, ctx, rs.direct, rs, nil, nil, false)
+ rs := requirementsFromModFiles(ld, ctx, nil, []*modfile.File{modFile}, nil)
+ rs, err := updateRoots(ld, ctx, rs.direct, rs, nil, nil, false)
if err != nil {
base.Fatal(err)
}
- loaderstate.requirements = rs
- if err := commitRequirements(loaderstate, ctx, WriteOpts{}); err != nil {
+ ld.requirements = rs
+ if err := commitRequirements(ld, ctx, WriteOpts{}); err != nil {
base.Fatal(err)
}
@@ -1275,7 +1275,7 @@ func checkModulePath(modPath string) {
// and does nothing for versions that already appear to be canonical.
//
// The VersionFixer sets 'fixed' if it ever returns a non-canonical version.
-func fixVersion(loaderstate *State, ctx context.Context, fixed *bool) modfile.VersionFixer {
+func fixVersion(ld *Loader, ctx context.Context, fixed *bool) modfile.VersionFixer {
return func(path, vers string) (resolved string, err error) {
defer func() {
if err == nil && resolved != vers {
@@ -1308,7 +1308,7 @@ func fixVersion(loaderstate *State, ctx context.Context, fixed *bool) modfile.Ve
return vers, nil
}
- info, err := Query(loaderstate, ctx, path, vers, "", nil)
+ info, err := Query(ld, ctx, path, vers, "", nil)
if err != nil {
return "", err
}
@@ -1323,16 +1323,16 @@ func fixVersion(loaderstate *State, ctx context.Context, fixed *bool) modfile.Ve
//
// This function affects the default cfg.BuildMod when outside of a module,
// so it can only be called prior to Init.
-func (s *State) AllowMissingModuleImports() {
- if s.initialized {
+func (ld *Loader) AllowMissingModuleImports() {
+ if ld.initialized {
panic("AllowMissingModuleImports after Init")
}
- s.allowMissingModuleImports = true
+ ld.allowMissingModuleImports = true
}
// makeMainModules creates a MainModuleSet and associated variables according to
// the given main modules.
-func makeMainModules(loaderstate *State, ms []module.Version, rootDirs []string, modFiles []*modfile.File, indices []*modFileIndex, workFile *modfile.WorkFile) *MainModuleSet {
+func makeMainModules(ld *Loader, ms []module.Version, rootDirs []string, modFiles []*modfile.File, indices []*modFileIndex, workFile *modfile.WorkFile) *MainModuleSet {
for _, m := range ms {
if m.Version != "" {
panic("mainModulesCalled with module.Version with non empty Version field: " + fmt.Sprintf("%#v", m))
@@ -1407,7 +1407,7 @@ func makeMainModules(loaderstate *State, ms []module.Version, rootDirs []string,
continue
}
var newV module.Version = r.New
- if WorkFilePath(loaderstate) != "" && newV.Version == "" && !filepath.IsAbs(newV.Path) {
+ if WorkFilePath(ld) != "" && newV.Version == "" && !filepath.IsAbs(newV.Path) {
// Since we are in a workspace, we may be loading replacements from
// multiple go.mod files. Relative paths in those replacement are
// relative to the go.mod file, not the workspace, so the same string
@@ -1449,14 +1449,14 @@ func makeMainModules(loaderstate *State, ms []module.Version, rootDirs []string,
// requirementsFromModFiles returns the set of non-excluded requirements from
// the global modFile.
-func requirementsFromModFiles(loaderstate *State, ctx context.Context, workFile *modfile.WorkFile, modFiles []*modfile.File, opts *PackageOpts) *Requirements {
+func requirementsFromModFiles(ld *Loader, ctx context.Context, workFile *modfile.WorkFile, modFiles []*modfile.File, opts *PackageOpts) *Requirements {
var roots []module.Version
direct := map[string]bool{}
var pruning modPruning
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
pruning = workspace
- roots = make([]module.Version, len(loaderstate.MainModules.Versions()), 2+len(loaderstate.MainModules.Versions()))
- copy(roots, loaderstate.MainModules.Versions())
+ roots = make([]module.Version, len(ld.MainModules.Versions()), 2+len(ld.MainModules.Versions()))
+ copy(roots, ld.MainModules.Versions())
goVersion := gover.FromGoWork(workFile)
var toolchain string
if workFile.Toolchain != nil {
@@ -1465,16 +1465,16 @@ func requirementsFromModFiles(loaderstate *State, ctx context.Context, workFile
roots = appendGoAndToolchainRoots(roots, goVersion, toolchain, direct)
direct = directRequirements(modFiles)
} else {
- pruning = pruningForGoVersion(loaderstate.MainModules.GoVersion(loaderstate))
+ pruning = pruningForGoVersion(ld.MainModules.GoVersion(ld))
if len(modFiles) != 1 {
panic(fmt.Errorf("requirementsFromModFiles called with %v modfiles outside workspace mode", len(modFiles)))
}
modFile := modFiles[0]
- roots, direct = rootsFromModFile(loaderstate, loaderstate.MainModules.mustGetSingleMainModule(loaderstate), modFile, withToolchainRoot)
+ roots, direct = rootsFromModFile(ld, ld.MainModules.mustGetSingleMainModule(ld), modFile, withToolchainRoot)
}
gover.ModSort(roots)
- rs := newRequirements(loaderstate, pruning, roots, direct)
+ rs := newRequirements(ld, pruning, roots, direct)
return rs
}
@@ -1497,7 +1497,7 @@ func directRequirements(modFiles []*modfile.File) map[string]bool {
return direct
}
-func rootsFromModFile(loaderstate *State, m module.Version, modFile *modfile.File, addToolchainRoot addToolchainRoot) (roots []module.Version, direct map[string]bool) {
+func rootsFromModFile(ld *Loader, m module.Version, modFile *modfile.File, addToolchainRoot addToolchainRoot) (roots []module.Version, direct map[string]bool) {
direct = make(map[string]bool)
padding := 2 // Add padding for the toolchain and go version, added upon return.
if !addToolchainRoot {
@@ -1505,7 +1505,7 @@ func rootsFromModFile(loaderstate *State, m module.Version, modFile *modfile.Fil
}
roots = make([]module.Version, 0, padding+len(modFile.Require))
for _, r := range modFile.Require {
- if index := loaderstate.MainModules.Index(m); index != nil && index.exclude[r.Mod] {
+ if index := ld.MainModules.Index(m); index != nil && index.exclude[r.Mod] {
if cfg.BuildMod == "mod" {
fmt.Fprintf(os.Stderr, "go: dropping requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
} else {
@@ -1546,9 +1546,9 @@ func appendGoAndToolchainRoots(roots []module.Version, goVersion, toolchain stri
// setDefaultBuildMod sets a default value for cfg.BuildMod if the -mod flag
// wasn't provided. setDefaultBuildMod may be called multiple times.
-func setDefaultBuildMod(loaderstate *State) {
+func setDefaultBuildMod(ld *Loader) {
if cfg.BuildModExplicit {
- if loaderstate.inWorkspaceMode() && cfg.BuildMod != "readonly" && cfg.BuildMod != "vendor" {
+ if ld.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
@@ -1583,8 +1583,8 @@ func setDefaultBuildMod(loaderstate *State) {
cfg.BuildMod = "readonly"
return
}
- if loaderstate.modRoots == nil {
- if loaderstate.allowMissingModuleImports {
+ if ld.modRoots == nil {
+ if ld.allowMissingModuleImports {
cfg.BuildMod = "mod"
} else {
cfg.BuildMod = "readonly"
@@ -1592,29 +1592,29 @@ func setDefaultBuildMod(loaderstate *State) {
return
}
- if len(loaderstate.modRoots) >= 1 {
+ if len(ld.modRoots) >= 1 {
var goVersion string
var versionSource string
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
versionSource = "go.work"
- if wfg := loaderstate.MainModules.WorkFile().Go; wfg != nil {
+ if wfg := ld.MainModules.WorkFile().Go; wfg != nil {
goVersion = wfg.Version
}
} else {
versionSource = "go.mod"
- index := loaderstate.MainModules.GetSingleIndexOrNil(loaderstate)
+ index := ld.MainModules.GetSingleIndexOrNil(ld)
if index != nil {
goVersion = index.goVersion
}
}
vendorDir := ""
- if loaderstate.workFilePath != "" {
- vendorDir = filepath.Join(filepath.Dir(loaderstate.workFilePath), "vendor")
+ if ld.workFilePath != "" {
+ vendorDir = filepath.Join(filepath.Dir(ld.workFilePath), "vendor")
} else {
- if len(loaderstate.modRoots) != 1 {
- panic(fmt.Errorf("outside workspace mode, but have %v modRoots", loaderstate.modRoots))
+ if len(ld.modRoots) != 1 {
+ panic(fmt.Errorf("outside workspace mode, but have %v modRoots", ld.modRoots))
}
- vendorDir = filepath.Join(loaderstate.modRoots[0], "vendor")
+ vendorDir = filepath.Join(ld.modRoots[0], "vendor")
}
if fi, err := fsys.Stat(vendorDir); err == nil && fi.IsDir() {
if goVersion != "" {
@@ -1682,8 +1682,8 @@ func modulesTextIsForWorkspace(vendorDir string) (bool, error) {
return false, nil
}
-func mustHaveCompleteRequirements(loaderstate *State) bool {
- return cfg.BuildMod != "mod" && !loaderstate.inWorkspaceMode()
+func mustHaveCompleteRequirements(ld *Loader) bool {
+ return cfg.BuildMod != "mod" && !ld.inWorkspaceMode()
}
// addGoStmt adds a go directive to the go.mod file if it does not already
@@ -1875,22 +1875,22 @@ type WriteOpts struct {
}
// WriteGoMod writes the current build list back to go.mod.
-func WriteGoMod(loaderstate *State, ctx context.Context, opts WriteOpts) error {
- loaderstate.requirements = LoadModFile(loaderstate, ctx)
- return commitRequirements(loaderstate, ctx, opts)
+func WriteGoMod(ld *Loader, ctx context.Context, opts WriteOpts) error {
+ ld.requirements = LoadModFile(ld, ctx)
+ return commitRequirements(ld, ctx, opts)
}
var errNoChange = errors.New("no update needed")
// UpdateGoModFromReqs returns a modified go.mod file using the current
// requirements. It does not commit these changes to disk.
-func UpdateGoModFromReqs(loaderstate *State, ctx context.Context, opts WriteOpts) (before, after []byte, modFile *modfile.File, err error) {
- if loaderstate.MainModules.Len() != 1 || loaderstate.MainModules.ModRoot(loaderstate.MainModules.Versions()[0]) == "" {
+func UpdateGoModFromReqs(ld *Loader, ctx context.Context, opts WriteOpts) (before, after []byte, modFile *modfile.File, err error) {
+ if ld.MainModules.Len() != 1 || ld.MainModules.ModRoot(ld.MainModules.Versions()[0]) == "" {
// We aren't in a module, so we don't have anywhere to write a go.mod file.
return nil, nil, nil, errNoChange
}
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
- modFile = loaderstate.MainModules.ModFile(mainModule)
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
+ modFile = ld.MainModules.ModFile(mainModule)
if modFile == nil {
// command-line-arguments has no .mod file to write.
return nil, nil, nil, errNoChange
@@ -1903,7 +1903,7 @@ func UpdateGoModFromReqs(loaderstate *State, ctx context.Context, opts WriteOpts
var list []*modfile.Require
toolchain := ""
goVersion := ""
- for _, m := range loaderstate.requirements.rootModules {
+ for _, m := range ld.requirements.rootModules {
if m.Path == "go" {
goVersion = m.Version
continue
@@ -1914,7 +1914,7 @@ func UpdateGoModFromReqs(loaderstate *State, ctx context.Context, opts WriteOpts
}
list = append(list, &modfile.Require{
Mod: m,
- Indirect: !loaderstate.requirements.direct[m.Path],
+ Indirect: !ld.requirements.direct[m.Path],
})
}
@@ -1984,13 +1984,13 @@ func UpdateGoModFromReqs(loaderstate *State, ctx context.Context, opts WriteOpts
// go.mod or go.sum are out of date in a semantically significant way.
//
// In workspace mode, commitRequirements only writes changes to go.work.sum.
-func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts) (err error) {
- if loaderstate.inWorkspaceMode() {
+func commitRequirements(ld *Loader, ctx context.Context, opts WriteOpts) (err error) {
+ if ld.inWorkspaceMode() {
// go.mod files aren't updated in workspace mode, but we still want to
// update the go.work.sum file.
- return loaderstate.Fetcher().WriteGoSum(ctx, keepSums(loaderstate, ctx, loaderstate.pkgLoader, loaderstate.requirements, addBuildListZipSums), mustHaveCompleteRequirements(loaderstate))
+ return ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld))
}
- _, updatedGoMod, modFile, err := UpdateGoModFromReqs(loaderstate, ctx, opts)
+ _, updatedGoMod, modFile, err := UpdateGoModFromReqs(ld, ctx, opts)
if err != nil {
if errors.Is(err, errNoChange) {
return nil
@@ -1998,7 +1998,7 @@ func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts)
return err
}
- index := loaderstate.MainModules.GetSingleIndexOrNil(loaderstate)
+ index := ld.MainModules.GetSingleIndexOrNil(ld)
dirty := index.modFileIsDirty(modFile) || len(opts.DropTools) > 0 || len(opts.AddTools) > 0
if dirty && cfg.BuildMod != "mod" {
// If we're about to fail due to -mod=readonly,
@@ -2012,15 +2012,15 @@ func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts)
// Don't write go.mod, but write go.sum in case we added or trimmed sums.
// 'go mod init' shouldn't write go.sum, since it will be incomplete.
if cfg.CmdName != "mod init" {
- if err := loaderstate.Fetcher().WriteGoSum(ctx, keepSums(loaderstate, ctx, loaderstate.pkgLoader, loaderstate.requirements, addBuildListZipSums), mustHaveCompleteRequirements(loaderstate)); err != nil {
+ if err := ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld)); err != nil {
return err
}
}
return nil
}
- mainModule := loaderstate.MainModules.mustGetSingleMainModule(loaderstate)
- modFilePath := modFilePath(loaderstate.MainModules.ModRoot(mainModule))
+ mainModule := ld.MainModules.mustGetSingleMainModule(ld)
+ modFilePath := modFilePath(ld.MainModules.ModRoot(mainModule))
if fsys.Replaced(modFilePath) {
if dirty {
return errors.New("updates to go.mod needed, but go.mod is part of the overlay specified with -overlay")
@@ -2029,13 +2029,13 @@ func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts)
}
defer func() {
// At this point we have determined to make the go.mod file on disk equal to new.
- loaderstate.MainModules.SetIndex(mainModule, indexModFile(updatedGoMod, modFile, mainModule, false))
+ ld.MainModules.SetIndex(mainModule, indexModFile(updatedGoMod, modFile, mainModule, false))
// Update go.sum after releasing the side lock and refreshing the index.
// 'go mod init' shouldn't write go.sum, since it will be incomplete.
if cfg.CmdName != "mod init" {
if err == nil {
- err = loaderstate.Fetcher().WriteGoSum(ctx, keepSums(loaderstate, ctx, loaderstate.pkgLoader, loaderstate.requirements, addBuildListZipSums), mustHaveCompleteRequirements(loaderstate))
+ err = ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld))
}
}
}()
@@ -2078,7 +2078,7 @@ func commitRequirements(loaderstate *State, ctx context.Context, opts WriteOpts)
// including any go.mod files needed to reconstruct the MVS result
// or identify go versions,
// in addition to the checksums for every module in keepMods.
-func keepSums(loaderstate *State, ctx context.Context, pld *packageLoader, rs *Requirements, which whichSums) map[module.Version]bool {
+func keepSums(ld *Loader, ctx context.Context, pld *packageLoader, rs *Requirements, which whichSums) map[module.Version]bool {
// Every module in the full module graph contributes its requirements,
// so in order to ensure that the build list itself is reproducible,
// we need sums for every go.mod in the graph (regardless of whether
@@ -2091,12 +2091,12 @@ func keepSums(loaderstate *State, ctx context.Context, pld *packageLoader, rs *R
// ambiguous import errors the next time we load the package.
keepModSumsForZipSums := true
if pld == nil {
- if gover.Compare(loaderstate.MainModules.GoVersion(loaderstate), gover.TidyGoModSumVersion) < 0 && cfg.BuildMod != "mod" {
+ if gover.Compare(ld.MainModules.GoVersion(ld), gover.TidyGoModSumVersion) < 0 && cfg.BuildMod != "mod" {
keepModSumsForZipSums = false
}
} else {
keepPkgGoModSums := true
- if gover.Compare(pld.requirements.GoVersion(loaderstate), gover.TidyGoModSumVersion) < 0 && (pld.Tidy || cfg.BuildMod != "mod") {
+ if gover.Compare(pld.requirements.GoVersion(ld), gover.TidyGoModSumVersion) < 0 && (pld.Tidy || cfg.BuildMod != "mod") {
keepPkgGoModSums = false
keepModSumsForZipSums = false
}
@@ -2114,21 +2114,21 @@ func keepSums(loaderstate *State, ctx context.Context, pld *packageLoader, rs *R
// minor, so we maintain the previous (buggy) behavior in 'go mod tidy' to
// avoid introducing unnecessary churn.
if keepPkgGoModSums {
- r := resolveReplacement(loaderstate, pkg.mod)
+ r := resolveReplacement(ld, pkg.mod)
keep[modkey(r)] = true
}
if rs.pruning == pruned && pkg.mod.Path != "" {
- if v, ok := rs.rootSelected(loaderstate, pkg.mod.Path); ok && v == pkg.mod.Version {
+ if v, ok := rs.rootSelected(ld, pkg.mod.Path); ok && v == pkg.mod.Version {
// pkg was loaded from a root module, and because the main module has
// a pruned module graph we do not check non-root modules for
// conflicts for packages that can be found in roots. So we only need
// the checksums for the root modules that may contain pkg, not all
// possible modules.
for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
- if v, ok := rs.rootSelected(loaderstate, prefix); ok && v != "none" {
+ if v, ok := rs.rootSelected(ld, prefix); ok && v != "none" {
m := module.Version{Path: prefix, Version: v}
- r := resolveReplacement(loaderstate, m)
+ r := resolveReplacement(ld, m)
keep[r] = true
}
}
@@ -2136,11 +2136,11 @@ func keepSums(loaderstate *State, ctx context.Context, pld *packageLoader, rs *R
}
}
- mg, _ := rs.Graph(loaderstate, ctx)
+ mg, _ := rs.Graph(ld, ctx)
for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
if v := mg.Selected(prefix); v != "none" {
m := module.Version{Path: prefix, Version: v}
- r := resolveReplacement(loaderstate, m)
+ r := resolveReplacement(ld, m)
keep[r] = true
}
}
@@ -2152,27 +2152,27 @@ func keepSums(loaderstate *State, ctx context.Context, pld *packageLoader, rs *R
// Save sums for the root modules (or their replacements), but don't
// incur the cost of loading the graph just to find and retain the sums.
for _, m := range rs.rootModules {
- r := resolveReplacement(loaderstate, m)
+ r := resolveReplacement(ld, m)
keep[modkey(r)] = true
if which == addBuildListZipSums {
keep[r] = true
}
}
} else {
- mg, _ := rs.Graph(loaderstate, ctx)
+ mg, _ := rs.Graph(ld, ctx)
mg.WalkBreadthFirst(func(m module.Version) {
if _, ok := mg.RequiredBy(m); ok {
// The requirements from m's go.mod file are present in the module graph,
// so they are relevant to the MVS result regardless of whether m was
// actually selected.
- r := resolveReplacement(loaderstate, m)
+ r := resolveReplacement(ld, m)
keep[modkey(r)] = true
}
})
if which == addBuildListZipSums {
for _, m := range mg.BuildList() {
- r := resolveReplacement(loaderstate, m)
+ r := resolveReplacement(ld, m)
if keepModSumsForZipSums {
keep[modkey(r)] = true // we need the go version from the go.mod file to do anything useful with the zipfile
}
diff --git a/src/cmd/go/internal/modload/list.go b/src/cmd/go/internal/modload/list.go
index 32f8c5fe3d..762e760c68 100644
--- a/src/cmd/go/internal/modload/list.go
+++ b/src/cmd/go/internal/modload/list.go
@@ -41,7 +41,7 @@ const (
// along with any error preventing additional matches from being identified.
//
// The returned slice can be nonempty even if the error is non-nil.
-func ListModules(loaderstate *State, ctx context.Context, args []string, mode ListMode, reuseFile string) ([]*modinfo.ModulePublic, error) {
+func ListModules(ld *Loader, ctx context.Context, args []string, mode ListMode, reuseFile string) ([]*modinfo.ModulePublic, error) {
var reuse map[module.Version]*modinfo.ModulePublic
if reuseFile != "" {
data, err := os.ReadFile(reuseFile)
@@ -69,7 +69,7 @@ func ListModules(loaderstate *State, ctx context.Context, args []string, mode Li
}
}
- rs, mods, err := listModules(loaderstate, ctx, LoadModFile(loaderstate, ctx), args, mode, reuse)
+ rs, mods, err := listModules(ld, ctx, LoadModFile(ld, ctx), args, mode, reuse)
type token struct{}
sem := make(chan token, runtime.GOMAXPROCS(0))
@@ -82,16 +82,16 @@ func ListModules(loaderstate *State, ctx context.Context, args []string, mode Li
sem <- token{}
go func() {
if mode&ListU != 0 {
- addUpdate(loaderstate, ctx, m)
+ addUpdate(ld, ctx, m)
}
if mode&ListVersions != 0 {
- addVersions(loaderstate, ctx, m, mode&ListRetractedVersions != 0)
+ addVersions(ld, ctx, m, mode&ListRetractedVersions != 0)
}
if mode&ListRetracted != 0 {
- addRetraction(loaderstate, ctx, m)
+ addRetraction(ld, ctx, m)
}
if mode&ListDeprecated != 0 {
- addDeprecation(loaderstate, ctx, m)
+ addDeprecation(ld, ctx, m)
}
<-sem
}()
@@ -109,7 +109,7 @@ func ListModules(loaderstate *State, ctx context.Context, args []string, mode Li
}
if err == nil {
- loaderstate.requirements = rs
+ ld.requirements = rs
// TODO(#61605): The extra ListU clause fixes a problem with Go 1.21rc3
// where "go mod tidy" and "go list -m -u all" fight over whether the go.sum
// should be considered up-to-date. The fix for now is to always treat the
@@ -117,20 +117,20 @@ func ListModules(loaderstate *State, ctx context.Context, args []string, mode Li
// but in general list -u is looking up other checksums in the checksum database
// that won't be necessary later, so it makes sense not to write the go.sum back out.
if !ExplicitWriteGoMod && mode&ListU == 0 {
- err = commitRequirements(loaderstate, ctx, WriteOpts{})
+ err = commitRequirements(ld, ctx, WriteOpts{})
}
}
return mods, err
}
-func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args []string, mode ListMode, reuse map[module.Version]*modinfo.ModulePublic) (_ *Requirements, mods []*modinfo.ModulePublic, mgErr error) {
+func listModules(ld *Loader, ctx context.Context, rs *Requirements, args []string, mode ListMode, reuse map[module.Version]*modinfo.ModulePublic) (_ *Requirements, mods []*modinfo.ModulePublic, mgErr error) {
if len(args) == 0 {
var ms []*modinfo.ModulePublic
- for _, m := range loaderstate.MainModules.Versions() {
+ for _, m := range ld.MainModules.Versions() {
if gover.IsToolchain(m.Path) {
continue
}
- ms = append(ms, moduleInfo(loaderstate, ctx, rs, m, mode, reuse))
+ ms = append(ms, moduleInfo(ld, ctx, rs, m, mode, reuse))
}
return rs, ms, nil
}
@@ -145,8 +145,8 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
}
if arg == "all" || strings.Contains(arg, "...") {
needFullGraph = true
- if !loaderstate.HasModRoot() {
- base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(loaderstate))
+ if !ld.HasModRoot() {
+ base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(ld))
}
continue
}
@@ -156,26 +156,26 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
}
if found {
if vers == "upgrade" || vers == "patch" {
- if _, ok := rs.rootSelected(loaderstate, path); !ok || rs.pruning == unpruned {
+ if _, ok := rs.rootSelected(ld, path); !ok || rs.pruning == unpruned {
needFullGraph = true
- if !loaderstate.HasModRoot() {
- base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(loaderstate))
+ if !ld.HasModRoot() {
+ base.Fatalf("go: cannot match %q: %v", arg, NewNoMainModulesError(ld))
}
}
}
continue
}
- if _, ok := rs.rootSelected(loaderstate, arg); !ok || rs.pruning == unpruned {
+ if _, ok := rs.rootSelected(ld, arg); !ok || rs.pruning == unpruned {
needFullGraph = true
- if mode&ListVersions == 0 && !loaderstate.HasModRoot() {
- base.Fatalf("go: cannot match %q without -versions or an explicit version: %v", arg, NewNoMainModulesError(loaderstate))
+ if mode&ListVersions == 0 && !ld.HasModRoot() {
+ base.Fatalf("go: cannot match %q without -versions or an explicit version: %v", arg, NewNoMainModulesError(ld))
}
}
}
var mg *ModuleGraph
if needFullGraph {
- rs, mg, mgErr = expandGraph(loaderstate, ctx, rs)
+ rs, mg, mgErr = expandGraph(ld, ctx, rs)
}
matchedModule := map[module.Version]bool{}
@@ -187,7 +187,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
if found {
var current string
if mg == nil {
- current, _ = rs.rootSelected(loaderstate, path)
+ current, _ = rs.rootSelected(ld, path)
} else {
current = mg.Selected(path)
}
@@ -200,13 +200,13 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
}
}
- allowed := loaderstate.CheckAllowed
+ allowed := ld.CheckAllowed
if IsRevisionQuery(path, vers) || mode&ListRetracted != 0 {
// Allow excluded and retracted versions if the user asked for a
// specific revision or used 'go list -retracted'.
allowed = nil
}
- info, err := queryReuse(loaderstate, ctx, path, vers, current, allowed, reuse)
+ info, err := queryReuse(ld, ctx, path, vers, current, allowed, reuse)
if err != nil {
var origin *codehost.Origin
if info != nil {
@@ -225,7 +225,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
// *Requirements instead.
var noRS *Requirements
- mod := moduleInfo(loaderstate, ctx, noRS, module.Version{Path: path, Version: info.Version}, mode, reuse)
+ mod := moduleInfo(ld, ctx, noRS, module.Version{Path: path, Version: info.Version}, mode, reuse)
if vers != mod.Version {
mod.Query = vers
}
@@ -245,7 +245,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
var v string
if mg == nil {
var ok bool
- v, ok = rs.rootSelected(loaderstate, arg)
+ v, ok = rs.rootSelected(ld, arg)
if !ok {
// We checked rootSelected(arg) in the earlier args loop, so if there
// is no such root we should have loaded a non-nil mg.
@@ -259,7 +259,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
continue
}
if v != "none" {
- mods = append(mods, moduleInfo(loaderstate, ctx, rs, module.Version{Path: arg, Version: v}, mode, reuse))
+ mods = append(mods, moduleInfo(ld, ctx, rs, module.Version{Path: arg, Version: v}, mode, reuse))
} else if cfg.BuildMod == "vendor" {
// In vendor mode, we can't determine whether a missing module is “a
// known dependency” because the module graph is incomplete.
@@ -300,7 +300,7 @@ func listModules(loaderstate *State, ctx context.Context, rs *Requirements, args
fetchedMods := make([]*modinfo.ModulePublic, len(matches))
for i, m := range matches {
q.Add(func() {
- fetchedMods[i] = moduleInfo(loaderstate, ctx, rs, m, mode, reuse)
+ fetchedMods[i] = moduleInfo(ld, ctx, rs, m, mode, reuse)
})
}
<-q.Idle()
diff --git a/src/cmd/go/internal/modload/load.go b/src/cmd/go/internal/modload/load.go
index d5737565d5..4efecdf8a1 100644
--- a/src/cmd/go/internal/modload/load.go
+++ b/src/cmd/go/internal/modload/load.go
@@ -242,7 +242,7 @@ type PackageOpts struct {
// LoadPackages identifies the set of packages matching the given patterns and
// loads the packages in the import graph rooted at that set.
-func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
+func LoadPackages(ld *Loader, ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
if opts.Tags == nil {
opts.Tags = imports.Tags()
}
@@ -263,11 +263,11 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
case m.IsLocal():
// Evaluate list of file system directories on first iteration.
if m.Dirs == nil {
- matchModRoots := loaderstate.modRoots
+ matchModRoots := ld.modRoots
if opts.MainModule != (module.Version{}) {
- matchModRoots = []string{loaderstate.MainModules.ModRoot(opts.MainModule)}
+ matchModRoots = []string{ld.MainModules.ModRoot(opts.MainModule)}
}
- matchLocalDirs(loaderstate, ctx, matchModRoots, m, rs)
+ matchLocalDirs(ld, ctx, matchModRoots, m, rs)
}
// Make a copy of the directory list and translate to import paths.
@@ -278,7 +278,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// the loader iterations.
m.Pkgs = m.Pkgs[:0]
for _, dir := range m.Dirs {
- pkg, err := resolveLocalPackage(loaderstate, ctx, dir, rs)
+ pkg, err := resolveLocalPackage(ld, ctx, dir, rs)
if err != nil {
if !m.IsLiteral() && (err == errPkgIsBuiltin || err == errPkgIsGorootSrc) {
continue // Don't include "builtin" or GOROOT/src in wildcard patterns.
@@ -286,8 +286,8 @@ 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 !loaderstate.HasModRoot() {
- die(loaderstate)
+ if !ld.HasModRoot() {
+ die(ld)
}
if pld != nil {
@@ -303,7 +303,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
case strings.Contains(m.Pattern(), "..."):
m.Errs = m.Errs[:0]
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
// The module graph is (or may be) incomplete — perhaps we failed to
// load the requirements of some module. This is an error in matching
@@ -313,26 +313,26 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// necessarily prevent us from loading the packages we could find.
m.Errs = append(m.Errs, err)
}
- matchPackages(loaderstate, ctx, m, opts.Tags, includeStd, mg.BuildList())
+ matchPackages(ld, ctx, m, opts.Tags, includeStd, mg.BuildList())
case m.Pattern() == "work":
- matchModules := loaderstate.MainModules.Versions()
+ matchModules := ld.MainModules.Versions()
if opts.MainModule != (module.Version{}) {
matchModules = []module.Version{opts.MainModule}
}
- matchPackages(loaderstate, ctx, m, opts.Tags, omitStd, matchModules)
+ matchPackages(ld, ctx, m, opts.Tags, omitStd, matchModules)
case m.Pattern() == "all":
if pld == nil {
// The initial roots are the packages and tools in the main module.
// loadFromRoots will expand that to "all".
m.Errs = m.Errs[:0]
- matchModules := loaderstate.MainModules.Versions()
+ matchModules := ld.MainModules.Versions()
if opts.MainModule != (module.Version{}) {
matchModules = []module.Version{opts.MainModule}
}
- matchPackages(loaderstate, ctx, m, opts.Tags, omitStd, matchModules)
- for tool := range loaderstate.MainModules.Tools() {
+ matchPackages(ld, ctx, m, opts.Tags, omitStd, matchModules)
+ for tool := range ld.MainModules.Tools() {
m.Pkgs = append(m.Pkgs, tool)
}
} else {
@@ -347,7 +347,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
}
case m.Pattern() == "tool":
- for tool := range loaderstate.MainModules.Tools() {
+ for tool := range ld.MainModules.Tools() {
m.Pkgs = append(m.Pkgs, tool)
}
default:
@@ -356,12 +356,12 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
}
}
- initialRS, err := loadModFile(loaderstate, ctx, &opts)
+ initialRS, err := loadModFile(ld, ctx, &opts)
if err != nil {
base.Fatal(err)
}
- ld := loadFromRoots(loaderstate, ctx, loaderParams{
+ pld := loadFromRoots(ld, ctx, loaderParams{
PackageOpts: opts,
requirements: initialRS,
@@ -377,18 +377,18 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
})
// One last pass to finalize wildcards.
- updateMatches(ld.requirements, ld)
+ updateMatches(pld.requirements, pld)
// List errors in matching patterns (such as directory permission
// errors for wildcard patterns).
- if !ld.SilencePackageErrors {
+ if !pld.SilencePackageErrors {
for _, match := range matches {
for _, err := range match.Errs {
- ld.error(err)
+ pld.error(err)
}
}
}
- ld.exitIfErrors(ctx)
+ pld.exitIfErrors(ctx)
if !opts.SilenceUnmatchedWarnings {
search.WarnUnmatched(matches)
@@ -396,10 +396,10 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
if opts.Tidy {
if cfg.BuildV {
- mg, _ := ld.requirements.Graph(loaderstate, ctx)
+ mg, _ := pld.requirements.Graph(ld, ctx)
for _, m := range initialRS.rootModules {
var unused bool
- if ld.requirements.pruning == unpruned {
+ if pld.requirements.pruning == unpruned {
// m is unused if it was dropped from the module graph entirely. If it
// was only demoted from direct to indirect, it may still be in use via
// a transitive import.
@@ -408,7 +408,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// m is unused if it was dropped from the roots. If it is still present
// as a transitive dependency, that transitive dependency is not needed
// by any package or test in the main module.
- _, ok := ld.requirements.rootSelected(loaderstate, m.Path)
+ _, ok := pld.requirements.rootSelected(ld, m.Path)
unused = !ok
}
if unused {
@@ -417,9 +417,9 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
}
}
- keep := keepSums(loaderstate, ctx, ld, ld.requirements, loadedZipSumsOnly)
- compatVersion := ld.TidyCompatibleVersion
- goVersion := ld.requirements.GoVersion(loaderstate)
+ keep := keepSums(ld, ctx, pld, pld.requirements, loadedZipSumsOnly)
+ compatVersion := pld.TidyCompatibleVersion
+ goVersion := pld.requirements.GoVersion(ld)
if compatVersion == "" {
if gover.Compare(goVersion, gover.GoStrictVersion) < 0 {
compatVersion = gover.Prev(goVersion)
@@ -435,32 +435,32 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// version higher than the go.mod version adds nothing.
compatVersion = goVersion
}
- if compatPruning := pruningForGoVersion(compatVersion); compatPruning != ld.requirements.pruning {
- compatRS := newRequirements(loaderstate, compatPruning, ld.requirements.rootModules, ld.requirements.direct)
- ld.checkTidyCompatibility(loaderstate, ctx, compatRS, compatVersion)
+ if compatPruning := pruningForGoVersion(compatVersion); compatPruning != pld.requirements.pruning {
+ compatRS := newRequirements(ld, compatPruning, pld.requirements.rootModules, pld.requirements.direct)
+ pld.checkTidyCompatibility(ld, ctx, compatRS, compatVersion)
- for m := range keepSums(loaderstate, ctx, ld, compatRS, loadedZipSumsOnly) {
+ for m := range keepSums(ld, ctx, pld, compatRS, loadedZipSumsOnly) {
keep[m] = true
}
}
if opts.TidyDiff {
cfg.BuildMod = "readonly"
- loaderstate.pkgLoader = ld
- loaderstate.requirements = loaderstate.pkgLoader.requirements
- currentGoMod, updatedGoMod, _, err := UpdateGoModFromReqs(loaderstate, ctx, WriteOpts{})
+ ld.pkgLoader = pld
+ ld.requirements = ld.pkgLoader.requirements
+ currentGoMod, updatedGoMod, _, err := UpdateGoModFromReqs(ld, ctx, WriteOpts{})
if err != nil {
base.Fatal(err)
}
goModDiff := diff.Diff("current/go.mod", currentGoMod, "tidy/go.mod", updatedGoMod)
- loaderstate.Fetcher().TrimGoSum(keep)
+ ld.Fetcher().TrimGoSum(keep)
// Dropping compatibility for 1.16 may result in a strictly smaller go.sum.
// Update the keep map with only the loaded.requirements.
if gover.Compare(compatVersion, "1.16") > 0 {
- keep = keepSums(loaderstate, ctx, loaderstate.pkgLoader, loaderstate.requirements, addBuildListZipSums)
+ keep = keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums)
}
- currentGoSum, tidyGoSum := loaderstate.fetcher.TidyGoSum(keep)
+ currentGoSum, tidyGoSum := ld.fetcher.TidyGoSum(keep)
goSumDiff := diff.Diff("current/go.sum", currentGoSum, "tidy/go.sum", tidyGoSum)
if len(goModDiff) > 0 {
@@ -475,14 +475,14 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
}
if !ExplicitWriteGoMod {
- loaderstate.Fetcher().TrimGoSum(keep)
+ ld.Fetcher().TrimGoSum(keep)
// commitRequirements below will also call WriteGoSum, but the "keep" map
// we have here could be strictly larger: commitRequirements only commits
// loaded.requirements, but here we may have also loaded (and want to
// preserve checksums for) additional entities from compatRS, which are
// only needed for compatibility with ld.TidyCompatibleVersion.
- if err := loaderstate.Fetcher().WriteGoSum(ctx, keep, mustHaveCompleteRequirements(loaderstate)); err != nil {
+ if err := ld.Fetcher().WriteGoSum(ctx, keep, mustHaveCompleteRequirements(ld)); err != nil {
base.Fatal(err)
}
}
@@ -496,10 +496,10 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// We'll skip updating if ExplicitWriteGoMod is true (the caller has opted
// to call WriteGoMod itself) or if ResolveMissingImports is false (the
// command wants to examine the package graph as-is).
- loaderstate.pkgLoader = ld
- loaderstate.requirements = loaderstate.pkgLoader.requirements
+ ld.pkgLoader = pld
+ ld.requirements = ld.pkgLoader.requirements
- for _, pkg := range ld.pkgs {
+ for _, pkg := range pld.pkgs {
if !pkg.isTest() {
loadedPackages = append(loadedPackages, pkg.path)
}
@@ -507,7 +507,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
sort.Strings(loadedPackages)
if !ExplicitWriteGoMod && opts.ResolveMissingImports {
- if err := commitRequirements(loaderstate, ctx, WriteOpts{}); err != nil {
+ if err := commitRequirements(ld, ctx, WriteOpts{}); err != nil {
base.Fatal(err)
}
}
@@ -517,7 +517,7 @@ func LoadPackages(loaderstate *State, ctx context.Context, opts PackageOpts, pat
// matchLocalDirs is like m.MatchDirs, but tries to avoid scanning directories
// outside of the standard library and active modules.
-func matchLocalDirs(loaderstate *State, ctx context.Context, modRoots []string, m *search.Match, rs *Requirements) {
+func matchLocalDirs(ld *Loader, ctx context.Context, modRoots []string, m *search.Match, rs *Requirements) {
if !m.IsLocal() {
panic(fmt.Sprintf("internal error: resolveLocalDirs on non-local pattern %s", m.Pattern()))
}
@@ -535,10 +535,10 @@ func matchLocalDirs(loaderstate *State, ctx context.Context, modRoots []string,
}
modRoot := findModuleRoot(absDir)
- if !slices.Contains(modRoots, modRoot) && search.InDir(absDir, cfg.GOROOTsrc) == "" && pathInModuleCache(loaderstate, ctx, absDir, rs) == "" {
+ if !slices.Contains(modRoots, modRoot) && search.InDir(absDir, cfg.GOROOTsrc) == "" && pathInModuleCache(ld, ctx, absDir, rs) == "" {
m.Dirs = []string{}
scope := "main module or its selected dependencies"
- if loaderstate.inWorkspaceMode() {
+ if ld.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))
@@ -550,7 +550,7 @@ func matchLocalDirs(loaderstate *State, ctx context.Context, modRoots []string,
}
// resolveLocalPackage resolves a filesystem path to a package path.
-func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs *Requirements) (string, error) {
+func resolveLocalPackage(ld *Loader, ctx context.Context, dir string, rs *Requirements) (string, error) {
var absDir string
if filepath.IsAbs(dir) {
absDir = filepath.Clean(dir)
@@ -588,13 +588,13 @@ func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs
}
}
- for _, mod := range loaderstate.MainModules.Versions() {
- modRoot := loaderstate.MainModules.ModRoot(mod)
+ for _, mod := range ld.MainModules.Versions() {
+ modRoot := ld.MainModules.ModRoot(mod)
if modRoot != "" && absDir == modRoot {
if absDir == cfg.GOROOTsrc {
return "", errPkgIsGorootSrc
}
- return loaderstate.MainModules.PathPrefix(mod), nil
+ return ld.MainModules.PathPrefix(mod), nil
}
}
@@ -603,8 +603,8 @@ func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs
// It's not strictly necessary but helpful to keep the checks.
var pkgNotFoundErr error
pkgNotFoundLongestPrefix := ""
- for _, mainModule := range loaderstate.MainModules.Versions() {
- modRoot := loaderstate.MainModules.ModRoot(mainModule)
+ for _, mainModule := range ld.MainModules.Versions() {
+ modRoot := ld.MainModules.ModRoot(mainModule)
if modRoot != "" && str.HasFilePathPrefix(absDir, modRoot) && !strings.Contains(absDir[len(modRoot):], "@") {
suffix := filepath.ToSlash(str.TrimFilePathPrefix(absDir, modRoot))
if pkg, found := strings.CutPrefix(suffix, "vendor/"); found {
@@ -612,14 +612,14 @@ func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs
return "", fmt.Errorf("without -mod=vendor, directory %s has no package path", absDir)
}
- readVendorList(VendorDir(loaderstate))
+ readVendorList(VendorDir(ld))
if _, ok := vendorPkgModule[pkg]; !ok {
return "", fmt.Errorf("directory %s is not a package listed in vendor/modules.txt", absDir)
}
return pkg, nil
}
- mainModulePrefix := loaderstate.MainModules.PathPrefix(mainModule)
+ mainModulePrefix := ld.MainModules.PathPrefix(mainModule)
if mainModulePrefix == "" {
pkg := suffix
if pkg == "builtin" {
@@ -660,13 +660,13 @@ func resolveLocalPackage(loaderstate *State, ctx context.Context, dir string, rs
return pkg, nil
}
- pkg := pathInModuleCache(loaderstate, ctx, absDir, rs)
+ pkg := pathInModuleCache(ld, ctx, absDir, rs)
if pkg == "" {
dirstr := fmt.Sprintf("directory %s", base.ShortPath(absDir))
if dirstr == "directory ." {
dirstr = "current directory"
}
- if loaderstate.inWorkspaceMode() {
+ if ld.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))
}
@@ -685,17 +685,17 @@ var (
// pathInModuleCache returns the import path of the directory dir,
// if dir is in the module cache copy of a module in our build list.
-func pathInModuleCache(loaderstate *State, ctx context.Context, dir string, rs *Requirements) string {
+func pathInModuleCache(ld *Loader, ctx context.Context, dir string, rs *Requirements) string {
tryMod := func(m module.Version) (string, bool) {
if gover.IsToolchain(m.Path) {
return "", false
}
var root string
var err error
- if repl := Replacement(loaderstate, m); repl.Path != "" && repl.Version == "" {
+ if repl := Replacement(ld, m); repl.Path != "" && repl.Version == "" {
root = repl.Path
if !filepath.IsAbs(root) {
- root = filepath.Join(replaceRelativeTo(loaderstate), root)
+ root = filepath.Join(replaceRelativeTo(ld), root)
}
} else if repl.Path != "" {
root, err = modfetch.DownloadDir(ctx, repl)
@@ -720,7 +720,7 @@ func pathInModuleCache(loaderstate *State, ctx context.Context, dir string, rs *
if rs.pruning == pruned {
for _, m := range rs.rootModules {
- if v, _ := rs.rootSelected(loaderstate, m.Path); v != m.Version {
+ if v, _ := rs.rootSelected(ld, m.Path); v != m.Version {
continue // m is a root, but we have a higher root for the same path.
}
if importPath, ok := tryMod(m); ok {
@@ -739,7 +739,7 @@ func pathInModuleCache(loaderstate *State, ctx context.Context, dir string, rs *
// versions of root modules may differ from what we already checked above.
// Re-check those paths too.
- mg, _ := rs.Graph(loaderstate, ctx)
+ mg, _ := rs.Graph(ld, ctx)
var importPath string
for _, m := range mg.BuildList() {
var found bool
@@ -758,8 +758,8 @@ func pathInModuleCache(loaderstate *State, ctx context.Context, dir string, rs *
//
// TODO(bcmills): Silencing errors seems off. Take a closer look at this and
// figure out what the error-reporting actually ought to be.
-func ImportFromFiles(loaderstate *State, ctx context.Context, gofiles []string) {
- rs := LoadModFile(loaderstate, ctx)
+func ImportFromFiles(ld *Loader, ctx context.Context, gofiles []string) {
+ rs := LoadModFile(ld, ctx)
tags := imports.Tags()
imports, testImports, err := imports.ScanFiles(gofiles, tags)
@@ -767,7 +767,7 @@ func ImportFromFiles(loaderstate *State, ctx context.Context, gofiles []string)
base.Fatal(err)
}
- loaderstate.pkgLoader = loadFromRoots(loaderstate, ctx, loaderParams{
+ ld.pkgLoader = loadFromRoots(ld, ctx, loaderParams{
PackageOpts: PackageOpts{
Tags: tags,
ResolveMissingImports: true,
@@ -780,10 +780,10 @@ func ImportFromFiles(loaderstate *State, ctx context.Context, gofiles []string)
return roots
},
})
- loaderstate.requirements = loaderstate.pkgLoader.requirements
+ ld.requirements = ld.pkgLoader.requirements
if !ExplicitWriteGoMod {
- if err := commitRequirements(loaderstate, ctx, WriteOpts{}); err != nil {
+ if err := commitRequirements(ld, ctx, WriteOpts{}); err != nil {
base.Fatal(err)
}
}
@@ -791,11 +791,11 @@ 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 !loaderstate.HasModRoot() {
+func (mms *MainModuleSet) DirImportPath(ld *Loader, ctx context.Context, dir string) (path string, m module.Version) {
+ if !ld.HasModRoot() {
return ".", module.Version{}
}
- LoadModFile(loaderstate, ctx) // Sets targetPrefix.
+ LoadModFile(ld, ctx) // Sets targetPrefix.
if !filepath.IsAbs(dir) {
dir = filepath.Join(base.Cwd(), dir)
@@ -812,7 +812,7 @@ func (mms *MainModuleSet) DirImportPath(loaderstate *State, ctx context.Context,
return mms.PathPrefix(v), v
}
if str.HasFilePathPrefix(dir, modRoot) {
- pathPrefix := loaderstate.MainModules.PathPrefix(v)
+ pathPrefix := ld.MainModules.PathPrefix(v)
if pathPrefix > longestPrefix {
longestPrefix = pathPrefix
longestPrefixVersion = v
@@ -833,8 +833,8 @@ func (mms *MainModuleSet) DirImportPath(loaderstate *State, ctx context.Context,
}
// PackageModule returns the module providing the package named by the import path.
-func (loaderstate *State) PackageModule(path string) module.Version {
- pkg, ok := loaderstate.pkgLoader.pkgCache.Get(path)
+func (ld *Loader) PackageModule(path string) module.Version {
+ pkg, ok := ld.pkgLoader.pkgCache.Get(path)
if !ok {
return module.Version{}
}
@@ -845,15 +845,15 @@ func (loaderstate *State) PackageModule(path string) module.Version {
// 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 Lookup(loaderstate *State, parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
+func Lookup(ld *Loader, parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
if path == "" {
panic("Lookup called with empty package path")
}
if parentIsStd {
- path = loaderstate.pkgLoader.stdVendor(loaderstate, parentPath, path)
+ path = ld.pkgLoader.stdVendor(ld, parentPath, path)
}
- pkg, ok := loaderstate.pkgLoader.pkgCache.Get(path)
+ pkg, ok := ld.pkgLoader.pkgCache.Get(path)
if !ok {
// The loader should have found all the relevant paths.
// There are a few exceptions, though:
@@ -949,11 +949,11 @@ func (pld *packageLoader) exitIfErrors(ctx context.Context) {
// goVersion reports the Go version that should be used for the loader's
// requirements: ld.TidyGoVersion if set, or ld.requirements.GoVersion()
// otherwise.
-func (pld *packageLoader) goVersion(loaderstate *State) string {
+func (pld *packageLoader) goVersion(ld *Loader) string {
if pld.TidyGoVersion != "" {
return pld.TidyGoVersion
}
- return pld.requirements.GoVersion(loaderstate)
+ return pld.requirements.GoVersion(ld)
}
// A loadPkg records information about a single loaded package.
@@ -1056,11 +1056,11 @@ func (pkg *loadPkg) isTest() bool {
// fromExternalModule reports whether pkg was loaded from a module other than
// the main module.
-func (pkg *loadPkg) fromExternalModule(loaderstate *State) bool {
+func (pkg *loadPkg) fromExternalModule(ld *Loader) bool {
if pkg.mod.Path == "" {
return false // loaded from the standard library, not a module
}
- return !loaderstate.MainModules.Contains(pkg.mod.Path)
+ return !ld.MainModules.Contains(pkg.mod.Path)
}
var errMissing = errors.New("cannot find package")
@@ -1071,7 +1071,7 @@ var errMissing = errors.New("cannot find package")
// The set of root packages is returned by the params.listRoots function, and
// expanded to the full set of packages by tracing imports (and possibly tests)
// as needed.
-func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams) *packageLoader {
+func loadFromRoots(ld *Loader, ctx context.Context, params loaderParams) *packageLoader {
pld := &packageLoader{
loaderParams: params,
work: par.NewQueue(runtime.GOMAXPROCS(0)),
@@ -1087,7 +1087,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// spot-checks in modules that do not maintain the expanded go.mod
// requirements needed for graph pruning.
var err error
- pld.requirements, _, err = expandGraph(loaderstate, ctx, pld.requirements)
+ pld.requirements, _, err = expandGraph(ld, ctx, pld.requirements)
if err != nil {
pld.error(err)
}
@@ -1095,11 +1095,11 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
pld.exitIfErrors(ctx)
updateGoVersion := func() {
- goVersion := pld.goVersion(loaderstate)
+ goVersion := pld.goVersion(ld)
if pld.requirements.pruning != workspace {
var err error
- pld.requirements, err = convertPruning(loaderstate, ctx, pld.requirements, pruningForGoVersion(goVersion))
+ pld.requirements, err = convertPruning(ld, ctx, pld.requirements, pruningForGoVersion(goVersion))
if err != nil {
pld.error(err)
pld.exitIfErrors(ctx)
@@ -1133,7 +1133,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// set of root packages does not change then we can select the correct
// versions of all transitive imports on the first try and complete
// loading in a single iteration.
- changedBuildList := pld.preloadRootModules(loaderstate, ctx, rootPkgs)
+ changedBuildList := pld.preloadRootModules(ld, ctx, rootPkgs)
if changedBuildList {
// The build list has changed, so the set of root packages may have also
// changed. Start over to pick up the changes. (Preloading roots is much
@@ -1146,7 +1146,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
inRoots := map[*loadPkg]bool{}
for _, path := range rootPkgs {
- root := pld.pkg(loaderstate, ctx, path, pkgIsRoot)
+ root := pld.pkg(ld, ctx, path, pkgIsRoot)
if !inRoots[root] {
pld.roots = append(pld.roots, root)
inRoots[root] = true
@@ -1162,7 +1162,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
pld.buildStacks()
- changed, err := pld.updateRequirements(loaderstate, ctx)
+ changed, err := pld.updateRequirements(ld, ctx)
if err != nil {
pld.error(err)
break
@@ -1176,12 +1176,12 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
continue
}
- if !pld.ResolveMissingImports || (!loaderstate.HasModRoot() && !loaderstate.allowMissingModuleImports) {
+ if !pld.ResolveMissingImports || (!ld.HasModRoot() && !ld.allowMissingModuleImports) {
// We've loaded as much as we can without resolving missing imports.
break
}
- modAddedBy, err := pld.resolveMissingImports(loaderstate, ctx)
+ modAddedBy, err := pld.resolveMissingImports(ld, ctx)
if err != nil {
pld.error(err)
break
@@ -1208,7 +1208,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// iteration so we don't need to also update it here. (That would waste time
// computing a "direct" map that we'll have to recompute later anyway.)
direct := pld.requirements.direct
- rs, err := updateRoots(loaderstate, ctx, direct, pld.requirements, noPkgs, toAdd, pld.AssumeRootsImported)
+ rs, err := updateRoots(ld, ctx, direct, pld.requirements, noPkgs, toAdd, pld.AssumeRootsImported)
if err != nil {
// If an error was found in a newly added module, report the package
// import stack instead of the module requirement stack. Packages
@@ -1236,7 +1236,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// Tidy the build list, if applicable, before we report errors.
// (The process of tidying may remove errors from irrelevant dependencies.)
if pld.Tidy {
- rs, err := tidyRoots(loaderstate, ctx, pld.requirements, pld.pkgs)
+ rs, err := tidyRoots(ld, ctx, pld.requirements, pld.pkgs)
if err != nil {
pld.error(err)
} else {
@@ -1244,8 +1244,8 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// Attempt to switch to the requested Go version. We have been using its
// pruning and semantics all along, but there may have been — and may
// still be — requirements on higher versions in the graph.
- tidy := overrideRoots(loaderstate, ctx, rs, []module.Version{{Path: "go", Version: pld.TidyGoVersion}})
- mg, err := tidy.Graph(loaderstate, ctx)
+ tidy := overrideRoots(ld, ctx, rs, []module.Version{{Path: "go", Version: pld.TidyGoVersion}})
+ mg, err := tidy.Graph(ld, ctx)
if err != nil {
pld.error(err)
}
@@ -1277,7 +1277,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
if m.Path == "go" && pld.TidyGoVersion != "" {
continue
}
- if v, ok := pld.requirements.rootSelected(loaderstate, m.Path); !ok || v != m.Version {
+ if v, ok := pld.requirements.rootSelected(ld, m.Path); !ok || v != m.Version {
pld.error(fmt.Errorf("internal error: a requirement on %v is needed but was not added during package loading (selected %s)", m, v))
}
}
@@ -1326,7 +1326,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
pld.error(fmt.Errorf("%s: %w", pkg.stackText(), pkg.err))
}
- pld.checkMultiplePaths(loaderstate)
+ pld.checkMultiplePaths(ld)
return pld
}
@@ -1349,7 +1349,7 @@ func loadFromRoots(loaderstate *State, ctx context.Context, params loaderParams)
// The "changed" return value reports whether the update changed the selected
// version of any module that either provided a loaded package or may now
// provide a package that was previously unresolved.
-func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Context) (changed bool, err error) {
+func (pld *packageLoader) updateRequirements(ld *Loader, ctx context.Context) (changed bool, err error) {
rs := pld.requirements
// direct contains the set of modules believed to provide packages directly
@@ -1382,16 +1382,16 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
}
}
}
- if pkg.mod.Version != "" || !loaderstate.MainModules.Contains(pkg.mod.Path) {
+ if pkg.mod.Version != "" || !ld.MainModules.Contains(pkg.mod.Path) {
continue
}
for _, dep := range pkg.imports {
- if !dep.fromExternalModule(loaderstate) {
+ if !dep.fromExternalModule(ld) {
continue
}
- if loaderstate.inWorkspaceMode() {
+ if ld.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.
@@ -1404,7 +1404,7 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
// of the vendor directory anyway.
continue
}
- if mg, err := rs.Graph(loaderstate, ctx); err != nil {
+ if mg, err := rs.Graph(ld, ctx); err != nil {
return false, err
} else if _, ok := mg.RequiredBy(dep.mod); !ok {
// dep.mod is not an explicit dependency, but needs to be.
@@ -1416,7 +1416,7 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
}
}
} else if pkg.err == nil && cfg.BuildMod != "mod" {
- if v, ok := rs.rootSelected(loaderstate, dep.mod.Path); !ok || v != dep.mod.Version {
+ if v, ok := rs.rootSelected(ld, dep.mod.Path); !ok || v != dep.mod.Version {
// dep.mod is not an explicit dependency, but needs to be.
// Because we are not in "mod" mode, we will not be able to update it.
// Instead, mark the importing package with an error.
@@ -1482,21 +1482,21 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
// roots can only increase and the set of roots can only expand. The set
// of extant root paths is finite and the set of versions of each path is
// finite, so the iteration *must* reach a stable fixed-point.
- tidy, err := tidyRoots(loaderstate, ctx, rs, pld.pkgs)
+ tidy, err := tidyRoots(ld, ctx, rs, pld.pkgs)
if err != nil {
return false, err
}
addRoots = tidy.rootModules
}
- rs, err = updateRoots(loaderstate, ctx, direct, rs, pld.pkgs, addRoots, pld.AssumeRootsImported)
+ rs, err = updateRoots(ld, ctx, direct, rs, pld.pkgs, addRoots, pld.AssumeRootsImported)
if err != nil {
// We don't actually know what even the root requirements are supposed to be,
// so we can't proceed with loading. Return the error to the caller
return false, err
}
- if rs.GoVersion(loaderstate) != pld.requirements.GoVersion(loaderstate) {
+ if rs.GoVersion(ld) != pld.requirements.GoVersion(ld) {
// A change in the selected Go version may or may not affect the set of
// loaded packages, but in some cases it can change the meaning of the "all"
// pattern, the level of pruning in the module graph, and even the set of
@@ -1507,12 +1507,12 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
// The roots of the module graph have changed in some way (not just the
// "direct" markings). Check whether the changes affected any of the loaded
// packages.
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
return false, err
}
for _, pkg := range pld.pkgs {
- if pkg.fromExternalModule(loaderstate) && mg.Selected(pkg.mod.Path) != pkg.mod.Version {
+ if pkg.fromExternalModule(ld) && mg.Selected(pkg.mod.Path) != pkg.mod.Version {
changed = true
break
}
@@ -1532,7 +1532,7 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
//
// In some sense, we can think of this as ‘upgraded the module providing
// pkg.path from "none" to a version higher than "none"’.
- if _, _, _, _, err = importFromModules(loaderstate, ctx, pkg.path, rs, nil, pld.skipImportModFiles); err == nil {
+ if _, _, _, _, err = importFromModules(ld, ctx, pkg.path, rs, nil, pld.skipImportModFiles); err == nil {
changed = true
break
}
@@ -1550,7 +1550,7 @@ func (pld *packageLoader) updateRequirements(loaderstate *State, ctx context.Con
// The newly-resolved packages are added to the addedModuleFor map, and
// resolveMissingImports returns a map from each new module version to
// the first missing package that module would resolve.
-func (pld *packageLoader) resolveMissingImports(loaderstate *State, ctx context.Context) (modAddedBy map[module.Version]*loadPkg, err error) {
+func (pld *packageLoader) resolveMissingImports(ld *Loader, ctx context.Context) (modAddedBy map[module.Version]*loadPkg, err error) {
type pkgMod struct {
pkg *loadPkg
mod *module.Version
@@ -1574,13 +1574,13 @@ func (pld *packageLoader) resolveMissingImports(loaderstate *State, ctx context.
var mod module.Version
pld.work.Add(func() {
var err error
- mod, err = queryImport(loaderstate, ctx, pkg.path, pld.requirements)
+ mod, err = queryImport(ld, ctx, pkg.path, pld.requirements)
if err != nil {
if ime, ok := errors.AsType[*ImportMissingError](err); ok {
for curstack := pkg.stack; curstack != nil; curstack = curstack.stack {
- if loaderstate.MainModules.Contains(curstack.mod.Path) {
+ if ld.MainModules.Contains(curstack.mod.Path) {
ime.ImportingMainModule = curstack.mod
- ime.modRoot = loaderstate.MainModules.ModRoot(ime.ImportingMainModule)
+ ime.modRoot = ld.MainModules.ModRoot(ime.ImportingMainModule)
break
}
}
@@ -1651,7 +1651,7 @@ func (pld *packageLoader) resolveMissingImports(loaderstate *State, ctx context.
// ld.work queue, and its test (if requested) will also be populated once
// imports have been resolved. When ld.work goes idle, all transitive imports of
// the requested package (and its test, if requested) will have been loaded.
-func (pld *packageLoader) pkg(loaderstate *State, ctx context.Context, path string, flags loadPkgFlags) *loadPkg {
+func (pld *packageLoader) pkg(ld *Loader, ctx context.Context, path string, flags loadPkgFlags) *loadPkg {
if flags.has(pkgImportsLoaded) {
panic("internal error: (*packageLoader).pkg called with pkgImportsLoaded flag set")
}
@@ -1660,20 +1660,20 @@ func (pld *packageLoader) pkg(loaderstate *State, ctx context.Context, path stri
pkg := &loadPkg{
path: path,
}
- pld.applyPkgFlags(loaderstate, ctx, pkg, flags)
+ pld.applyPkgFlags(ld, ctx, pkg, flags)
- pld.work.Add(func() { pld.load(loaderstate, ctx, pkg) })
+ pld.work.Add(func() { pld.load(ld, ctx, pkg) })
return pkg
})
- pld.applyPkgFlags(loaderstate, ctx, pkg, flags)
+ pld.applyPkgFlags(ld, ctx, pkg, flags)
return pkg
}
// applyPkgFlags updates pkg.flags to set the given flags and propagate the
// (transitive) effects of those flags, possibly loading or enqueueing further
// packages as a result.
-func (pld *packageLoader) applyPkgFlags(loaderstate *State, ctx context.Context, pkg *loadPkg, flags loadPkgFlags) {
+func (pld *packageLoader) applyPkgFlags(ld *Loader, ctx context.Context, pkg *loadPkg, flags loadPkgFlags) {
if flags == 0 {
return
}
@@ -1701,7 +1701,7 @@ func (pld *packageLoader) applyPkgFlags(loaderstate *State, ctx context.Context,
// so it's ok if we call it more than is strictly necessary.
wantTest := false
switch {
- case pld.allPatternIsRoot && loaderstate.MainModules.Contains(pkg.mod.Path):
+ case pld.allPatternIsRoot && ld.MainModules.Contains(pkg.mod.Path):
// We are loading the "all" pattern, which includes packages imported by
// tests in the main module. This package is in the main module, so we
// need to identify the imports of its test even if LoadTests is not set.
@@ -1722,13 +1722,13 @@ func (pld *packageLoader) applyPkgFlags(loaderstate *State, ctx context.Context,
if wantTest {
var testFlags loadPkgFlags
- if loaderstate.MainModules.Contains(pkg.mod.Path) || (pld.allClosesOverTests && new.has(pkgInAll)) {
+ if ld.MainModules.Contains(pkg.mod.Path) || (pld.allClosesOverTests && new.has(pkgInAll)) {
// Tests of packages in the main module are in "all", in the sense that
// they cause the packages they import to also be in "all". So are tests
// of packages in "all" if "all" closes over test dependencies.
testFlags |= pkgInAll
}
- pld.pkgTest(loaderstate, ctx, pkg, testFlags)
+ pld.pkgTest(ld, ctx, pkg, testFlags)
}
}
@@ -1736,13 +1736,13 @@ func (pld *packageLoader) applyPkgFlags(loaderstate *State, ctx context.Context,
// We have just marked pkg with pkgInAll, or we have just loaded its
// imports, or both. Now is the time to propagate pkgInAll to the imports.
for _, dep := range pkg.imports {
- pld.applyPkgFlags(loaderstate, ctx, dep, pkgInAll)
+ pld.applyPkgFlags(ld, ctx, dep, pkgInAll)
}
}
if new.has(pkgFromRoot) && !old.has(pkgFromRoot|pkgImportsLoaded) {
for _, dep := range pkg.imports {
- pld.applyPkgFlags(loaderstate, ctx, dep, pkgFromRoot)
+ pld.applyPkgFlags(ld, ctx, dep, pkgFromRoot)
}
}
}
@@ -1750,7 +1750,7 @@ func (pld *packageLoader) applyPkgFlags(loaderstate *State, ctx context.Context,
// preloadRootModules loads the module requirements needed to identify the
// selected version of each module providing a package in rootPkgs,
// adding new root modules to the module graph if needed.
-func (pld *packageLoader) preloadRootModules(loaderstate *State, ctx context.Context, rootPkgs []string) (changedBuildList bool) {
+func (pld *packageLoader) preloadRootModules(ld *Loader, ctx context.Context, rootPkgs []string) (changedBuildList bool) {
needc := make(chan map[module.Version]bool, 1)
needc <- map[module.Version]bool{}
for _, path := range rootPkgs {
@@ -1761,12 +1761,12 @@ func (pld *packageLoader) preloadRootModules(loaderstate *State, ctx context.Con
// If the main module is tidy and the package is in "all" — or if we're
// lucky — we can identify all of its imports without actually loading the
// full module graph.
- m, _, _, _, err := importFromModules(loaderstate, ctx, path, pld.requirements, nil, pld.skipImportModFiles)
+ m, _, _, _, err := importFromModules(ld, ctx, path, pld.requirements, nil, pld.skipImportModFiles)
if err != nil {
if _, ok := errors.AsType[*ImportMissingError](err); ok && pld.ResolveMissingImports {
// This package isn't provided by any selected module.
// If we can find it, it will be a new root dependency.
- m, err = queryImport(loaderstate, ctx, path, pld.requirements)
+ m, err = queryImport(ld, ctx, path, pld.requirements)
}
if err != nil {
// We couldn't identify the root module containing this package.
@@ -1779,7 +1779,7 @@ func (pld *packageLoader) preloadRootModules(loaderstate *State, ctx context.Con
return
}
- v, ok := pld.requirements.rootSelected(loaderstate, m.Path)
+ v, ok := pld.requirements.rootSelected(ld, m.Path)
if !ok || v != m.Version {
// We found the requested package in m, but m is not a root, so
// loadModGraph will not load its requirements. We need to promote the
@@ -1807,7 +1807,7 @@ func (pld *packageLoader) preloadRootModules(loaderstate *State, ctx context.Con
}
gover.ModSort(toAdd)
- rs, err := updateRoots(loaderstate, ctx, pld.requirements.direct, pld.requirements, nil, toAdd, pld.AssumeRootsImported)
+ rs, err := updateRoots(ld, ctx, pld.requirements.direct, pld.requirements, nil, toAdd, pld.AssumeRootsImported)
if err != nil {
// We are missing some root dependency, and for some reason we can't load
// enough of the module dependency graph to add the missing root. Package
@@ -1829,11 +1829,11 @@ func (pld *packageLoader) preloadRootModules(loaderstate *State, ctx context.Con
}
// load loads an individual package.
-func (pld *packageLoader) load(loaderstate *State, ctx context.Context, pkg *loadPkg) {
+func (pld *packageLoader) load(ld *Loader, ctx context.Context, pkg *loadPkg) {
var mg *ModuleGraph
if pld.requirements.pruning == unpruned {
var err error
- mg, err = pld.requirements.Graph(loaderstate, ctx)
+ mg, err = pld.requirements.Graph(ld, ctx)
if err != nil {
// We already checked the error from Graph in loadFromRoots and/or
// updateRequirements, so we ignored the error on purpose and we should
@@ -1848,17 +1848,17 @@ func (pld *packageLoader) load(loaderstate *State, ctx context.Context, pkg *loa
}
var modroot string
- pkg.mod, modroot, pkg.dir, pkg.altMods, pkg.err = importFromModules(loaderstate, ctx, pkg.path, pld.requirements, mg, pld.skipImportModFiles)
- if loaderstate.MainModules.Tools()[pkg.path] {
+ pkg.mod, modroot, pkg.dir, pkg.altMods, pkg.err = importFromModules(ld, ctx, pkg.path, pld.requirements, mg, pld.skipImportModFiles)
+ if ld.MainModules.Tools()[pkg.path] {
// Tools declared by main modules are always in "all".
// We apply the package flags before returning so that missing
// tool dependencies report an error https://go.dev/issue/70582
- pld.applyPkgFlags(loaderstate, ctx, pkg, pkgInAll)
+ pld.applyPkgFlags(ld, ctx, pkg, pkgInAll)
}
if pkg.dir == "" {
return
}
- if loaderstate.MainModules.Contains(pkg.mod.Path) {
+ if ld.MainModules.Contains(pkg.mod.Path) {
// Go ahead and mark pkg as in "all". This provides the invariant that a
// package that is *only* imported by other packages in "all" is always
// marked as such before loading its imports.
@@ -1868,7 +1868,7 @@ func (pld *packageLoader) load(loaderstate *State, ctx context.Context, pkg *loa
// about (by reducing churn on the flag bits of dependencies), and costs
// essentially nothing (these atomic flag ops are essentially free compared
// to scanning source code for imports).
- pld.applyPkgFlags(loaderstate, ctx, pkg, pkgInAll)
+ pld.applyPkgFlags(ld, ctx, pkg, pkgInAll)
}
if pld.AllowPackage != nil {
if err := pld.AllowPackage(ctx, pkg.path, pkg.mod); err != nil {
@@ -1900,13 +1900,13 @@ func (pld *packageLoader) load(loaderstate *State, ctx context.Context, pkg *loa
if pkg.inStd {
// Imports from packages in "std" and "cmd" should resolve using
// GOROOT/src/vendor even when "std" is not the main module.
- path = pld.stdVendor(loaderstate, pkg.path, path)
+ path = pld.stdVendor(ld, pkg.path, path)
}
- pkg.imports = append(pkg.imports, pld.pkg(loaderstate, ctx, path, importFlags))
+ pkg.imports = append(pkg.imports, pld.pkg(ld, ctx, path, importFlags))
}
pkg.testImports = testImports
- pld.applyPkgFlags(loaderstate, ctx, pkg, pkgImportsLoaded)
+ pld.applyPkgFlags(ld, ctx, pkg, pkgImportsLoaded)
}
// pkgTest locates the test of pkg, creating it if needed, and updates its state
@@ -1914,7 +1914,7 @@ func (pld *packageLoader) load(loaderstate *State, ctx context.Context, pkg *loa
//
// pkgTest requires that the imports of pkg have already been loaded (flagged
// with pkgImportsLoaded).
-func (pld *packageLoader) pkgTest(loaderstate *State, ctx context.Context, pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
+func (pld *packageLoader) pkgTest(ld *Loader, ctx context.Context, pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
if pkg.isTest() {
panic("pkgTest called on a test package")
}
@@ -1929,7 +1929,7 @@ func (pld *packageLoader) pkgTest(loaderstate *State, ctx context.Context, pkg *
err: pkg.err,
inStd: pkg.inStd,
}
- pld.applyPkgFlags(loaderstate, ctx, pkg.test, testFlags)
+ pld.applyPkgFlags(ld, ctx, pkg.test, testFlags)
createdTest = true
})
@@ -1942,14 +1942,14 @@ func (pld *packageLoader) pkgTest(loaderstate *State, ctx context.Context, pkg *
}
for _, path := range pkg.testImports {
if pkg.inStd {
- path = pld.stdVendor(loaderstate, test.path, path)
+ path = pld.stdVendor(ld, test.path, path)
}
- test.imports = append(test.imports, pld.pkg(loaderstate, ctx, path, importFlags))
+ test.imports = append(test.imports, pld.pkg(ld, ctx, path, importFlags))
}
pkg.testImports = nil
- pld.applyPkgFlags(loaderstate, ctx, test, pkgImportsLoaded)
+ pld.applyPkgFlags(ld, ctx, test, pkgImportsLoaded)
} else {
- pld.applyPkgFlags(loaderstate, ctx, test, testFlags)
+ pld.applyPkgFlags(ld, ctx, test, testFlags)
}
return test
@@ -1957,7 +1957,7 @@ func (pld *packageLoader) pkgTest(loaderstate *State, ctx context.Context, pkg *
// stdVendor returns the canonical import path for the package with the given
// path when imported from the standard-library package at parentPath.
-func (pld *packageLoader) stdVendor(loaderstate *State, parentPath, path string) string {
+func (pld *packageLoader) stdVendor(ld *Loader, parentPath, path string) string {
if p, _, ok := fips140.ResolveImport(path); ok {
return p
}
@@ -1966,14 +1966,14 @@ func (pld *packageLoader) stdVendor(loaderstate *State, parentPath, path string)
}
if str.HasPathPrefix(parentPath, "cmd") {
- if !pld.VendorModulesInGOROOTSrc || !loaderstate.MainModules.Contains("cmd") {
+ if !pld.VendorModulesInGOROOTSrc || !ld.MainModules.Contains("cmd") {
vendorPath := pathpkg.Join("cmd", "vendor", path)
if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
return vendorPath
}
}
- } else if !pld.VendorModulesInGOROOTSrc || !loaderstate.MainModules.Contains("std") || str.HasPathPrefix(parentPath, "vendor") {
+ } else if !pld.VendorModulesInGOROOTSrc || !ld.MainModules.Contains("std") || str.HasPathPrefix(parentPath, "vendor") {
// If we are outside of the 'std' module, resolve imports from within 'std'
// to the vendor directory.
//
@@ -2019,7 +2019,7 @@ func (pld *packageLoader) computePatternAll() (all []string) {
// or as a replacement for another module, but not both at the same time.
//
// (See https://golang.org/issue/26607 and https://golang.org/issue/34650.)
-func (pld *packageLoader) checkMultiplePaths(loaderstate *State) {
+func (pld *packageLoader) checkMultiplePaths(ld *Loader) {
mods := pld.requirements.rootModules
if cached := pld.requirements.graph.Load(); cached != nil {
if mg := cached.mg; mg != nil {
@@ -2029,7 +2029,7 @@ func (pld *packageLoader) checkMultiplePaths(loaderstate *State) {
firstPath := map[module.Version]string{}
for _, mod := range mods {
- src := resolveReplacement(loaderstate, mod)
+ src := resolveReplacement(ld, mod)
if prev, ok := firstPath[src]; !ok {
firstPath[src] = mod.Path
} else if prev != mod.Path {
@@ -2040,8 +2040,8 @@ func (pld *packageLoader) checkMultiplePaths(loaderstate *State) {
// checkTidyCompatibility emits an error if any package would be loaded from a
// different module under rs than under ld.requirements.
-func (pld *packageLoader) checkTidyCompatibility(loaderstate *State, ctx context.Context, rs *Requirements, compatVersion string) {
- goVersion := rs.GoVersion(loaderstate)
+func (pld *packageLoader) checkTidyCompatibility(ld *Loader, ctx context.Context, rs *Requirements, compatVersion string) {
+ goVersion := rs.GoVersion(ld)
suggestUpgrade := false
suggestEFlag := false
suggestFixes := func() {
@@ -2058,7 +2058,7 @@ func (pld *packageLoader) checkTidyCompatibility(loaderstate *State, ctx context
fmt.Fprintln(os.Stderr)
goFlag := ""
- if goVersion != loaderstate.MainModules.GoVersion(loaderstate) {
+ if goVersion != ld.MainModules.GoVersion(ld) {
goFlag = " -go=" + goVersion
}
@@ -2087,7 +2087,7 @@ func (pld *packageLoader) checkTidyCompatibility(loaderstate *State, ctx context
fmt.Fprintf(os.Stderr, "For information about 'go mod tidy' compatibility, see:\n\thttps://go.dev/ref/mod#graph-pruning\n")
}
- mg, err := rs.Graph(loaderstate, ctx)
+ mg, err := rs.Graph(ld, ctx)
if err != nil {
pld.error(fmt.Errorf("error loading go %s module graph: %w", compatVersion, err))
pld.switchIfErrors(ctx)
@@ -2125,7 +2125,7 @@ func (pld *packageLoader) checkTidyCompatibility(loaderstate *State, ctx context
pkg := pkg
pld.work.Add(func() {
- mod, _, _, _, err := importFromModules(loaderstate, ctx, pkg.path, rs, mg, pld.skipImportModFiles)
+ mod, _, _, _, err := importFromModules(ld, ctx, pkg.path, rs, mg, pld.skipImportModFiles)
if mod != pkg.mod {
mismatches := <-mismatchMu
mismatches[pkg] = mismatch{mod: mod, err: err}
@@ -2383,8 +2383,8 @@ func (pkg *loadPkg) why() string {
// 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 (loaderstate *State) Why(path string) string {
- pkg, ok := loaderstate.pkgLoader.pkgCache.Get(path)
+func (ld *Loader) Why(path string) string {
+ pkg, ok := ld.pkgLoader.pkgCache.Get(path)
if !ok {
return ""
}
@@ -2394,9 +2394,9 @@ func (loaderstate *State) Why(path string) string {
// 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 (loaderstate *State) WhyDepth(path string) int {
+func (ld *Loader) WhyDepth(path string) int {
n := 0
- pkg, _ := loaderstate.pkgLoader.pkgCache.Get(path)
+ pkg, _ := ld.pkgLoader.pkgCache.Get(path)
for p := pkg; p != nil; p = p.stack {
n++
}
diff --git a/src/cmd/go/internal/modload/modfile.go b/src/cmd/go/internal/modload/modfile.go
index 1e54a58034..574ff69c8c 100644
--- a/src/cmd/go/internal/modload/modfile.go
+++ b/src/cmd/go/internal/modload/modfile.go
@@ -138,11 +138,11 @@ func pruningForGoVersion(goVersion string) modPruning {
// 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 (s *State) CheckAllowed(ctx context.Context, m module.Version) error {
- if err := s.CheckExclusions(ctx, m); err != nil {
+func (ld *Loader) CheckAllowed(ctx context.Context, m module.Version) error {
+ if err := ld.CheckExclusions(ctx, m); err != nil {
return err
}
- if err := s.CheckRetractions(ctx, m); err != nil {
+ if err := ld.CheckRetractions(ctx, m); err != nil {
return err
}
return nil
@@ -154,9 +154,9 @@ var ErrDisallowed = errors.New("disallowed module version")
// CheckExclusions returns an error equivalent to ErrDisallowed if module m is
// excluded by the main module's go.mod file.
-func (s *State) CheckExclusions(ctx context.Context, m module.Version) error {
- for _, mainModule := range s.MainModules.Versions() {
- if index := s.MainModules.Index(mainModule); index != nil && index.exclude[m] {
+func (ld *Loader) CheckExclusions(ctx context.Context, m module.Version) error {
+ for _, mainModule := range ld.MainModules.Versions() {
+ if index := ld.MainModules.Index(mainModule); index != nil && index.exclude[m] {
return module.VersionError(m, errExcluded)
}
}
@@ -172,7 +172,7 @@ func (e *excludedError) Is(err error) bool { return err == ErrDisallowed }
// CheckRetractions returns an error if module m has been retracted by
// its author.
-func (s *State) CheckRetractions(ctx context.Context, m module.Version) (err error) {
+func (ld *Loader) CheckRetractions(ctx context.Context, m module.Version) (err error) {
defer func() {
if err == nil {
return
@@ -193,7 +193,7 @@ func (s *State) CheckRetractions(ctx context.Context, m module.Version) (err err
// Cannot be retracted.
return nil
}
- if repl := Replacement(s, module.Version{Path: m.Path}); repl.Path != "" {
+ if repl := Replacement(ld, module.Version{Path: m.Path}); repl.Path != "" {
// All versions of the module were replaced.
// Don't load retractions, since we'd just load the replacement.
return nil
@@ -210,11 +210,11 @@ func (s *State) CheckRetractions(ctx context.Context, m module.Version) (err err
// We load the raw file here: the go.mod file may have a different module
// path that we expect if the module or its repository was renamed.
// We still want to apply retractions to other aliases of the module.
- rm, err := queryLatestVersionIgnoringRetractions(s, ctx, m.Path)
+ rm, err := queryLatestVersionIgnoringRetractions(ld, ctx, m.Path)
if err != nil {
return err
}
- summary, err := rawGoModSummary(s, rm)
+ summary, err := rawGoModSummary(ld, rm)
if err != nil && !errors.Is(err, gover.ErrTooNew) {
return err
}
@@ -300,7 +300,7 @@ func ShortMessage(message, emptyDefault string) string {
//
// CheckDeprecation returns an error if the message can't be loaded.
// CheckDeprecation returns "", nil if there is no deprecation message.
-func CheckDeprecation(loaderstate *State, ctx context.Context, m module.Version) (deprecation string, err error) {
+func CheckDeprecation(ld *Loader, ctx context.Context, m module.Version) (deprecation string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("loading deprecation for %s: %w", m.Path, err)
@@ -312,17 +312,17 @@ func CheckDeprecation(loaderstate *State, ctx context.Context, m module.Version)
// Don't look up deprecation.
return "", nil
}
- if repl := Replacement(loaderstate, module.Version{Path: m.Path}); repl.Path != "" {
+ if repl := Replacement(ld, module.Version{Path: m.Path}); repl.Path != "" {
// All versions of the module were replaced.
// We'll look up deprecation separately for the replacement.
return "", nil
}
- latest, err := queryLatestVersionIgnoringRetractions(loaderstate, ctx, m.Path)
+ latest, err := queryLatestVersionIgnoringRetractions(ld, ctx, m.Path)
if err != nil {
return "", err
}
- summary, err := rawGoModSummary(loaderstate, latest)
+ summary, err := rawGoModSummary(ld, latest)
if err != nil && !errors.Is(err, gover.ErrTooNew) {
return "", err
}
@@ -342,28 +342,28 @@ func replacement(mod module.Version, replace map[module.Version]module.Version)
// 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 Replacement(loaderstate *State, mod module.Version) module.Version {
- r, foundModRoot, _ := replacementFrom(loaderstate, mod)
- return canonicalizeReplacePath(loaderstate, r, foundModRoot)
+func Replacement(ld *Loader, mod module.Version) module.Version {
+ r, foundModRoot, _ := replacementFrom(ld, mod)
+ return canonicalizeReplacePath(ld, r, foundModRoot)
}
// replacementFrom returns the replacement for mod, if any, the modroot of the replacement if it appeared in a go.mod,
// and the source of the replacement. The replacement is relative to the go.work or go.mod file it appears in.
-func replacementFrom(loaderstate *State, mod module.Version) (r module.Version, modroot string, fromFile string) {
+func replacementFrom(ld *Loader, mod module.Version) (r module.Version, modroot string, fromFile string) {
foundFrom, found, foundModRoot := "", module.Version{}, ""
- if loaderstate.MainModules == nil {
+ if ld.MainModules == nil {
return module.Version{}, "", ""
- } else if loaderstate.MainModules.Contains(mod.Path) && mod.Version == "" {
+ } else if ld.MainModules.Contains(mod.Path) && mod.Version == "" {
// Don't replace the workspace version of the main module.
return module.Version{}, "", ""
}
- if _, r, ok := replacement(mod, loaderstate.MainModules.WorkFileReplaceMap()); ok {
- return r, "", loaderstate.workFilePath
+ if _, r, ok := replacement(mod, ld.MainModules.WorkFileReplaceMap()); ok {
+ return r, "", ld.workFilePath
}
- for _, v := range loaderstate.MainModules.Versions() {
- if index := loaderstate.MainModules.Index(v); index != nil {
+ for _, v := range ld.MainModules.Versions() {
+ if index := ld.MainModules.Index(v); index != nil {
if from, r, ok := replacement(mod, index.replace); ok {
- modRoot := loaderstate.MainModules.ModRoot(v)
+ modRoot := ld.MainModules.ModRoot(v)
if foundModRoot != "" && foundFrom != from && found != r {
base.Errorf("conflicting replacements found for %v in workspace modules defined by %v and %v",
mod, modFilePath(foundModRoot), modFilePath(modRoot))
@@ -376,21 +376,21 @@ func replacementFrom(loaderstate *State, mod module.Version) (r module.Version,
return found, foundModRoot, modFilePath(foundModRoot)
}
-func replaceRelativeTo(loaderstate *State) string {
- if workFilePath := WorkFilePath(loaderstate); workFilePath != "" {
+func replaceRelativeTo(ld *Loader) string {
+ if workFilePath := WorkFilePath(ld); workFilePath != "" {
return filepath.Dir(workFilePath)
}
- return loaderstate.MainModules.ModRoot(loaderstate.MainModules.mustGetSingleMainModule(loaderstate))
+ return ld.MainModules.ModRoot(ld.MainModules.mustGetSingleMainModule(ld))
}
// canonicalizeReplacePath ensures that relative, on-disk, replaced module paths
// are relative to the workspace directory (in workspace mode) or to the module's
// directory (in module mode, as they already are).
-func canonicalizeReplacePath(loaderstate *State, r module.Version, modRoot string) module.Version {
+func canonicalizeReplacePath(ld *Loader, r module.Version, modRoot string) module.Version {
if filepath.IsAbs(r.Path) || r.Version != "" || modRoot == "" {
return r
}
- workFilePath := WorkFilePath(loaderstate)
+ workFilePath := WorkFilePath(ld)
if workFilePath == "" {
return r
}
@@ -407,8 +407,8 @@ func canonicalizeReplacePath(loaderstate *State, r module.Version, modRoot strin
// for m: either m itself, or the replacement for m (iff m is replaced).
// It also returns the modroot of the module providing the replacement if
// one was found.
-func resolveReplacement(loaderstate *State, m module.Version) module.Version {
- if r := Replacement(loaderstate, m); r.Path != "" {
+func resolveReplacement(ld *Loader, m module.Version) module.Version {
+ if r := Replacement(ld, m); r.Path != "" {
return r
}
return m
@@ -573,12 +573,12 @@ type retraction struct {
// module versions.
//
// The caller must not modify the returned summary.
-func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error) {
- if m.Version == "" && !loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
+func goModSummary(ld *Loader, m module.Version) (*modFileSummary, error) {
+ if m.Version == "" && !ld.inWorkspaceMode() && ld.MainModules.Contains(m.Path) {
panic("internal error: goModSummary called on a main module")
}
if gover.IsToolchain(m.Path) {
- return rawGoModSummary(loaderstate, m)
+ return rawGoModSummary(ld, m)
}
if cfg.BuildMod == "vendor" {
@@ -586,7 +586,7 @@ func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error)
module: module.Version{Path: m.Path},
}
- readVendorList(VendorDir(loaderstate))
+ readVendorList(VendorDir(ld))
if vendorVersion[m.Path] != m.Version {
// This module is not vendored, so packages cannot be loaded from it and
// it cannot be relevant to the build.
@@ -601,15 +601,15 @@ func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error)
return summary, nil
}
- actual := resolveReplacement(loaderstate, m)
- if mustHaveSums(loaderstate) && actual.Version != "" {
+ actual := resolveReplacement(ld, m)
+ if mustHaveSums(ld) && actual.Version != "" {
key := module.Version{Path: actual.Path, Version: actual.Version + "/go.mod"}
- if !modfetch.HaveSum(loaderstate.Fetcher(), key) {
+ if !modfetch.HaveSum(ld.Fetcher(), key) {
suggestion := fmt.Sprintf(" for go.mod file; to add it:\n\tgo mod download %s", m.Path)
return nil, module.VersionError(actual, &sumMissingError{suggestion: suggestion})
}
}
- summary, err := rawGoModSummary(loaderstate, actual)
+ summary, err := rawGoModSummary(ld, actual)
if err != nil {
return nil, err
}
@@ -641,8 +641,8 @@ func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error)
}
}
- for _, mainModule := range loaderstate.MainModules.Versions() {
- if index := loaderstate.MainModules.Index(mainModule); index != nil && len(index.exclude) > 0 {
+ for _, mainModule := range ld.MainModules.Versions() {
+ if index := ld.MainModules.Index(mainModule); index != nil && len(index.exclude) > 0 {
// Drop any requirements on excluded versions.
// Don't modify the cached summary though, since we might need the raw
// summary separately.
@@ -676,7 +676,7 @@ func goModSummary(loaderstate *State, m module.Version) (*modFileSummary, error)
// rawGoModSummary cannot be used on the main module outside of workspace mode.
// The modFileSummary can still be used for retractions and deprecations
// even if a TooNewError is returned.
-func rawGoModSummary(loaderstate *State, m module.Version) (*modFileSummary, error) {
+func rawGoModSummary(ld *Loader, m module.Version) (*modFileSummary, error) {
if gover.IsToolchain(m.Path) {
if m.Path == "go" && gover.Compare(m.Version, gover.GoStrictVersion) >= 0 {
// Declare that go 1.21.3 requires toolchain 1.21.3,
@@ -686,7 +686,7 @@ func rawGoModSummary(loaderstate *State, m module.Version) (*modFileSummary, err
}
return &modFileSummary{module: m}, nil
}
- if m.Version == "" && !loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
+ if m.Version == "" && !ld.inWorkspaceMode() && ld.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,22 +694,22 @@ 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 == "" && loaderstate.inWorkspaceMode() && m.Path == "command-line-arguments" {
+ if m.Version == "" && ld.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 == "" && loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
+ } else if m.Version == "" && ld.inWorkspaceMode() && ld.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
// recompute a summary using the updated contents of the modfile.
- if mf := loaderstate.MainModules.ModFile(m); mf != nil {
- return summaryFromModFile(m, loaderstate.MainModules.modFiles[m])
+ if mf := ld.MainModules.ModFile(m); mf != nil {
+ return summaryFromModFile(m, ld.MainModules.modFiles[m])
}
}
return rawGoModSummaryCache.Do(m, func() (*modFileSummary, error) {
- name, data, err := rawGoModData(loaderstate, m)
+ name, data, err := rawGoModData(ld, m)
if err != nil {
return nil, err
}
@@ -781,15 +781,15 @@ var rawGoModSummaryCache par.ErrCache[module.Version, *modFileSummary]
//
// Unlike rawGoModSummary, rawGoModData does not cache its results in memory.
// Use rawGoModSummary instead unless you specifically need these bytes.
-func rawGoModData(loaderstate *State, m module.Version) (name string, data []byte, err error) {
+func rawGoModData(ld *Loader, m module.Version) (name string, data []byte, err error) {
if m.Version == "" {
dir := m.Path
if !filepath.IsAbs(dir) {
- if loaderstate.inWorkspaceMode() && loaderstate.MainModules.Contains(m.Path) {
- dir = loaderstate.MainModules.ModRoot(m)
+ if ld.inWorkspaceMode() && ld.MainModules.Contains(m.Path) {
+ dir = ld.MainModules.ModRoot(m)
} else {
// m is a replacement module with only a file path.
- dir = filepath.Join(replaceRelativeTo(loaderstate), dir)
+ dir = filepath.Join(replaceRelativeTo(ld), dir)
}
}
name = filepath.Join(dir, "go.mod")
@@ -810,7 +810,7 @@ func rawGoModData(loaderstate *State, m module.Version) (name string, data []byt
base.Fatalf("go: internal error: %s@%s: unexpected invalid semantic version", m.Path, m.Version)
}
name = "go.mod"
- data, err = loaderstate.Fetcher().GoMod(context.TODO(), m.Path, m.Version)
+ data, err = ld.Fetcher().GoMod(context.TODO(), m.Path, m.Version)
}
return name, data, err
}
@@ -825,12 +825,12 @@ func rawGoModData(loaderstate *State, m module.Version) (name string, data []byt
//
// If the queried latest version is replaced,
// queryLatestVersionIgnoringRetractions returns the replacement.
-func queryLatestVersionIgnoringRetractions(loaderstate *State, ctx context.Context, path string) (latest module.Version, err error) {
+func queryLatestVersionIgnoringRetractions(ld *Loader, ctx context.Context, path string) (latest module.Version, err error) {
return latestVersionIgnoringRetractionsCache.Do(path, func() (module.Version, error) {
ctx, span := trace.StartSpan(ctx, "queryLatestVersionIgnoringRetractions "+path)
defer span.Done()
- if repl := Replacement(loaderstate, module.Version{Path: path}); repl.Path != "" {
+ if repl := Replacement(ld, module.Version{Path: path}); repl.Path != "" {
// All versions of the module were replaced.
// No need to query.
return repl, nil
@@ -840,12 +840,12 @@ func queryLatestVersionIgnoringRetractions(loaderstate *State, ctx context.Conte
// Ignore exclusions from the main module's go.mod.
const ignoreSelected = ""
var allowAll AllowedFunc
- rev, err := Query(loaderstate, ctx, path, "latest", ignoreSelected, allowAll)
+ rev, err := Query(ld, ctx, path, "latest", ignoreSelected, allowAll)
if err != nil {
return module.Version{}, err
}
latest := module.Version{Path: path, Version: rev.Version}
- if repl := resolveReplacement(loaderstate, latest); repl.Path != "" {
+ if repl := resolveReplacement(ld, latest); repl.Path != "" {
latest = repl
}
return latest, nil
diff --git a/src/cmd/go/internal/modload/mvs.go b/src/cmd/go/internal/modload/mvs.go
index 63fedae0f1..27796c274a 100644
--- a/src/cmd/go/internal/modload/mvs.go
+++ b/src/cmd/go/internal/modload/mvs.go
@@ -39,12 +39,12 @@ func cmpVersion(p string, v1, v2 string) int {
// mvsReqs implements mvs.Reqs for module semantic versions,
// with any exclusions or replacements applied internally.
type mvsReqs struct {
- loaderstate *State // TODO(jitsu): Is there a way we can not depend on the entire loader state?
- roots []module.Version
+ ld *Loader // TODO(jitsu): Is there a way we can not depend on the entire loader state?
+ roots []module.Version
}
func (r *mvsReqs) Required(mod module.Version) ([]module.Version, error) {
- if mod.Version == "" && r.loaderstate.MainModules.Contains(mod.Path) {
+ if mod.Version == "" && r.ld.MainModules.Contains(mod.Path) {
// Use the build list as it existed when r was constructed, not the current
// global build list.
return r.roots, nil
@@ -54,7 +54,7 @@ func (r *mvsReqs) Required(mod module.Version) ([]module.Version, error) {
return nil, nil
}
- summary, err := goModSummary(r.loaderstate, mod)
+ summary, err := goModSummary(r.ld, mod)
if err != nil {
return nil, err
}
@@ -80,11 +80,11 @@ func (*mvsReqs) Upgrade(m module.Version) (module.Version, error) {
return m, nil
}
-func versions(loaderstate *State, ctx context.Context, path string, allowed AllowedFunc) (versions []string, origin *codehost.Origin, err error) {
+func versions(ld *Loader, ctx context.Context, path string, allowed AllowedFunc) (versions []string, origin *codehost.Origin, err error) {
// Note: modfetch.Lookup and repo.Versions are cached,
// so there's no need for us to add extra caching here.
err = modfetch.TryProxies(func(proxy string) error {
- repo, err := lookupRepo(loaderstate, ctx, proxy, path)
+ repo, err := lookupRepo(ld, ctx, proxy, path)
if err != nil {
return err
}
@@ -112,12 +112,12 @@ func versions(loaderstate *State, ctx context.Context, path string, allowed Allo
//
// Since the version of a main module is not found in the version list,
// it has no previous version.
-func previousVersion(loaderstate *State, ctx context.Context, m module.Version) (module.Version, error) {
- if m.Version == "" && loaderstate.MainModules.Contains(m.Path) {
+func previousVersion(ld *Loader, ctx context.Context, m module.Version) (module.Version, error) {
+ if m.Version == "" && ld.MainModules.Contains(m.Path) {
return module.Version{Path: m.Path, Version: "none"}, nil
}
- list, _, err := versions(loaderstate, ctx, m.Path, loaderstate.CheckAllowed)
+ list, _, err := versions(ld, ctx, m.Path, ld.CheckAllowed)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return module.Version{Path: m.Path, Version: "none"}, nil
@@ -133,5 +133,5 @@ func previousVersion(loaderstate *State, ctx context.Context, m module.Version)
func (r *mvsReqs) Previous(m module.Version) (module.Version, error) {
// TODO(golang.org/issue/38714): thread tracing context through MVS.
- return previousVersion(r.loaderstate, context.TODO(), m)
+ return previousVersion(r.ld, context.TODO(), m)
}
diff --git a/src/cmd/go/internal/modload/query.go b/src/cmd/go/internal/modload/query.go
index b6bf0803c1..e7f30dfaf8 100644
--- a/src/cmd/go/internal/modload/query.go
+++ b/src/cmd/go/internal/modload/query.go
@@ -80,19 +80,19 @@ import (
//
// Query often returns a non-nil *RevInfo with a non-nil error,
// to provide an info.Origin that can allow the error to be cached.
-func Query(loaderstate *State, ctx context.Context, path, query, current string, allowed AllowedFunc) (*modfetch.RevInfo, error) {
+func Query(ld *Loader, ctx context.Context, path, query, current string, allowed AllowedFunc) (*modfetch.RevInfo, error) {
ctx, span := trace.StartSpan(ctx, "modload.Query "+path)
defer span.Done()
- return queryReuse(loaderstate, ctx, path, query, current, allowed, nil)
+ return queryReuse(ld, ctx, path, query, current, allowed, nil)
}
// queryReuse is like Query but also takes a map of module info that can be reused
// if the validation criteria in Origin are met.
-func queryReuse(loaderstate *State, ctx context.Context, path, query, current string, allowed AllowedFunc, reuse map[module.Version]*modinfo.ModulePublic) (*modfetch.RevInfo, error) {
+func queryReuse(ld *Loader, ctx context.Context, path, query, current string, allowed AllowedFunc, reuse map[module.Version]*modinfo.ModulePublic) (*modfetch.RevInfo, error) {
var info *modfetch.RevInfo
err := modfetch.TryProxies(func(proxy string) (err error) {
- info, err = queryProxy(loaderstate, ctx, proxy, path, query, current, allowed, reuse)
+ info, err = queryProxy(ld, ctx, proxy, path, query, current, allowed, reuse)
return err
})
return info, err
@@ -100,9 +100,9 @@ func queryReuse(loaderstate *State, ctx context.Context, path, query, current st
// checkReuse checks whether a revision of a given module
// for a given module may be reused, according to the information in origin.
-func checkReuse(loaderstate *State, ctx context.Context, m module.Version, old *codehost.Origin) error {
+func checkReuse(ld *Loader, ctx context.Context, m module.Version, old *codehost.Origin) error {
return modfetch.TryProxies(func(proxy string) error {
- repo, err := lookupRepo(loaderstate, ctx, proxy, m.Path)
+ repo, err := lookupRepo(ld, ctx, proxy, m.Path)
if err != nil {
return err
}
@@ -197,7 +197,7 @@ func (queryDisabledError) Error() string {
return fmt.Sprintf("cannot query module due to -mod=%s\n\t(%s)", cfg.BuildMod, cfg.BuildModReason)
}
-func queryProxy(loaderstate *State, ctx context.Context, proxy, path, query, current string, allowed AllowedFunc, reuse map[module.Version]*modinfo.ModulePublic) (*modfetch.RevInfo, error) {
+func queryProxy(ld *Loader, ctx context.Context, proxy, path, query, current string, allowed AllowedFunc, reuse map[module.Version]*modinfo.ModulePublic) (*modfetch.RevInfo, error) {
ctx, span := trace.StartSpan(ctx, "modload.queryProxy "+path+" "+query)
defer span.Done()
@@ -211,7 +211,7 @@ func queryProxy(loaderstate *State, ctx context.Context, proxy, path, query, cur
allowed = func(context.Context, module.Version) error { return nil }
}
- if loaderstate.MainModules.Contains(path) && (query == "upgrade" || query == "patch") {
+ if ld.MainModules.Contains(path) && (query == "upgrade" || query == "patch") {
m := module.Version{Path: path}
if err := allowed(ctx, m); err != nil {
return nil, fmt.Errorf("internal error: main module version is not allowed: %w", err)
@@ -223,7 +223,7 @@ func queryProxy(loaderstate *State, ctx context.Context, proxy, path, query, cur
return nil, fmt.Errorf("can't query specific version (%q) of standard-library module %q", query, path)
}
- repo, err := lookupRepo(loaderstate, ctx, proxy, path)
+ repo, err := lookupRepo(ld, ctx, proxy, path)
if err != nil {
return nil, err
}
@@ -296,7 +296,7 @@ func queryProxy(loaderstate *State, ctx context.Context, proxy, path, query, cur
return &clone
}
- releases, prereleases, err := qm.filterVersions(loaderstate, ctx, versions.List)
+ releases, prereleases, err := qm.filterVersions(ld, ctx, versions.List)
if err != nil {
return revWithOrigin(nil), err
}
@@ -569,7 +569,7 @@ func (qm *queryMatcher) allowsVersion(ctx context.Context, v string) bool {
//
// If the allowed predicate returns an error not equivalent to ErrDisallowed,
// filterVersions returns that error.
-func (qm *queryMatcher) filterVersions(loaderstate *State, ctx context.Context, versions []string) (releases, prereleases []string, err error) {
+func (qm *queryMatcher) filterVersions(ld *Loader, ctx context.Context, versions []string) (releases, prereleases []string, err error) {
needIncompatible := qm.preferIncompatible
var lastCompatible string
@@ -602,7 +602,7 @@ func (qm *queryMatcher) filterVersions(loaderstate *State, ctx context.Context,
// ignore any version with a higher (+incompatible) major version. (See
// https://golang.org/issue/34165.) Note that we even prefer a
// compatible pre-release over an incompatible release.
- ok, err := versionHasGoMod(loaderstate, ctx, module.Version{Path: qm.path, Version: lastCompatible})
+ ok, err := versionHasGoMod(ld, ctx, module.Version{Path: qm.path, Version: lastCompatible})
if err != nil {
return nil, nil, err
}
@@ -639,11 +639,11 @@ type QueryResult struct {
// QueryPackages is like QueryPattern, but requires that the pattern match at
// least one package and omits the non-package result (if any).
-func QueryPackages(loaderstate *State, ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) ([]QueryResult, error) {
- pkgMods, modOnly, err := QueryPattern(loaderstate, ctx, pattern, query, current, allowed)
+func QueryPackages(ld *Loader, ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) ([]QueryResult, error) {
+ pkgMods, modOnly, err := QueryPattern(ld, ctx, pattern, query, current, allowed)
if len(pkgMods) == 0 && err == nil {
- replacement := Replacement(loaderstate, modOnly.Mod)
+ replacement := Replacement(ld, modOnly.Mod)
return nil, &PackageNotInModuleError{
Mod: modOnly.Mod,
Replacement: replacement,
@@ -670,7 +670,7 @@ func QueryPackages(loaderstate *State, ctx context.Context, pattern, query strin
//
// QueryPattern always returns at least one QueryResult (which may be only
// modOnly) or a non-nil error.
-func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) (pkgMods []QueryResult, modOnly *QueryResult, err error) {
+func QueryPattern(ld *Loader, ctx context.Context, pattern, query string, current func(string) string, allowed AllowedFunc) (pkgMods []QueryResult, modOnly *QueryResult, err error) {
ctx, span := trace.StartSpan(ctx, "modload.QueryPattern "+pattern+" "+query)
defer span.Done()
@@ -693,15 +693,15 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
}
match = func(mod module.Version, roots []string, isLocal bool) *search.Match {
m := search.NewMatch(pattern)
- matchPackages(loaderstate, ctx, m, imports.AnyTags(), omitStd, []module.Version{mod})
+ matchPackages(ld, ctx, m, imports.AnyTags(), omitStd, []module.Version{mod})
return m
}
} else {
match = func(mod module.Version, roots []string, isLocal bool) *search.Match {
m := search.NewMatch(pattern)
prefix := mod.Path
- if loaderstate.MainModules.Contains(mod.Path) {
- prefix = loaderstate.MainModules.PathPrefix(module.Version{Path: mod.Path})
+ if ld.MainModules.Contains(mod.Path) {
+ prefix = ld.MainModules.PathPrefix(module.Version{Path: mod.Path})
}
for _, root := range roots {
if _, ok, err := dirInModule(pattern, prefix, root, isLocal); err != nil {
@@ -715,8 +715,8 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
}
var mainModuleMatches []module.Version
- for _, mainModule := range loaderstate.MainModules.Versions() {
- m := match(mainModule, loaderstate.modRoots, true)
+ for _, mainModule := range ld.MainModules.Versions() {
+ m := match(mainModule, ld.modRoots, true)
if len(m.Pkgs) > 0 {
if query != "upgrade" && query != "patch" {
return nil, nil, &QueryMatchesPackagesInMainModuleError{
@@ -756,7 +756,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
var (
results []QueryResult
- candidateModules = modulePrefixesExcludingTarget(loaderstate, base)
+ candidateModules = modulePrefixesExcludingTarget(ld, base)
)
if len(candidateModules) == 0 {
if modOnly != nil {
@@ -766,7 +766,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
MainModules: mainModuleMatches,
Pattern: pattern,
Query: query,
- PatternIsModule: loaderstate.MainModules.Contains(pattern),
+ PatternIsModule: ld.MainModules.Contains(pattern),
}
} else {
return nil, nil, &PackageNotInModuleError{
@@ -784,7 +784,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
pathCurrent := current(path)
r.Mod.Path = path
- r.Rev, err = queryProxy(loaderstate, ctx, proxy, path, query, pathCurrent, allowed, nil)
+ r.Rev, err = queryProxy(ld, ctx, proxy, path, query, pathCurrent, allowed, nil)
if err != nil {
return r, err
}
@@ -792,7 +792,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
if gover.IsToolchain(r.Mod.Path) {
return r, nil
}
- root, isLocal, err := fetch(loaderstate, ctx, r.Mod)
+ root, isLocal, err := fetch(ld, ctx, r.Mod)
if err != nil {
return r, err
}
@@ -802,7 +802,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
if err := firstError(m); err != nil {
return r, err
}
- replacement := Replacement(loaderstate, r.Mod)
+ replacement := Replacement(ld, r.Mod)
return r, &PackageNotInModuleError{
Mod: r.Mod,
Replacement: replacement,
@@ -813,7 +813,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
return r, nil
}
- allResults, err := queryPrefixModules(loaderstate, ctx, candidateModules, queryModule)
+ allResults, err := queryPrefixModules(ld, ctx, candidateModules, queryModule)
results = allResults[:0]
for _, r := range allResults {
if len(r.Packages) == 0 {
@@ -829,7 +829,7 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
return nil, nil, &QueryMatchesMainModulesError{
Pattern: pattern,
Query: query,
- PatternIsModule: loaderstate.MainModules.Contains(pattern),
+ PatternIsModule: ld.MainModules.Contains(pattern),
}
}
return slices.Clip(results), modOnly, err
@@ -840,11 +840,11 @@ func QueryPattern(loaderstate *State, ctx context.Context, pattern, query string
// itself, sorted by descending length. Prefixes that are not valid module paths
// but are valid package paths (like "m" or "example.com/.gen") are included,
// since they might be replaced.
-func modulePrefixesExcludingTarget(loaderstate *State, path string) []string {
+func modulePrefixesExcludingTarget(ld *Loader, path string) []string {
prefixes := make([]string, 0, strings.Count(path, "/")+1)
mainModulePrefixes := make(map[string]bool)
- for _, m := range loaderstate.MainModules.Versions() {
+ for _, m := range ld.MainModules.Versions() {
mainModulePrefixes[m.Path] = true
}
@@ -865,7 +865,7 @@ func modulePrefixesExcludingTarget(loaderstate *State, path string) []string {
return prefixes
}
-func queryPrefixModules(loaderstate *State, ctx context.Context, candidateModules []string, queryModule func(ctx context.Context, path string) (QueryResult, error)) (found []QueryResult, err error) {
+func queryPrefixModules(ld *Loader, ctx context.Context, candidateModules []string, queryModule func(ctx context.Context, path string) (QueryResult, error)) (found []QueryResult, err error) {
ctx, span := trace.StartSpan(ctx, "modload.queryPrefixModules")
defer span.Done()
@@ -907,7 +907,7 @@ func queryPrefixModules(loaderstate *State, ctx context.Context, candidateModule
case *PackageNotInModuleError:
// Given the option, prefer to attribute “package not in module”
// to modules other than the main one.
- if noPackage == nil || loaderstate.MainModules.Contains(noPackage.Mod.Path) {
+ if noPackage == nil || ld.MainModules.Contains(noPackage.Mod.Path) {
noPackage = rErr
}
case *NoMatchingVersionError:
@@ -1098,8 +1098,8 @@ func (e *PackageNotInModuleError) ImportPath() string {
// go.mod with different content. Second, if we don't fetch the .zip, then
// we don't need to verify it in go.sum. This makes 'go list -m -u' faster
// and simpler.
-func versionHasGoMod(loaderstate *State, _ context.Context, m module.Version) (bool, error) {
- _, data, err := rawGoModData(loaderstate, m)
+func versionHasGoMod(ld *Loader, _ context.Context, m module.Version) (bool, error) {
+ _, data, err := rawGoModData(ld, m)
if err != nil {
return false, err
}
@@ -1119,20 +1119,20 @@ type versionRepo interface {
var _ versionRepo = modfetch.Repo(nil)
-func lookupRepo(loaderstate *State, ctx context.Context, proxy, path string) (repo versionRepo, err error) {
+func lookupRepo(ld *Loader, ctx context.Context, proxy, path string) (repo versionRepo, err error) {
if path != "go" && path != "toolchain" {
err = module.CheckPath(path)
}
if err == nil {
- repo = loaderstate.Fetcher().Lookup(ctx, proxy, path)
+ repo = ld.Fetcher().Lookup(ctx, proxy, path)
} else {
repo = emptyRepo{path: path, err: err}
}
- if loaderstate.MainModules == nil {
+ if ld.MainModules == nil {
return repo, err
- } else if _, ok := loaderstate.MainModules.HighestReplaced()[path]; ok {
- return &replacementRepo{repo: repo, loaderstate: loaderstate}, nil
+ } else if _, ok := ld.MainModules.HighestReplaced()[path]; ok {
+ return &replacementRepo{repo: repo, ld: ld}, nil
}
return repo, err
@@ -1167,8 +1167,8 @@ func (er emptyRepo) Latest(ctx context.Context) (*modfetch.RevInfo, error) { ret
// modules, so a replacementRepo should only be constructed for a module that
// actually has one or more valid replacements.
type replacementRepo struct {
- repo versionRepo
- loaderstate *State
+ repo versionRepo
+ ld *Loader
}
var _ versionRepo = (*replacementRepo)(nil)
@@ -1191,8 +1191,8 @@ func (rr *replacementRepo) Versions(ctx context.Context, prefix string) (*modfet
}
versions := repoVersions.List
- for _, mm := range rr.loaderstate.MainModules.Versions() {
- if index := rr.loaderstate.MainModules.Index(mm); index != nil && len(index.replace) > 0 {
+ for _, mm := range rr.ld.MainModules.Versions() {
+ if index := rr.ld.MainModules.Index(mm); index != nil && len(index.replace) > 0 {
path := rr.ModulePath()
for m := range index.replace {
if m.Path == path && strings.HasPrefix(m.Version, prefix) && m.Version != "" && !module.IsPseudoVersion(m.Version) {
@@ -1220,8 +1220,8 @@ func (rr *replacementRepo) Stat(ctx context.Context, rev string) (*modfetch.RevI
return info, err
}
var hasReplacements bool
- for _, v := range rr.loaderstate.MainModules.Versions() {
- if index := rr.loaderstate.MainModules.Index(v); index != nil && len(index.replace) > 0 {
+ for _, v := range rr.ld.MainModules.Versions() {
+ if index := rr.ld.MainModules.Index(v); index != nil && len(index.replace) > 0 {
hasReplacements = true
}
}
@@ -1244,7 +1244,7 @@ func (rr *replacementRepo) Stat(ctx context.Context, rev string) (*modfetch.RevI
}
}
- if r := Replacement(rr.loaderstate, module.Version{Path: path, Version: v}); r.Path == "" {
+ if r := Replacement(rr.ld, module.Version{Path: path, Version: v}); r.Path == "" {
return info, err
}
return rr.replacementStat(v)
@@ -1254,7 +1254,7 @@ func (rr *replacementRepo) Latest(ctx context.Context) (*modfetch.RevInfo, error
info, err := rr.repo.Latest(ctx)
path := rr.ModulePath()
- if v, ok := rr.loaderstate.MainModules.HighestReplaced()[path]; ok {
+ if v, ok := rr.ld.MainModules.HighestReplaced()[path]; ok {
if v == "" {
// The only replacement is a wildcard that doesn't specify a version, so
// synthesize a pseudo-version with an appropriate major version and a
diff --git a/src/cmd/go/internal/modload/query_test.go b/src/cmd/go/internal/modload/query_test.go
index a465fab5db..261240715c 100644
--- a/src/cmd/go/internal/modload/query_test.go
+++ b/src/cmd/go/internal/modload/query_test.go
@@ -168,7 +168,7 @@ func TestQuery(t *testing.T) {
ctx := context.Background()
for _, tt := range queryTests {
- loaderstate := NewState()
+ ld := NewLoader()
allow := tt.allow
if allow == "" {
allow = "*"
@@ -183,7 +183,7 @@ func TestQuery(t *testing.T) {
t.Run(strings.ReplaceAll(tt.path, "/", "_")+"/"+tt.query+"/"+tt.current+"/"+allow, func(t *testing.T) {
t.Parallel()
- info, err := Query(loaderstate, ctx, tt.path, tt.query, tt.current, allowed)
+ info, err := Query(ld, ctx, tt.path, tt.query, tt.current, allowed)
if tt.err != "" {
if err == nil {
t.Errorf("Query(_, %q, %q, %q, %v) = %v, want error %q", tt.path, tt.query, tt.current, allow, info.Version, tt.err)
diff --git a/src/cmd/go/internal/modload/search.go b/src/cmd/go/internal/modload/search.go
index c45808635d..a08c01479f 100644
--- a/src/cmd/go/internal/modload/search.go
+++ b/src/cmd/go/internal/modload/search.go
@@ -41,7 +41,7 @@ const (
// matchPackages is like m.MatchPackages, but uses a local variable (rather than
// a global) for tags, can include or exclude packages in the standard library,
// and is restricted to the given list of modules.
-func matchPackages(loaderstate *State, ctx context.Context, m *search.Match, tags map[string]bool, filter stdFilter, modules []module.Version) {
+func matchPackages(ld *Loader, ctx context.Context, m *search.Match, tags map[string]bool, filter stdFilter, modules []module.Version) {
ctx, span := trace.StartSpan(ctx, "modload.matchPackages")
defer span.Done()
@@ -74,7 +74,7 @@ func matchPackages(loaderstate *State, ctx context.Context, m *search.Match, tag
)
q := par.NewQueue(runtime.GOMAXPROCS(0))
- ignorePatternsMap := parseIgnorePatterns(loaderstate, ctx, treeCanMatch, modules)
+ ignorePatternsMap := parseIgnorePatterns(ld, ctx, treeCanMatch, modules)
walkPkgs := func(root, importPathRoot string, prune pruning) {
_, span := trace.StartSpan(ctx, "walkPkgs "+root)
defer span.Done()
@@ -171,13 +171,13 @@ func matchPackages(loaderstate *State, ctx context.Context, m *search.Match, tag
}
if cfg.BuildMod == "vendor" {
- for _, mod := range loaderstate.MainModules.Versions() {
- if modRoot := loaderstate.MainModules.ModRoot(mod); modRoot != "" {
- walkPkgs(modRoot, loaderstate.MainModules.PathPrefix(mod), pruneGoMod|pruneVendor)
+ for _, mod := range ld.MainModules.Versions() {
+ if modRoot := ld.MainModules.ModRoot(mod); modRoot != "" {
+ walkPkgs(modRoot, ld.MainModules.PathPrefix(mod), pruneGoMod|pruneVendor)
}
}
- if loaderstate.HasModRoot() {
- walkPkgs(VendorDir(loaderstate), "", pruneVendor)
+ if ld.HasModRoot() {
+ walkPkgs(VendorDir(ld), "", pruneVendor)
}
return
}
@@ -191,16 +191,16 @@ func matchPackages(loaderstate *State, ctx context.Context, m *search.Match, tag
root, modPrefix string
isLocal bool
)
- if loaderstate.MainModules.Contains(mod.Path) {
- if loaderstate.MainModules.ModRoot(mod) == "" {
+ if ld.MainModules.Contains(mod.Path) {
+ if ld.MainModules.ModRoot(mod) == "" {
continue // If there is no main module, we can't search in it.
}
- root = loaderstate.MainModules.ModRoot(mod)
- modPrefix = loaderstate.MainModules.PathPrefix(mod)
+ root = ld.MainModules.ModRoot(mod)
+ modPrefix = ld.MainModules.PathPrefix(mod)
isLocal = true
} else {
var err error
- root, isLocal, err = fetch(loaderstate, ctx, mod)
+ root, isLocal, err = fetch(ld, ctx, mod)
if err != nil {
m.AddError(err)
continue
@@ -283,20 +283,20 @@ func walkFromIndex(index *modindex.Module, importPathRoot string, isMatch, treeC
//
// If m is the zero module.Version, MatchInModule matches the pattern
// against the standard library (std and cmd) in GOROOT/src.
-func MatchInModule(loaderstate *State, ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match {
+func MatchInModule(ld *Loader, ctx context.Context, pattern string, m module.Version, tags map[string]bool) *search.Match {
match := search.NewMatch(pattern)
if m == (module.Version{}) {
- matchPackages(loaderstate, ctx, match, tags, includeStd, nil)
+ matchPackages(ld, ctx, match, tags, includeStd, nil)
}
- LoadModFile(loaderstate, ctx) // Sets Target, needed by fetch and matchPackages.
+ LoadModFile(ld, ctx) // Sets Target, needed by fetch and matchPackages.
if !match.IsLiteral() {
- matchPackages(loaderstate, ctx, match, tags, omitStd, []module.Version{m})
+ matchPackages(ld, ctx, match, tags, omitStd, []module.Version{m})
return match
}
- root, isLocal, err := fetch(loaderstate, ctx, m)
+ root, isLocal, err := fetch(ld, ctx, m)
if err != nil {
match.Errs = []error{err}
return match
@@ -322,7 +322,7 @@ func MatchInModule(loaderstate *State, ctx context.Context, pattern string, m mo
// parseIgnorePatterns collects all ignore patterns associated with the
// provided list of modules.
// It returns a map of module root -> *search.IgnorePatterns.
-func parseIgnorePatterns(loaderstate *State, ctx context.Context, treeCanMatch func(string) bool, modules []module.Version) map[string]*search.IgnorePatterns {
+func parseIgnorePatterns(ld *Loader, ctx context.Context, treeCanMatch func(string) bool, modules []module.Version) map[string]*search.IgnorePatterns {
ignorePatternsMap := make(map[string]*search.IgnorePatterns)
for _, mod := range modules {
if gover.IsToolchain(mod.Path) || !treeCanMatch(mod.Path) {
@@ -330,12 +330,12 @@ func parseIgnorePatterns(loaderstate *State, ctx context.Context, treeCanMatch f
}
var modRoot string
var ignorePatterns []string
- if loaderstate.MainModules.Contains(mod.Path) {
- modRoot = loaderstate.MainModules.ModRoot(mod)
+ if ld.MainModules.Contains(mod.Path) {
+ modRoot = ld.MainModules.ModRoot(mod)
if modRoot == "" {
continue
}
- modIndex := loaderstate.MainModules.Index(mod)
+ modIndex := ld.MainModules.Index(mod)
if modIndex == nil {
continue
}
@@ -344,11 +344,11 @@ func parseIgnorePatterns(loaderstate *State, ctx context.Context, treeCanMatch f
// Skip getting ignore patterns for vendored modules because they
// do not have go.mod files.
var err error
- modRoot, _, err = fetch(loaderstate, ctx, mod)
+ modRoot, _, err = fetch(ld, ctx, mod)
if err != nil {
continue
}
- summary, err := goModSummary(loaderstate, mod)
+ summary, err := goModSummary(ld, mod)
if err != nil {
continue
}
diff --git a/src/cmd/go/internal/modload/vendor.go b/src/cmd/go/internal/modload/vendor.go
index 9956bcdb12..577e8f6776 100644
--- a/src/cmd/go/internal/modload/vendor.go
+++ b/src/cmd/go/internal/modload/vendor.go
@@ -140,10 +140,10 @@ func readVendorList(vendorDir string) {
// checkVendorConsistency verifies that the vendor/modules.txt file matches (if
// go 1.14) or at least does not contradict (go 1.13 or earlier) the
// requirements and replacements listed in the main module's go.mod file.
-func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFiles []*modfile.File, modRoots []string) {
+func checkVendorConsistency(ld *Loader, indexes []*modFileIndex, modFiles []*modfile.File, modRoots []string) {
// readVendorList only needs the main module to get the directory
// the vendor directory is in.
- readVendorList(VendorDir(loaderstate))
+ readVendorList(VendorDir(ld))
if len(modFiles) < 1 {
// We should never get here if there are zero modfiles. Either
@@ -154,7 +154,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
}
pre114 := false
- if !loaderstate.inWorkspaceMode() { // workspace mode was added after Go 1.14
+ if !ld.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)))
}
@@ -215,8 +215,8 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
continue // Don't print the same error more than once
}
seenrep[r.Old] = true
- rNew, modRoot, replacementSource := replacementFrom(loaderstate, r.Old)
- rNewCanonical := canonicalizeReplacePath(loaderstate, rNew, modRoot)
+ rNew, modRoot, replacementSource := replacementFrom(ld, r.Old)
+ rNewCanonical := canonicalizeReplacePath(ld, rNew, modRoot)
vr := vendorMeta[r.Old].Replacement
if vr == (module.Version{}) {
if rNewCanonical == (module.Version{}) {
@@ -236,8 +236,8 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
for _, modFile := range modFiles {
checkReplace(modFile.Replace)
}
- if loaderstate.MainModules.workFile != nil {
- checkReplace(loaderstate.MainModules.workFile.Replace)
+ if ld.MainModules.workFile != nil {
+ checkReplace(ld.MainModules.workFile.Replace)
}
for _, mod := range vendorList {
@@ -252,7 +252,7 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
}
if !foundRequire {
article := ""
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
article = "a "
}
vendErrorf(mod, "is marked as explicit in vendor/modules.txt, but not explicitly required in %vgo.mod", article)
@@ -262,9 +262,9 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
}
for _, mod := range vendorReplaced {
- r := Replacement(loaderstate, mod)
+ r := Replacement(ld, mod)
replacementSource := "go.mod"
- if loaderstate.inWorkspaceMode() {
+ if ld.inWorkspaceMode() {
replacementSource = "the workspace"
}
if r == (module.Version{}) {
@@ -276,9 +276,9 @@ func checkVendorConsistency(loaderstate *State, indexes []*modFileIndex, modFile
if vendErrors.Len() > 0 {
subcmd := "mod"
- if loaderstate.inWorkspaceMode() {
+ if ld.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)
+ 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(ld)), vendErrors, subcmd)
}
}
diff --git a/src/cmd/go/internal/run/run.go b/src/cmd/go/internal/run/run.go
index a1ad91ed85..1725c7d04f 100644
--- a/src/cmd/go/internal/run/run.go
+++ b/src/cmd/go/internal/run/run.go
@@ -75,22 +75,22 @@ func init() {
}
func runRun(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if shouldUseOutsideModuleMode(args) {
// Set global module flags for 'go run cmd@version'.
// This must be done before modload.Init, but we need to call work.BuildInit
// before loading packages, since it affects package locations, e.g.,
// for -race and -msan.
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.RootMode = modload.NoRoot
- moduleLoaderState.AllowMissingModuleImports()
- modload.Init(moduleLoaderState)
+ moduleLoader.ForceUseModules = true
+ moduleLoader.RootMode = modload.NoRoot
+ moduleLoader.AllowMissingModuleImports()
+ modload.Init(moduleLoader)
} else {
- moduleLoaderState.InitWorkfile()
+ moduleLoader.InitWorkfile()
}
- work.BuildInit(moduleLoaderState)
- b := work.NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
+ work.BuildInit(moduleLoader)
+ b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -112,18 +112,18 @@ func runRun(ctx context.Context, cmd *base.Command, args []string) {
base.Fatalf("go: cannot run *_test.go files (%s)", file)
}
}
- p = load.GoFilesPackage(moduleLoaderState, ctx, pkgOpts, files)
+ p = load.GoFilesPackage(moduleLoader, ctx, pkgOpts, files)
} else if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
arg := args[0]
var pkgs []*load.Package
if strings.Contains(arg, "@") && !build.IsLocalImport(arg) && !filepath.IsAbs(arg) {
var err error
- pkgs, err = load.PackagesAndErrorsOutsideModule(moduleLoaderState, ctx, pkgOpts, args[:1])
+ pkgs, err = load.PackagesAndErrorsOutsideModule(moduleLoader, ctx, pkgOpts, args[:1])
if err != nil {
base.Fatal(err)
}
} else {
- pkgs = load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, args[:1])
+ pkgs = load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, args[:1])
}
if len(pkgs) == 0 {
@@ -145,7 +145,7 @@ func runRun(ctx context.Context, cmd *base.Command, args []string) {
load.CheckPackageErrors([]*load.Package{p})
if cfg.BuildCover {
- load.PrepareForCoverageBuild(moduleLoaderState, []*load.Package{p})
+ load.PrepareForCoverageBuild(moduleLoader, []*load.Package{p})
}
p.Internal.OmitDebug = true
@@ -171,7 +171,7 @@ func runRun(ctx context.Context, cmd *base.Command, args []string) {
p.Internal.ExeName = p.DefaultExecName()
}
- a1 := b.LinkAction(moduleLoaderState, work.ModeBuild, work.ModeBuild, p)
+ a1 := b.LinkAction(moduleLoader, work.ModeBuild, work.ModeBuild, p)
a1.CacheExecutable = true
a := &work.Action{Mode: "go run", Actor: work.ActorFunc(buildRunProgram), Args: cmdArgs, Deps: []*work.Action{a1}}
b.Do(ctx, a)
diff --git a/src/cmd/go/internal/telemetrystats/telemetrystats.go b/src/cmd/go/internal/telemetrystats/telemetrystats.go
index 81a6e1e175..f975a759a1 100644
--- a/src/cmd/go/internal/telemetrystats/telemetrystats.go
+++ b/src/cmd/go/internal/telemetrystats/telemetrystats.go
@@ -24,7 +24,7 @@ func Increment() {
func incrementConfig() {
// TODO(jitsu): Telemetry for the go/mode counters should eventually be
// moved to modload.Init()
- s := modload.NewState()
+ s := modload.NewLoader()
if !s.WillBeEnabled() {
counter.Inc("go/mode:gopath")
} else if workfile := s.FindGoWork(base.Cwd()); workfile != "" {
diff --git a/src/cmd/go/internal/test/test.go b/src/cmd/go/internal/test/test.go
index 59474138ad..2473c243e3 100644
--- a/src/cmd/go/internal/test/test.go
+++ b/src/cmd/go/internal/test/test.go
@@ -692,9 +692,9 @@ var defaultVetFlags = []string{
}
func runTest(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
pkgArgs, testArgs = testFlags(args)
- moduleLoaderState.InitWorkfile() // The test command does custom flag processing; initialize workspaces after that.
+ moduleLoader.InitWorkfile() // The test command does custom flag processing; initialize workspaces after that.
if cfg.DebugTrace != "" {
var close func() error
@@ -715,13 +715,13 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
work.FindExecCmd() // initialize cached result
- work.BuildInit(moduleLoaderState)
+ work.BuildInit(moduleLoader)
work.VetFlags = testVet.flags
work.VetExplicit = testVet.explicit
work.VetTool = base.Tool("vet")
pkgOpts := load.PackageOpts{ModResolveTests: true}
- pkgs = load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, pkgArgs)
+ pkgs = load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, pkgArgs)
// We *don't* call load.CheckPackageErrors here because we want to report
// loading errors as per-package test setup errors later.
if len(pkgs) == 0 {
@@ -747,12 +747,12 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
// the module cache (or permanently alter the behavior of std tests for all
// users) by writing the failing input to the package's testdata directory.
// (See https://golang.org/issue/48495 and cmd/internal/fuzztest/test_fuzz_modcache.txt.)
- mainMods := moduleLoaderState.MainModules
+ mainMods := moduleLoader.MainModules
if m := pkgs[0].Module; m != nil && m.Path != "" {
if !mainMods.Contains(m.Path) {
base.Fatalf("cannot use -fuzz flag on package outside the main module")
}
- } else if pkgs[0].Standard && moduleLoaderState.Enabled() {
+ } else if pkgs[0].Standard && moduleLoader.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
@@ -865,7 +865,7 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
}
}
- b := work.NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
+ b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -876,15 +876,15 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
var writeCoverMetaAct *work.Action
if cfg.BuildCoverPkg != nil {
- match := make([]func(*modload.State, *load.Package) bool, len(cfg.BuildCoverPkg))
+ match := make([]func(*modload.Loader, *load.Package) bool, len(cfg.BuildCoverPkg))
for i := range cfg.BuildCoverPkg {
match[i] = load.MatchPackage(cfg.BuildCoverPkg[i], base.Cwd())
}
// Select for coverage all dependencies matching the -coverpkg
// patterns.
- plist := load.TestPackageList(moduleLoaderState, ctx, pkgOpts, pkgs)
- testCoverPkgs = load.SelectCoverPackages(moduleLoaderState, plist, match, "test")
+ plist := load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs)
+ testCoverPkgs = load.SelectCoverPackages(moduleLoader, plist, match, "test")
if len(testCoverPkgs) > 0 {
// create a new singleton action that will collect up the
// meta-data files from all of the packages mentioned in
@@ -962,7 +962,7 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
"testing": true,
"time": true,
}
- for _, p := range load.TestPackageList(moduleLoaderState, ctx, pkgOpts, pkgs) {
+ for _, p := range load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs) {
if !skipInstrumentation[p.ImportPath] {
p.Internal.FuzzInstrument = true
}
@@ -992,7 +992,7 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
// happens we'll wind up building the Q compile action
// before updating its deps to include sync/atomic).
if cfg.BuildCoverMode == "atomic" && p.ImportPath != "sync/atomic" {
- load.EnsureImport(moduleLoaderState, p, "sync/atomic")
+ load.EnsureImport(moduleLoader, p, "sync/atomic")
}
// Tag the package for static meta-data generation if no
// test files (this works only with the new coverage
@@ -1059,7 +1059,7 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
reportSetupFailed(firstErrPkg, firstErrPkg.Error)
continue
}
- buildTest, runTest, printTest, perr, err := builderTest(moduleLoaderState, b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
+ buildTest, runTest, printTest, perr, err := builderTest(moduleLoader, b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
if err != nil {
reportErr(perr, err)
reportSetupFailed(perr, err)
@@ -1140,7 +1140,7 @@ var windowsBadWords = []string{
"update",
}
-func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Context, pkgOpts load.PackageOpts, p *load.Package, imported bool, writeCoverMetaAct *work.Action) (buildAction, runAction, printAction *work.Action, perr *load.Package, err error) {
+func builderTest(ld *modload.Loader, b *work.Builder, ctx context.Context, pkgOpts load.PackageOpts, p *load.Package, imported bool, writeCoverMetaAct *work.Action) (buildAction, runAction, printAction *work.Action, perr *load.Package, err error) {
if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
run := &work.Action{
@@ -1168,7 +1168,7 @@ func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Contex
run.Deps = append(run.Deps, writeCoverMetaAct)
writeCoverMetaAct.Deps = append(writeCoverMetaAct.Deps, build)
}
- addTestVet(loaderstate, b, p, run, nil)
+ addTestVet(ld, b, p, run, nil)
print := &work.Action{
Mode: "test print",
Actor: work.ActorFunc(builderPrintTest),
@@ -1192,7 +1192,7 @@ func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Contex
Paths: cfg.BuildCoverPkg,
}
}
- pmain, ptest, pxtest, perr := load.TestPackagesFor(loaderstate, ctx, pkgOpts, p, cover)
+ pmain, ptest, pxtest, perr := load.TestPackagesFor(ld, ctx, pkgOpts, p, cover)
if perr != nil {
return nil, nil, nil, perr, perr.Error
}
@@ -1232,7 +1232,7 @@ func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Contex
}
}
- a := b.LinkAction(loaderstate, work.ModeBuild, work.ModeBuild, pmain)
+ a := b.LinkAction(ld, work.ModeBuild, work.ModeBuild, pmain)
a.Target = testDir + testBinary + cfg.ExeSuffix
if cfg.Goos == "windows" {
// There are many reserved words on Windows that,
@@ -1358,10 +1358,10 @@ func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Contex
}
if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
- addTestVet(loaderstate, b, ptest, vetRunAction, installAction)
+ addTestVet(ld, b, ptest, vetRunAction, installAction)
}
if pxtest != nil {
- addTestVet(loaderstate, b, pxtest, vetRunAction, installAction)
+ addTestVet(ld, b, pxtest, vetRunAction, installAction)
}
if installAction != nil {
@@ -1376,12 +1376,12 @@ func builderTest(loaderstate *modload.State, b *work.Builder, ctx context.Contex
return buildAction, runAction, printAction, nil, nil
}
-func addTestVet(loaderstate *modload.State, b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
+func addTestVet(ld *modload.Loader, b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
if testVet.off {
return
}
- vet := b.VetAction(loaderstate, work.ModeBuild, work.ModeBuild, false, p)
+ vet := b.VetAction(ld, work.ModeBuild, work.ModeBuild, false, p)
runAction.Deps = append(runAction.Deps, vet)
// Install will clean the build directory.
// Make sure vet runs first.
diff --git a/src/cmd/go/internal/tool/tool.go b/src/cmd/go/internal/tool/tool.go
index b62e626a69..a84b2e8ccb 100644
--- a/src/cmd/go/internal/tool/tool.go
+++ b/src/cmd/go/internal/tool/tool.go
@@ -89,10 +89,10 @@ func init() {
}
func runTool(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if len(args) == 0 {
counter.Inc("go/subcommand:tool")
- listTools(moduleLoaderState, ctx)
+ listTools(moduleLoader, ctx)
return
}
toolName := args[0]
@@ -120,14 +120,14 @@ func runTool(ctx context.Context, cmd *base.Command, args []string) {
if tool := loadBuiltinTool(toolName); tool != "" {
// Increment a counter for the tool subcommand with the tool name.
counter.Inc("go/subcommand:tool-" + toolName)
- buildAndRunBuiltinTool(moduleLoaderState, ctx, toolName, tool, args[1:])
+ buildAndRunBuiltinTool(moduleLoader, ctx, toolName, tool, args[1:])
return
}
// Try to build and run mod tool.
- tool := loadModTool(moduleLoaderState, ctx, toolName)
+ tool := loadModTool(moduleLoader, ctx, toolName)
if tool != "" {
- buildAndRunModtool(moduleLoaderState, ctx, toolName, tool, args[1:])
+ buildAndRunModtool(moduleLoader, ctx, toolName, tool, args[1:])
return
}
@@ -144,7 +144,7 @@ func runTool(ctx context.Context, cmd *base.Command, args []string) {
}
// listTools prints a list of the available tools in the tools directory.
-func listTools(loaderstate *modload.State, ctx context.Context) {
+func listTools(ld *modload.Loader, ctx context.Context) {
f, err := os.Open(build.ToolDir)
if err != nil {
fmt.Fprintf(os.Stderr, "go: no tool directory: %s\n", err)
@@ -176,9 +176,9 @@ func listTools(loaderstate *modload.State, ctx context.Context) {
fmt.Println(name)
}
- loaderstate.InitWorkfile()
- modload.LoadModFile(loaderstate, ctx)
- modTools := slices.Sorted(maps.Keys(loaderstate.MainModules.Tools()))
+ ld.InitWorkfile()
+ modload.LoadModFile(ld, ctx)
+ modTools := slices.Sorted(maps.Keys(ld.MainModules.Tools()))
seen := make(map[string]bool) // aliases we've seen already
for _, tool := range modTools {
alias := defaultExecName(tool)
@@ -282,12 +282,12 @@ func loadBuiltinTool(toolName string) string {
return cmdTool
}
-func loadModTool(loaderstate *modload.State, ctx context.Context, name string) string {
- loaderstate.InitWorkfile()
- modload.LoadModFile(loaderstate, ctx)
+func loadModTool(ld *modload.Loader, ctx context.Context, name string) string {
+ ld.InitWorkfile()
+ modload.LoadModFile(ld, ctx)
matches := []string{}
- for tool := range loaderstate.MainModules.Tools() {
+ for tool := range ld.MainModules.Tools() {
if tool == name || defaultExecName(tool) == name {
matches = append(matches, tool)
}
@@ -331,7 +331,7 @@ func builtTool(runAction *work.Action) string {
return linkAction.BuiltTarget()
}
-func buildAndRunBuiltinTool(loaderstate *modload.State, ctx context.Context, toolName, tool string, args []string) {
+func buildAndRunBuiltinTool(ld *modload.Loader, ctx context.Context, toolName, tool string, args []string) {
// Override GOOS and GOARCH for the build to build the tool using
// the same GOOS and GOARCH as this go command.
cfg.ForceHost()
@@ -339,17 +339,17 @@ func buildAndRunBuiltinTool(loaderstate *modload.State, ctx context.Context, too
// Ignore go.mod and go.work: we don't need them, and we want to be able
// to run the tool even if there's an issue with the module or workspace the
// user happens to be in.
- loaderstate.RootMode = modload.NoRoot
+ ld.RootMode = modload.NoRoot
runFunc := func(b *work.Builder, ctx context.Context, a *work.Action) error {
cmdline := str.StringList(builtTool(a), a.Args)
return runBuiltTool(toolName, nil, cmdline)
}
- buildAndRunTool(loaderstate, ctx, tool, args, runFunc)
+ buildAndRunTool(ld, ctx, tool, args, runFunc)
}
-func buildAndRunModtool(loaderstate *modload.State, ctx context.Context, toolName, tool string, args []string) {
+func buildAndRunModtool(ld *modload.Loader, ctx context.Context, toolName, tool string, args []string) {
runFunc := func(b *work.Builder, ctx context.Context, a *work.Action) error {
// Use the ExecCmd to run the binary, as go run does. ExecCmd allows users
// to provide a runner to run the binary, for example a simulator for binaries
@@ -363,12 +363,12 @@ func buildAndRunModtool(loaderstate *modload.State, ctx context.Context, toolNam
return runBuiltTool(toolName, env, cmdline)
}
- buildAndRunTool(loaderstate, ctx, tool, args, runFunc)
+ buildAndRunTool(ld, ctx, tool, args, runFunc)
}
-func buildAndRunTool(loaderstate *modload.State, ctx context.Context, tool string, args []string, runTool work.ActorFunc) {
- work.BuildInit(loaderstate)
- b := work.NewBuilder("", loaderstate.VendorDirOrEmpty)
+func buildAndRunTool(ld *modload.Loader, ctx context.Context, tool string, args []string, runTool work.ActorFunc) {
+ work.BuildInit(ld)
+ b := work.NewBuilder("", ld.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -376,11 +376,11 @@ func buildAndRunTool(loaderstate *modload.State, ctx context.Context, tool strin
}()
pkgOpts := load.PackageOpts{MainOnly: true}
- p := load.PackagesAndErrors(loaderstate, ctx, pkgOpts, []string{tool})[0]
+ p := load.PackagesAndErrors(ld, ctx, pkgOpts, []string{tool})[0]
p.Internal.OmitDebug = true
p.Internal.ExeName = p.DefaultExecName()
- a1 := b.LinkAction(loaderstate, work.ModeBuild, work.ModeBuild, p)
+ a1 := b.LinkAction(ld, work.ModeBuild, work.ModeBuild, p)
a1.CacheExecutable = true
a := &work.Action{Mode: "go tool", Actor: runTool, Args: args, Deps: []*work.Action{a1}}
b.Do(ctx, a)
diff --git a/src/cmd/go/internal/toolchain/select.go b/src/cmd/go/internal/toolchain/select.go
index e7a9af793c..7aa2a4ce8e 100644
--- a/src/cmd/go/internal/toolchain/select.go
+++ b/src/cmd/go/internal/toolchain/select.go
@@ -96,11 +96,11 @@ var (
// It must be called early in startup.
// See https://go.dev/doc/toolchain#select.
func Select() {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
log.SetPrefix("go: ")
defer log.SetPrefix("")
- if !moduleLoaderState.WillBeEnabled() {
+ if !moduleLoader.WillBeEnabled() {
return
}
@@ -173,7 +173,7 @@ func Select() {
gotoolchain = minToolchain
if mode == "auto" || mode == "path" {
// Read go.mod to find new minimum and suggested toolchain.
- file, goVers, toolchain := modGoToolchain(moduleLoaderState)
+ file, goVers, toolchain := modGoToolchain(moduleLoader)
gover.Startup.AutoFile = file
if toolchain == "default" {
// "default" means always use the default toolchain,
@@ -233,7 +233,7 @@ func Select() {
}
}
}
- maybeSwitchForGoInstallVersion(moduleLoaderState, minVers)
+ maybeSwitchForGoInstallVersion(moduleLoader, minVers)
}
// If we are invoked as a target toolchain, confirm that
@@ -285,7 +285,7 @@ func Select() {
}
counterSelectExec.Inc()
- Exec(moduleLoaderState, gotoolchain)
+ Exec(moduleLoader, gotoolchain)
panic("unreachable")
}
@@ -303,7 +303,7 @@ var TestVersionSwitch string
// If $GOTOOLCHAIN is set to path or min+path, Exec only considers the PATH
// as a source of Go toolchains. Otherwise Exec tries the PATH but then downloads
// a toolchain if necessary.
-func Exec(s *modload.State, gotoolchain string) {
+func Exec(s *modload.Loader, gotoolchain string) {
log.SetPrefix("go: ")
writeBits = sysWriteBits()
@@ -524,9 +524,9 @@ func raceSafeCopy(old, new string) error {
// modGoToolchain finds the enclosing go.work or go.mod file
// and returns the go version and toolchain lines from the file.
// The toolchain line overrides the version line
-func modGoToolchain(loaderstate *modload.State) (file, goVers, toolchain string) {
+func modGoToolchain(ld *modload.Loader) (file, goVers, toolchain string) {
wd := base.UncachedCwd()
- file = loaderstate.FindGoWork(wd)
+ file = ld.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 {
@@ -548,7 +548,7 @@ func modGoToolchain(loaderstate *modload.State) (file, goVers, toolchain string)
// maybeSwitchForGoInstallVersion reports whether the command line is go install m@v or go run m@v.
// If so, switch to the go version required to build m@v if it's higher than minVers.
-func maybeSwitchForGoInstallVersion(loaderstate *modload.State, minVers string) {
+func maybeSwitchForGoInstallVersion(ld *modload.Loader, minVers string) {
// Note: We assume there are no flags between 'go' and 'install' or 'run'.
// During testing there are some debugging flags that are accepted
// in that position, but in production go binaries there are not.
@@ -695,27 +695,27 @@ func maybeSwitchForGoInstallVersion(loaderstate *modload.State, minVers string)
// command lines if we add new flags in the future.
// Set up modules without an explicit go.mod, to download go.mod.
- loaderstate.ForceUseModules = true
- loaderstate.RootMode = modload.NoRoot
- modload.Init(loaderstate)
- defer loaderstate.Reset()
+ ld.ForceUseModules = true
+ ld.RootMode = modload.NoRoot
+ modload.Init(ld)
+ defer ld.Reset()
// See internal/load.PackagesAndErrorsOutsideModule
ctx := context.Background()
- allowed := loaderstate.CheckAllowed
+ allowed := ld.CheckAllowed
if modload.IsRevisionQuery(path, version) {
// Don't check for retractions if a specific revision is requested.
allowed = nil
}
noneSelected := func(path string) (version string) { return "none" }
- _, err = modload.QueryPackages(loaderstate, ctx, path, version, noneSelected, allowed)
+ _, err = modload.QueryPackages(ld, ctx, path, version, noneSelected, allowed)
if errors.Is(err, gover.ErrTooNew) {
// Run early switch, same one go install or go run would eventually do,
// if it understood all the command-line flags.
- s := NewSwitcher(loaderstate)
+ s := NewSwitcher(ld)
s.Error(err)
if s.TooNew != nil && gover.Compare(s.TooNew.GoVersion, minVers) > 0 {
- SwitchOrFatal(loaderstate, ctx, err)
+ SwitchOrFatal(ld, ctx, err)
}
}
}
diff --git a/src/cmd/go/internal/toolchain/switch.go b/src/cmd/go/internal/toolchain/switch.go
index ff4fce0307..b6a8910ff7 100644
--- a/src/cmd/go/internal/toolchain/switch.go
+++ b/src/cmd/go/internal/toolchain/switch.go
@@ -32,14 +32,14 @@ import (
//
// See https://go.dev/doc/toolchain#switch.
type Switcher struct {
- TooNew *gover.TooNewError // max go requirement observed
- Errors []error // errors collected so far
- loaderstate *modload.State // temporarily here while we eliminate global module loader state
+ TooNew *gover.TooNewError // max go requirement observed
+ Errors []error // errors collected so far
+ ld *modload.Loader // temporarily here while we eliminate global module loader state
}
-func NewSwitcher(s *modload.State) *Switcher {
+func NewSwitcher(s *modload.Loader) *Switcher {
sw := new(Switcher)
- sw.loaderstate = s
+ sw.ld = s
return sw
}
@@ -97,7 +97,7 @@ func (s *Switcher) Switch(ctx context.Context) {
}
// Switch to newer Go toolchain if necessary and possible.
- tv, err := NewerToolchain(ctx, s.loaderstate.Fetcher(), s.TooNew.GoVersion)
+ tv, err := NewerToolchain(ctx, s.ld.Fetcher(), s.TooNew.GoVersion)
if err != nil {
for _, err := range s.Errors {
base.Error(err)
@@ -108,7 +108,7 @@ func (s *Switcher) Switch(ctx context.Context) {
fmt.Fprintf(os.Stderr, "go: %v requires go >= %v; switching to %v\n", s.TooNew.What, s.TooNew.GoVersion, tv)
counterSwitchExec.Inc()
- Exec(s.loaderstate, tv)
+ Exec(s.ld, tv)
panic("unreachable")
}
@@ -116,8 +116,8 @@ var counterSwitchExec = counter.New("go/toolchain/switch-exec")
// SwitchOrFatal attempts a toolchain switch based on the information in err
// and otherwise falls back to base.Fatal(err).
-func SwitchOrFatal(loaderstate *modload.State, ctx context.Context, err error) {
- s := NewSwitcher(loaderstate)
+func SwitchOrFatal(ld *modload.Loader, ctx context.Context, err error) {
+ s := NewSwitcher(ld)
s.Error(err)
s.Switch(ctx)
base.Exit()
diff --git a/src/cmd/go/internal/vet/vet.go b/src/cmd/go/internal/vet/vet.go
index 61e3f59426..3f45050159 100644
--- a/src/cmd/go/internal/vet/vet.go
+++ b/src/cmd/go/internal/vet/vet.go
@@ -124,13 +124,13 @@ var (
// run implements both "go vet" and "go fix".
func run(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
// Compute flags for the vet/fix tool (e.g. cmd/{vet,fix}).
toolFlags, pkgArgs := toolFlags(cmd, args)
// The vet/fix commands do custom flag processing;
// initialize workspaces after that.
- moduleLoaderState.InitWorkfile()
+ moduleLoader.InitWorkfile()
if cfg.DebugTrace != "" {
var close func() error
@@ -149,7 +149,7 @@ func run(ctx context.Context, cmd *base.Command, args []string) {
ctx, span := trace.StartSpan(ctx, fmt.Sprint("Running ", cmd.Name(), " command"))
defer span.Done()
- work.BuildInit(moduleLoaderState)
+ work.BuildInit(moduleLoader)
// Flag theory:
//
@@ -231,14 +231,14 @@ func run(ctx context.Context, cmd *base.Command, args []string) {
work.VetFlags = toolFlags
pkgOpts := load.PackageOpts{ModResolveTests: true}
- pkgs := load.PackagesAndErrors(moduleLoaderState, ctx, pkgOpts, pkgArgs)
+ pkgs := load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, pkgArgs)
load.CheckPackageErrors(pkgs)
if len(pkgs) == 0 {
base.Fatalf("no packages to %s", cmd.Name())
}
// Build action graph.
- b := work.NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
+ b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -248,7 +248,7 @@ func run(ctx context.Context, cmd *base.Command, args []string) {
root := &work.Action{Mode: "go " + cmd.Name()}
addVetAction := func(p *load.Package) {
- act := b.VetAction(moduleLoaderState, work.ModeBuild, work.ModeBuild, applyFixes, p)
+ act := b.VetAction(moduleLoader, work.ModeBuild, work.ModeBuild, applyFixes, p)
root.Deps = append(root.Deps, act)
}
@@ -277,7 +277,7 @@ func run(ctx context.Context, cmd *base.Command, args []string) {
continue
}
}
- _, ptest, pxtest, perr := load.TestPackagesFor(moduleLoaderState, ctx, pkgOpts, p, nil)
+ _, ptest, pxtest, perr := load.TestPackagesFor(moduleLoader, ctx, pkgOpts, p, nil)
if perr != nil {
base.Errorf("%v", perr.Error)
continue
diff --git a/src/cmd/go/internal/work/action.go b/src/cmd/go/internal/work/action.go
index f0e34c3368..8b3897e215 100644
--- a/src/cmd/go/internal/work/action.go
+++ b/src/cmd/go/internal/work/action.go
@@ -397,7 +397,7 @@ func (b *Builder) NewObjdir() string {
// at shlibpath. For the native toolchain this list is stored, newline separated, in
// an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the
// .go_export section.
-func readpkglist(s *modload.State, shlibpath string) (pkgs []*load.Package) {
+func readpkglist(s *modload.Loader, shlibpath string) (pkgs []*load.Package) {
var stk load.ImportStack
if cfg.BuildToolchainName == "gccgo" {
f, err := elf.Open(shlibpath)
@@ -448,7 +448,7 @@ func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *A
}
// AutoAction returns the "right" action for go build or go install of p.
-func (b *Builder) AutoAction(s *modload.State, mode, depMode BuildMode, p *load.Package) *Action {
+func (b *Builder) AutoAction(s *modload.Loader, mode, depMode BuildMode, p *load.Package) *Action {
if p.Name == "main" {
return b.LinkAction(s, mode, depMode, p)
}
@@ -871,14 +871,14 @@ func (b *Builder) cgoAction(p *load.Package, objdir string, deps []*Action, hasC
// It depends on the action for compiling p.
// If the caller may be causing p to be installed, it is up to the caller
// to make sure that the install depends on (runs after) vet.
-func (b *Builder) VetAction(s *modload.State, mode, depMode BuildMode, needFix bool, p *load.Package) *Action {
+func (b *Builder) VetAction(s *modload.Loader, mode, depMode BuildMode, needFix bool, p *load.Package) *Action {
a := b.vetAction(s, mode, depMode, p)
a.VetxOnly = false
a.needFix = needFix
return a
}
-func (b *Builder) vetAction(s *modload.State, mode, depMode BuildMode, p *load.Package) *Action {
+func (b *Builder) vetAction(s *modload.Loader, mode, depMode BuildMode, p *load.Package) *Action {
// Construct vet action.
a := b.cacheAction("vet", p, func() *Action {
a1 := b.CompileAction(mode|ModeVetOnly, depMode, p)
@@ -919,7 +919,7 @@ func (b *Builder) vetAction(s *modload.State, mode, depMode BuildMode, p *load.P
// LinkAction returns the action for linking p into an executable
// and possibly installing the result (according to mode).
// depMode is the action (build or install) to use when compiling dependencies.
-func (b *Builder) LinkAction(s *modload.State, mode, depMode BuildMode, p *load.Package) *Action {
+func (b *Builder) LinkAction(s *modload.Loader, mode, depMode BuildMode, p *load.Package) *Action {
// Construct link action.
a := b.cacheAction("link", p, func() *Action {
a := &Action{
@@ -1040,7 +1040,7 @@ func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action {
// makes sure those are present in a.Deps.
// If shlib is non-empty, then a corresponds to the build and installation of shlib,
// so any rebuild of shlib should not be added as a dependency.
-func (b *Builder) addTransitiveLinkDeps(s *modload.State, a, a1 *Action, shlib string) {
+func (b *Builder) addTransitiveLinkDeps(s *modload.Loader, a, a1 *Action, shlib string) {
// Expand Deps to include all built packages, for the linker.
// Use breadth-first search to find rebuilt-for-test packages
// before the standard ones.
@@ -1117,7 +1117,7 @@ func (b *Builder) addInstallHeaderAction(a *Action) {
// buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps.
// That is, the input a1 represents "go build pkgs" and the result represents "go build -buildmode=shared pkgs".
-func (b *Builder) buildmodeShared(s *modload.State, mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action {
+func (b *Builder) buildmodeShared(s *modload.Loader, mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action {
name, err := libname(args, pkgs)
if err != nil {
base.Fatalf("%v", err)
@@ -1129,7 +1129,7 @@ func (b *Builder) buildmodeShared(s *modload.State, mode, depMode BuildMode, arg
// and returns an action that links them together into a shared library with the name shlib.
// If a1 is nil, shlib should be an absolute path to an existing shared library,
// and then linkSharedAction reads that library to find out the package list.
-func (b *Builder) linkSharedAction(s *modload.State, mode, depMode BuildMode, shlib string, a1 *Action) *Action {
+func (b *Builder) linkSharedAction(s *modload.Loader, mode, depMode BuildMode, shlib string, a1 *Action) *Action {
fullShlib := shlib
shlib = filepath.Base(shlib)
a := b.cacheAction("build-shlib "+shlib, nil, func() *Action {
diff --git a/src/cmd/go/internal/work/build.go b/src/cmd/go/internal/work/build.go
index 88ce9c6d21..969e0029c3 100644
--- a/src/cmd/go/internal/work/build.go
+++ b/src/cmd/go/internal/work/build.go
@@ -459,17 +459,17 @@ func oneMainPkg(pkgs []*load.Package) []*load.Package {
var pkgsFilter = func(pkgs []*load.Package) []*load.Package { return pkgs }
func runBuild(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
- BuildInit(moduleLoaderState)
- b := NewBuilder("", moduleLoaderState.VendorDirOrEmpty)
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
+ BuildInit(moduleLoader)
+ b := NewBuilder("", moduleLoader.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
}
}()
- pkgs := load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{AutoVCS: true}, args)
+ pkgs := load.PackagesAndErrors(moduleLoader, ctx, load.PackageOpts{AutoVCS: true}, args)
load.CheckPackageErrors(pkgs)
explicitO := len(cfg.BuildO) > 0
@@ -504,7 +504,7 @@ func runBuild(ctx context.Context, cmd *base.Command, args []string) {
}
if cfg.BuildCover {
- load.PrepareForCoverageBuild(moduleLoaderState, pkgs)
+ load.PrepareForCoverageBuild(moduleLoader, pkgs)
}
if cfg.BuildO != "" {
@@ -528,7 +528,7 @@ func runBuild(ctx context.Context, cmd *base.Command, args []string) {
p.Target += cfg.ExeSuffix
p.Stale = true
p.StaleReason = "build -o flag in use"
- a.Deps = append(a.Deps, b.AutoAction(moduleLoaderState, ModeInstall, depMode, p))
+ a.Deps = append(a.Deps, b.AutoAction(moduleLoader, ModeInstall, depMode, p))
}
if len(a.Deps) == 0 {
base.Fatalf("go: no main packages to build")
@@ -545,17 +545,17 @@ func runBuild(ctx context.Context, cmd *base.Command, args []string) {
p.Target = cfg.BuildO
p.Stale = true // must build - not up to date
p.StaleReason = "build -o flag in use"
- a := b.AutoAction(moduleLoaderState, ModeInstall, depMode, p)
+ a := b.AutoAction(moduleLoader, ModeInstall, depMode, p)
b.Do(ctx, a)
return
}
a := &Action{Mode: "go build"}
for _, p := range pkgs {
- a.Deps = append(a.Deps, b.AutoAction(moduleLoaderState, ModeBuild, depMode, p))
+ a.Deps = append(a.Deps, b.AutoAction(moduleLoader, ModeBuild, depMode, p))
}
if cfg.BuildBuildmode == "shared" {
- a = b.buildmodeShared(moduleLoaderState, ModeBuild, depMode, args, pkgs, a)
+ a = b.buildmodeShared(moduleLoader, ModeBuild, depMode, args, pkgs, a)
}
b.Do(ctx, a)
}
@@ -688,18 +688,18 @@ func libname(args []string, pkgs []*load.Package) (string, error) {
}
func runInstall(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
for _, arg := range args {
if strings.Contains(arg, "@") && !build.IsLocalImport(arg) && !filepath.IsAbs(arg) {
- installOutsideModule(moduleLoaderState, ctx, args)
+ installOutsideModule(moduleLoader, ctx, args)
return
}
}
- moduleLoaderState.InitWorkfile()
- BuildInit(moduleLoaderState)
- pkgs := load.PackagesAndErrors(moduleLoaderState, ctx, load.PackageOpts{AutoVCS: true}, args)
- if cfg.ModulesEnabled && !moduleLoaderState.HasModRoot() {
+ moduleLoader.InitWorkfile()
+ BuildInit(moduleLoader)
+ pkgs := load.PackagesAndErrors(moduleLoader, ctx, load.PackageOpts{AutoVCS: true}, args)
+ if cfg.ModulesEnabled && !moduleLoader.HasModRoot() {
haveErrors := false
allMissingErrors := true
for _, pkg := range pkgs {
@@ -724,10 +724,10 @@ func runInstall(ctx context.Context, cmd *base.Command, args []string) {
load.CheckPackageErrors(pkgs)
if cfg.BuildCover {
- load.PrepareForCoverageBuild(moduleLoaderState, pkgs)
+ load.PrepareForCoverageBuild(moduleLoader, pkgs)
}
- InstallPackages(moduleLoaderState, ctx, args, pkgs)
+ InstallPackages(moduleLoader, ctx, args, pkgs)
}
// omitTestOnly returns pkgs with test-only packages removed.
@@ -747,7 +747,7 @@ func omitTestOnly(pkgs []*load.Package) []*load.Package {
return list
}
-func InstallPackages(loaderstate *modload.State, ctx context.Context, patterns []string, pkgs []*load.Package) {
+func InstallPackages(ld *modload.Loader, ctx context.Context, patterns []string, pkgs []*load.Package) {
ctx, span := trace.StartSpan(ctx, "InstallPackages "+strings.Join(patterns, " "))
defer span.Done()
@@ -785,7 +785,7 @@ func InstallPackages(loaderstate *modload.State, ctx context.Context, patterns [
}
base.ExitIfErrors()
- b := NewBuilder("", loaderstate.VendorDirOrEmpty)
+ b := NewBuilder("", ld.VendorDirOrEmpty)
defer func() {
if err := b.Close(); err != nil {
base.Fatal(err)
@@ -799,7 +799,7 @@ func InstallPackages(loaderstate *modload.State, ctx context.Context, patterns [
// If p is a tool, delay the installation until the end of the build.
// This avoids installing assemblers/compilers that are being executed
// by other steps in the build.
- a1 := b.AutoAction(loaderstate, ModeInstall, depMode, p)
+ a1 := b.AutoAction(ld, ModeInstall, depMode, p)
if load.InstallTargetDir(p) == load.ToTool {
a.Deps = append(a.Deps, a1.Deps...)
a1.Deps = append(a1.Deps, a)
@@ -821,7 +821,7 @@ func InstallPackages(loaderstate *modload.State, ctx context.Context, patterns [
// tools above did not apply, and a is just a simple Action
// with a list of Deps, one per package named in pkgs,
// the same as in runBuild.
- a = b.buildmodeShared(loaderstate, ModeInstall, ModeInstall, patterns, pkgs, a)
+ a = b.buildmodeShared(ld, ModeInstall, ModeInstall, patterns, pkgs, a)
}
b.Do(ctx, a)
@@ -860,12 +860,12 @@ func InstallPackages(loaderstate *modload.State, ctx context.Context, patterns [
// in the current directory or parent directories.
//
// See golang.org/issue/40276 for details and rationale.
-func installOutsideModule(loaderstate *modload.State, ctx context.Context, args []string) {
- loaderstate.ForceUseModules = true
- loaderstate.RootMode = modload.NoRoot
- loaderstate.AllowMissingModuleImports()
- modload.Init(loaderstate)
- BuildInit(loaderstate)
+func installOutsideModule(ld *modload.Loader, ctx context.Context, args []string) {
+ ld.ForceUseModules = true
+ ld.RootMode = modload.NoRoot
+ ld.AllowMissingModuleImports()
+ modload.Init(ld)
+ BuildInit(ld)
// Load packages. Ignore non-main packages.
// Print a warning if an argument contains "..." and matches no main packages.
@@ -874,7 +874,7 @@ func installOutsideModule(loaderstate *modload.State, ctx context.Context, args
// TODO(golang.org/issue/40276): don't report errors loading non-main packages
// matched by a pattern.
pkgOpts := load.PackageOpts{MainOnly: true}
- pkgs, err := load.PackagesAndErrorsOutsideModule(loaderstate, ctx, pkgOpts, args)
+ pkgs, err := load.PackagesAndErrorsOutsideModule(ld, ctx, pkgOpts, args)
if err != nil {
base.Fatal(err)
}
@@ -885,7 +885,7 @@ func installOutsideModule(loaderstate *modload.State, ctx context.Context, args
}
// Build and install the packages.
- InstallPackages(loaderstate, ctx, patterns, pkgs)
+ InstallPackages(ld, ctx, patterns, pkgs)
}
// ExecCmd is the command to use to run user binaries.
diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go
index c61779bb3c..4217aee1bf 100644
--- a/src/cmd/go/internal/work/exec.go
+++ b/src/cmd/go/internal/work/exec.go
@@ -3444,7 +3444,7 @@ func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
}
srcs := []string{src}
- p := load.GoFilesPackage(modload.NewState(), context.TODO(), load.PackageOpts{}, srcs)
+ p := load.GoFilesPackage(modload.NewLoader(), context.TODO(), load.PackageOpts{}, srcs)
if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, "", srcs); e != nil {
return "32", nil
diff --git a/src/cmd/go/internal/work/init.go b/src/cmd/go/internal/work/init.go
index 964d6e8363..9226dd3fd6 100644
--- a/src/cmd/go/internal/work/init.go
+++ b/src/cmd/go/internal/work/init.go
@@ -50,14 +50,14 @@ func makeCfgChangedEnv() []string {
return slices.Clip(env)
}
-func BuildInit(loaderstate *modload.State) {
+func BuildInit(ld *modload.Loader) {
if buildInitStarted {
base.Fatalf("go: internal error: work.BuildInit called more than once")
}
buildInitStarted = true
base.AtExit(closeBuilders)
- modload.Init(loaderstate)
+ modload.Init(ld)
instrumentInit()
buildModeInit()
initCompilerConcurrencyPool()
diff --git a/src/cmd/go/internal/workcmd/edit.go b/src/cmd/go/internal/workcmd/edit.go
index 2ccd1adf51..bb47ad39b6 100644
--- a/src/cmd/go/internal/workcmd/edit.go
+++ b/src/cmd/go/internal/workcmd/edit.go
@@ -132,7 +132,7 @@ func init() {
}
func runEditwork(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
+ moduleLoader := modload.NewLoader()
if *editJSON && *editPrint {
base.Fatalf("go: cannot use both -json and -print")
}
@@ -144,8 +144,8 @@ func runEditwork(ctx context.Context, cmd *base.Command, args []string) {
if len(args) == 1 {
gowork = args[0]
} else {
- moduleLoaderState.InitWorkfile()
- gowork = modload.WorkFilePath(moduleLoaderState)
+ moduleLoader.InitWorkfile()
+ gowork = modload.WorkFilePath(moduleLoader)
}
if gowork == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
diff --git a/src/cmd/go/internal/workcmd/init.go b/src/cmd/go/internal/workcmd/init.go
index 896740f080..c264c3b4be 100644
--- a/src/cmd/go/internal/workcmd/init.go
+++ b/src/cmd/go/internal/workcmd/init.go
@@ -44,12 +44,12 @@ func init() {
}
func runInit(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
- moduleLoaderState.ForceUseModules = true
+ moduleLoader.ForceUseModules = true
- gowork := modload.WorkFilePath(moduleLoaderState)
+ gowork := modload.WorkFilePath(moduleLoader)
if gowork == "" {
gowork = filepath.Join(base.Cwd(), "go.work")
}
@@ -62,6 +62,6 @@ func runInit(ctx context.Context, cmd *base.Command, args []string) {
wf := new(modfile.WorkFile)
wf.Syntax = new(modfile.FileSyntax)
wf.AddGoStmt(goV)
- workUse(ctx, moduleLoaderState, gowork, wf, args)
+ workUse(ctx, moduleLoader, gowork, wf, args)
modload.WriteWorkFile(gowork, wf)
}
diff --git a/src/cmd/go/internal/workcmd/sync.go b/src/cmd/go/internal/workcmd/sync.go
index 8c90c75bdb..a05e6cf2aa 100644
--- a/src/cmd/go/internal/workcmd/sync.go
+++ b/src/cmd/go/internal/workcmd/sync.go
@@ -48,20 +48,20 @@ func init() {
}
func runSync(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.InitWorkfile()
- if modload.WorkFilePath(moduleLoaderState) == "" {
+ moduleLoader := modload.NewLoader()
+ moduleLoader.ForceUseModules = true
+ moduleLoader.InitWorkfile()
+ if modload.WorkFilePath(moduleLoader) == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
}
- _, err := modload.LoadModGraph(moduleLoaderState, ctx, "")
+ _, err := modload.LoadModGraph(moduleLoader, ctx, "")
if err != nil {
- toolchain.SwitchOrFatal(moduleLoaderState, ctx, err)
+ toolchain.SwitchOrFatal(moduleLoader, ctx, err)
}
mustSelectFor := map[module.Version][]module.Version{}
- mms := moduleLoaderState.MainModules
+ mms := moduleLoader.MainModules
opts := modload.PackageOpts{
Tags: imports.AnyTags(),
@@ -74,7 +74,7 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
}
for _, m := range mms.Versions() {
opts.MainModule = m
- _, pkgs := modload.LoadPackages(moduleLoaderState, ctx, opts, "all")
+ _, pkgs := modload.LoadPackages(moduleLoader, ctx, opts, "all")
opts.MainModule = module.Version{} // reset
var (
@@ -82,7 +82,7 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
inMustSelect = map[module.Version]bool{}
)
for _, pkg := range pkgs {
- if r := moduleLoaderState.PackageModule(pkg); r.Version != "" && !inMustSelect[r] {
+ if r := moduleLoader.PackageModule(pkg); r.Version != "" && !inMustSelect[r] {
// r has a known version, so force that version.
mustSelect = append(mustSelect, r)
inMustSelect[r] = true
@@ -92,7 +92,7 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
mustSelectFor[m] = mustSelect
}
- workFilePath := modload.WorkFilePath(moduleLoaderState) // save go.work path because EnterModule clobbers it.
+ workFilePath := modload.WorkFilePath(moduleLoader) // save go.work path because EnterModule clobbers it.
var goV string
for _, m := range mms.Versions() {
@@ -105,7 +105,7 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
// Use EnterModule to reset the global state in modload to be in
// single-module mode using the modroot of m.
- modload.EnterModule(moduleLoaderState, ctx, mms.ModRoot(m))
+ modload.EnterModule(moduleLoader, ctx, mms.ModRoot(m))
// Edit the build list in the same way that 'go get' would if we
// requested the relevant module versions explicitly.
@@ -115,12 +115,12 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
// so we don't write some go.mods with the "before" toolchain
// and others with the "after" toolchain. If nothing else, that
// discrepancy could show up in auto-recorded toolchain lines.
- changed, err := modload.EditBuildList(moduleLoaderState, ctx, nil, mustSelectFor[m])
+ changed, err := modload.EditBuildList(moduleLoader, ctx, nil, mustSelectFor[m])
if err != nil {
continue
}
if changed {
- modload.LoadPackages(moduleLoaderState, ctx, modload.PackageOpts{
+ modload.LoadPackages(moduleLoader, ctx, modload.PackageOpts{
Tags: imports.AnyTags(),
Tidy: true,
VendorModulesInGOROOTSrc: true,
@@ -130,9 +130,9 @@ func runSync(ctx context.Context, cmd *base.Command, args []string) {
SilenceMissingStdImports: true,
SilencePackageErrors: true,
}, "all")
- modload.WriteGoMod(moduleLoaderState, ctx, modload.WriteOpts{})
+ modload.WriteGoMod(moduleLoader, ctx, modload.WriteOpts{})
}
- goV = gover.Max(goV, moduleLoaderState.MainModules.GoVersion(moduleLoaderState))
+ goV = gover.Max(goV, moduleLoader.MainModules.GoVersion(moduleLoader))
}
wf, err := modload.ReadWorkFile(workFilePath)
diff --git a/src/cmd/go/internal/workcmd/use.go b/src/cmd/go/internal/workcmd/use.go
index f019b5b68e..1d833b37ec 100644
--- a/src/cmd/go/internal/workcmd/use.go
+++ b/src/cmd/go/internal/workcmd/use.go
@@ -64,10 +64,10 @@ func init() {
}
func runUse(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.ForceUseModules = true
- moduleLoaderState.InitWorkfile()
- gowork := modload.WorkFilePath(moduleLoaderState)
+ moduleLoader := modload.NewLoader()
+ moduleLoader.ForceUseModules = true
+ moduleLoader.InitWorkfile()
+ gowork := modload.WorkFilePath(moduleLoader)
if gowork == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
}
@@ -75,11 +75,11 @@ func runUse(ctx context.Context, cmd *base.Command, args []string) {
if err != nil {
base.Fatal(err)
}
- workUse(ctx, moduleLoaderState, gowork, wf, args)
+ workUse(ctx, moduleLoader, gowork, wf, args)
modload.WriteWorkFile(gowork, wf)
}
-func workUse(ctx context.Context, s *modload.State, gowork string, wf *modfile.WorkFile, args []string) {
+func workUse(ctx context.Context, s *modload.Loader, gowork string, wf *modfile.WorkFile, args []string) {
workDir := filepath.Dir(gowork) // absolute, since gowork itself is absolute
haveDirs := make(map[string][]string) // absolute → original(s)
diff --git a/src/cmd/go/internal/workcmd/vendor.go b/src/cmd/go/internal/workcmd/vendor.go
index 26715c8d3b..fdc7ea312b 100644
--- a/src/cmd/go/internal/workcmd/vendor.go
+++ b/src/cmd/go/internal/workcmd/vendor.go
@@ -46,11 +46,11 @@ func init() {
}
func runVendor(ctx context.Context, cmd *base.Command, args []string) {
- moduleLoaderState := modload.NewState()
- moduleLoaderState.InitWorkfile()
- if modload.WorkFilePath(moduleLoaderState) == "" {
+ moduleLoader := modload.NewLoader()
+ moduleLoader.InitWorkfile()
+ if modload.WorkFilePath(moduleLoader) == "" {
base.Fatalf("go: no go.work file found\n\t(run 'go work init' first or specify path using GOWORK environment variable)")
}
- modcmd.RunVendor(moduleLoaderState, ctx, vendorE, vendorO, args)
+ modcmd.RunVendor(moduleLoader, ctx, vendorE, vendorO, args)
}