Update go version

This commit is contained in:
dwrz
2026-08-21 10:23:37 +00:00
parent 78248a6145
commit c2e2d9ea02
466 changed files with 67766 additions and 2881 deletions

View File

@@ -32,6 +32,7 @@ import (
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/gocommand"
"golang.org/x/tools/internal/gopathwalk"
"golang.org/x/tools/internal/modindex"
"golang.org/x/tools/internal/stdlib"
)
@@ -273,7 +274,6 @@ func (p *pass) loadPackageNames(ctx context.Context, imports []*ImportInfo) erro
}
unknown = append(unknown, imp.ImportPath)
}
names, err := p.source.LoadPackageNames(ctx, p.srcDir, unknown)
if err != nil {
return err
@@ -321,6 +321,7 @@ func (p *pass) importIdentifier(imp *ImportInfo) string {
// load reads in everything necessary to run a pass, and reports whether the
// file already has all the imports it needs. It fills in p.missingRefs with the
// file's missing symbols, if any, or removes unused imports if not.
// This is called 3(!) times: self, otherFiles, loadRealPackageNames
func (p *pass) load(ctx context.Context) ([]*ImportFix, bool) {
p.knownPackages = map[string]*PackageInfo{}
p.missingRefs = References{}
@@ -578,6 +579,17 @@ func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename st
}
func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, goroot string, logf func(string, ...any), source Source) ([]*ImportFix, error) {
// If there is an Index for the GOMODCACHE, remember that, and later make it so that the
// directory walk doesn't go into the module cache, since we already have all the information
var ix *modindex.Index
src, ok := source.(*ProcessEnvSource)
if ok {
var err error
if ix, err = modindex.Read(src.env.Env["GOMODCACHE"]); err != nil {
ix = nil // don't use it if there was an error
}
}
// This logic is defensively duplicated from getFixes.
abs, err := filepath.Abs(filename)
if err != nil {
@@ -636,6 +648,20 @@ func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, f
}
p.loadRealPackageNames = true
p.otherFiles = otherFiles
if ix != nil {
src, ok := p.source.(*ProcessEnvSource)
if ok {
// For safety, clone the env so that we don't modify the caller's env.
env := *src.env
env.Env = maps.Clone(src.env.Env)
src.env = &env
// avoid looking in the module cache, as we have the index instead:
// This makes a later call to newModuleresolver (from
// LoadPackageNames) produce a resolver that will not look
// in the module cache
src.env.Env["GOMODCACHE"] = ""
}
}
if fixes, done := p.load(ctx); done {
return fixes, nil
}
@@ -650,7 +676,7 @@ func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, f
// Go look for candidates in $GOPATH, etc. We don't necessarily load
// the real exports of sibling imports, so keep assuming their contents.
if err := addExternalCandidates(ctx, p, p.missingRefs, filename); err != nil {
if err := addExternalCandidates(ctx, p, p.missingRefs, filename, ix); err != nil {
return nil, err
}
@@ -1185,7 +1211,7 @@ type scanCallback struct {
exportsLoaded func(pkg *pkg, exports []stdlib.Symbol)
}
func addExternalCandidates(ctx context.Context, pass *pass, refs References, filename string) error {
func addExternalCandidates(ctx context.Context, pass *pass, refs References, filename string, ix *modindex.Index) error {
ctx, done := event.Start(ctx, "imports.addExternalCandidates")
defer done()
@@ -1194,6 +1220,24 @@ func addExternalCandidates(ctx context.Context, pass *pass, refs References, fil
return err
}
// Add candidates from the module cache.
if ix != nil {
for k, v := range refs {
for n := range v {
cands := ix.Lookup(k, n, false)
for _, cand := range cands {
x := &Result{
&ImportInfo{ImportPath: cand.ImportPath},
&PackageInfo{Name: cand.PkgName,
Exports: map[string]bool{cand.Name: true},
},
}
results = append(results, x)
}
}
}
}
for _, result := range results {
if result == nil {
continue
@@ -1650,9 +1694,7 @@ func (s *symbolSearcher) search(ctx context.Context, candidates []pkgDistance, p
}()
// Start the search.
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for i, c := range candidates {
select {
case loadExportsSem <- struct{}{}:
@@ -1681,7 +1723,7 @@ func (s *symbolSearcher) search(ctx context.Context, candidates []pkgDistance, p
rescv[i] <- pkg // may be nil
}()
}
}()
})
// Await the first (best) result.
for _, resc := range rescv {

View File

@@ -74,6 +74,10 @@ func Process(filename string, src []byte, opt *Options) (formatted []byte, err e
// Note that filename's directory influences which imports can be chosen,
// so it is important that filename be accurate.
func FixImports(ctx context.Context, filename string, src []byte, goroot string, logf func(string, ...any), source Source) (fixes []*ImportFix, err error) {
if source == nil {
// In case someone adds a defective call from a new place
panic("source is nil")
}
ctx, done := event.Start(ctx, "imports.FixImports")
defer done()

View File

@@ -166,10 +166,7 @@ func newModuleResolver(e *ProcessEnv, moduleCacheCache *DirInfoCache) (*ModuleRe
}
}
r.moduleCacheDir = gomodcacheForEnv(goenv)
if r.moduleCacheDir == "" {
return nil, fmt.Errorf("cannot resolve GOMODCACHE")
}
r.moduleCacheDir = goenv["GOMODCACHE"]
sort.Slice(r.modsByModPath, func(i, j int) bool {
count := func(x int) int {
@@ -238,26 +235,6 @@ func newModuleResolver(e *ProcessEnv, moduleCacheCache *DirInfoCache) (*ModuleRe
return r, nil
}
// gomodcacheForEnv returns the GOMODCACHE value to use based on the given env
// map, which must have GOMODCACHE and GOPATH populated.
//
// TODO(rfindley): this is defensive refactoring.
// 1. Is this even relevant anymore? Can't we just read GOMODCACHE.
// 2. Use this to separate module cache scanning from other scanning.
func gomodcacheForEnv(goenv map[string]string) string {
if gmc := goenv["GOMODCACHE"]; gmc != "" {
// golang/go#67156: ensure that the module cache is clean, since it is
// assumed as a prefix to directories scanned by gopathwalk, which are
// themselves clean.
return filepath.Clean(gmc)
}
gopaths := filepath.SplitList(goenv["GOPATH"])
if len(gopaths) == 0 {
return ""
}
return filepath.Join(gopaths[0], "/pkg/mod")
}
func (r *ModuleResolver) initAllMods() error {
stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-e", "-json", "...")
if err != nil {
@@ -679,11 +656,11 @@ func modRelevance(mod *gocommand.ModuleJSON) float64 {
_, versionString, ok := module.SplitPathVersion(mod.Path)
if ok {
index := strings.Index(versionString, "v")
if index == -1 {
_, after, ok := strings.Cut(versionString, "v")
if !ok {
return relevance
}
if versionNumber, err := strconv.ParseFloat(versionString[index+1:], 64); err == nil {
if versionNumber, err := strconv.ParseFloat(after, 64); err == nil {
relevance += versionNumber / 1000
}
}

View File

@@ -53,7 +53,7 @@ func (s *ProcessEnvSource) ResolveReferences(ctx context.Context, filename strin
found := make(map[string][]pkgDistance)
callback := &scanCallback{
rootFound: func(gopathwalk.Root) bool {
return true // We want everything.
return true
},
dirFound: func(pkg *pkg) bool {
return pkgIsCandidate(filename, refs, pkg)

View File

@@ -1,100 +0,0 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imports
import (
"context"
"sync"
"time"
"golang.org/x/tools/internal/modindex"
)
// This code is here rather than in the modindex package
// to avoid import loops
// TODO(adonovan): this code is only used by a test in this package.
// Can we delete it? Or is there a plan to call NewIndexSource from
// cmd/goimports?
// implements Source using modindex, so only for module cache.
//
// this is perhaps over-engineered. A new Index is read at first use.
// And then Update is called after every 15 minutes, and a new Index
// is read if the index changed. It is not clear the Mutex is needed.
type IndexSource struct {
modcachedir string
mu sync.Mutex
index *modindex.Index // (access via getIndex)
expires time.Time
}
// create a new Source. Called from NewView in cache/session.go.
func NewIndexSource(cachedir string) *IndexSource {
return &IndexSource{modcachedir: cachedir}
}
func (s *IndexSource) LoadPackageNames(ctx context.Context, srcDir string, paths []ImportPath) (map[ImportPath]PackageName, error) {
/// This is used by goimports to resolve the package names of imports of the
// current package, which is irrelevant for the module cache.
return nil, nil
}
func (s *IndexSource) ResolveReferences(ctx context.Context, filename string, missing References) ([]*Result, error) {
index, err := s.getIndex()
if err != nil {
return nil, err
}
var cs []modindex.Candidate
for pkg, nms := range missing {
for nm := range nms {
x := index.Lookup(pkg, nm, false)
cs = append(cs, x...)
}
}
found := make(map[string]*Result)
for _, c := range cs {
var x *Result
if x = found[c.ImportPath]; x == nil {
x = &Result{
Import: &ImportInfo{
ImportPath: c.ImportPath,
Name: "",
},
Package: &PackageInfo{
Name: c.PkgName,
Exports: make(map[string]bool),
},
}
found[c.ImportPath] = x
}
x.Package.Exports[c.Name] = true
}
var ans []*Result
for _, x := range found {
ans = append(ans, x)
}
return ans, nil
}
func (s *IndexSource) getIndex() (*modindex.Index, error) {
s.mu.Lock()
defer s.mu.Unlock()
// (s.index = nil => s.expires is zero,
// so the first condition is strictly redundant.
// But it makes the postcondition very clear.)
if s.index == nil || time.Now().After(s.expires) {
index, err := modindex.Update(s.modcachedir)
if err != nil {
return nil, err
}
s.index = index
s.expires = index.ValidAt.Add(15 * time.Minute) // (refresh period)
}
// Inv: s.index != nil
return s.index, nil
}