\n" {
+ err = fmt.Errorf("not the start of an archive file (%q)", line)
+ return
+ }
- // First entry should be __.PKGDEF.
- if name != "__.PKGDEF" {
- err = fmt.Errorf("go archive is missing __.PKGDEF")
- return
- }
+ // Archive file. Scan to __.PKGDEF.
+ var name string
+ if name, size, err = readGopackHeader(r); err != nil {
+ return
+ }
+ arsize := size
- // Read first line of __.PKGDEF data, so that line
- // is once again the first line of the input.
- if line, err = r.ReadSlice('\n'); err != nil {
- err = fmt.Errorf("can't find export data (%v)", err)
- return
- }
- size -= int64(len(line))
+ // First entry should be __.PKGDEF.
+ if name != "__.PKGDEF" {
+ err = fmt.Errorf("go archive is missing __.PKGDEF")
+ return
+ }
+
+ // Read first line of __.PKGDEF data, so that line
+ // is once again the first line of the input.
+ if line, err = r.ReadSlice('\n'); err != nil {
+ err = fmt.Errorf("can't find export data (%v)", err)
+ return
}
+ size -= int64(len(line))
// Now at __.PKGDEF in archive or still at beginning of file.
// Either way, line should begin with "go object ".
@@ -81,8 +89,8 @@ func FindExportData(r *bufio.Reader) (hdr string, size int64, err error) {
return
}
- // Skip over object header to export data.
- // Begins after first line starting with $$.
+ // Skip over object headers to get to the export data section header "$$B\n".
+ // Object headers are lines that do not start with '$'.
for line[0] != '$' {
if line, err = r.ReadSlice('\n'); err != nil {
err = fmt.Errorf("can't find export data (%v)", err)
@@ -90,9 +98,18 @@ func FindExportData(r *bufio.Reader) (hdr string, size int64, err error) {
}
size -= int64(len(line))
}
- hdr = string(line)
+
+ // Check for the binary export data section header "$$B\n".
+ hdr := string(line)
+ if hdr != "$$B\n" {
+ err = fmt.Errorf("unknown export data header: %q", hdr)
+ return
+ }
+ // TODO(taking): Remove end-of-section marker "\n$$\n" from size.
+
if size < 0 {
- size = -1
+ err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", arsize, size)
+ return
}
return
diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go
index e6c5d51..dbbca86 100644
--- a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go
+++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go
@@ -161,6 +161,8 @@ func FindPkg(path, srcDir string) (filename, id string) {
// Import imports a gc-generated package given its import path and srcDir, adds
// the corresponding package object to the packages map, and returns the object.
// The packages map must contain all packages already imported.
+//
+// TODO(taking): Import is only used in tests. Move to gcimporter_test.
func Import(packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) {
var rc io.ReadCloser
var filename, id string
@@ -210,58 +212,50 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func
}
defer rc.Close()
- var hdr string
var size int64
buf := bufio.NewReader(rc)
- if hdr, size, err = FindExportData(buf); err != nil {
+ if size, err = FindExportData(buf); err != nil {
return
}
- switch hdr {
- case "$$B\n":
- var data []byte
- data, err = io.ReadAll(buf)
- if err != nil {
- break
- }
+ var data []byte
+ data, err = io.ReadAll(buf)
+ if err != nil {
+ return
+ }
+ if len(data) == 0 {
+ return nil, fmt.Errorf("no data to load a package from for path %s", id)
+ }
- // TODO(gri): allow clients of go/importer to provide a FileSet.
- // Or, define a new standard go/types/gcexportdata package.
- fset := token.NewFileSet()
-
- // Select appropriate importer.
- if len(data) > 0 {
- switch data[0] {
- case 'v', 'c', 'd':
- // binary: emitted by cmd/compile till go1.10; obsolete.
- return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0])
-
- case 'i':
- // indexed: emitted by cmd/compile till go1.19;
- // now used only for serializing go/types.
- // See https://github.com/golang/go/issues/69491.
- _, pkg, err := IImportData(fset, packages, data[1:], id)
- return pkg, err
-
- case 'u':
- // unified: emitted by cmd/compile since go1.20.
- _, pkg, err := UImportData(fset, packages, data[1:size], id)
- return pkg, err
-
- default:
- l := len(data)
- if l > 10 {
- l = 10
- }
- return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), id)
- }
- }
+ // TODO(gri): allow clients of go/importer to provide a FileSet.
+ // Or, define a new standard go/types/gcexportdata package.
+ fset := token.NewFileSet()
+
+ // Select appropriate importer.
+ switch data[0] {
+ case 'v', 'c', 'd':
+ // binary: emitted by cmd/compile till go1.10; obsolete.
+ return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0])
+
+ case 'i':
+ // indexed: emitted by cmd/compile till go1.19;
+ // now used only for serializing go/types.
+ // See https://github.com/golang/go/issues/69491.
+ _, pkg, err := IImportData(fset, packages, data[1:], id)
+ return pkg, err
+
+ case 'u':
+ // unified: emitted by cmd/compile since go1.20.
+ _, pkg, err := UImportData(fset, packages, data[1:size], id)
+ return pkg, err
default:
- err = fmt.Errorf("unknown export data header: %q", hdr)
+ l := len(data)
+ if l > 10 {
+ l = 10
+ }
+ return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), id)
}
-
- return
}
type byPath []*types.Package
diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go
index 1e19fbe..7dfc31a 100644
--- a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go
+++ b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go
@@ -246,6 +246,26 @@ import (
// IExportShallow encodes "shallow" export data for the specified package.
//
+// For types, we use "shallow" export data. Historically, the Go
+// compiler always produced a summary of the types for a given package
+// that included types from other packages that it indirectly
+// referenced: "deep" export data. This had the advantage that the
+// compiler (and analogous tools such as gopls) need only load one
+// file per direct import. However, it meant that the files tended to
+// get larger based on the level of the package in the import
+// graph. For example, higher-level packages in the kubernetes module
+// have over 1MB of "deep" export data, even when they have almost no
+// content of their own, merely because they mention a major type that
+// references many others. In pathological cases the export data was
+// 300x larger than the source for a package due to this quadratic
+// growth.
+//
+// "Shallow" export data means that the serialized types describe only
+// a single package. If those types mention types from other packages,
+// the type checker may need to request additional packages beyond
+// just the direct imports. Type information for the entire transitive
+// closure of imports is provided (lazily) by the DAG.
+//
// No promises are made about the encoding other than that it can be decoded by
// the same version of IIExportShallow. If you plan to save export data in the
// file system, be sure to include a cryptographic digest of the executable in
@@ -268,8 +288,8 @@ func IExportShallow(fset *token.FileSet, pkg *types.Package, reportf ReportFunc)
}
// IImportShallow decodes "shallow" types.Package data encoded by
-// IExportShallow in the same executable. This function cannot import data from
-// cmd/compile or gcexportdata.Write.
+// [IExportShallow] in the same executable. This function cannot import data
+// from cmd/compile or gcexportdata.Write.
//
// The importer calls getPackages to obtain package symbols for all
// packages mentioned in the export data, including the one being
diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go
index 21908a1..e260c0e 100644
--- a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go
+++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go
@@ -558,6 +558,14 @@ type importReader struct {
prevColumn int64
}
+// markBlack is redefined in iimport_go123.go, to work around golang/go#69912.
+//
+// If TypeNames are not marked black (in the sense of go/types cycle
+// detection), they may be mutated when dot-imported. Fix this by punching a
+// hole through the type, when compiling with Go 1.23. (The bug has been fixed
+// for 1.24, but the fix was not worth back-porting).
+var markBlack = func(name *types.TypeName) {}
+
func (r *importReader) obj(name string) {
tag := r.byte()
pos := r.pos()
@@ -570,6 +578,7 @@ func (r *importReader) obj(name string) {
}
typ := r.typ()
obj := aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ, tparams)
+ markBlack(obj) // workaround for golang/go#69912
r.declare(obj)
case constTag:
@@ -590,6 +599,9 @@ func (r *importReader) obj(name string) {
// declaration before recursing.
obj := types.NewTypeName(pos, r.currPkg, name, nil)
named := types.NewNamed(obj, nil, nil)
+
+ markBlack(obj) // workaround for golang/go#69912
+
// Declare obj before calling r.tparamList, so the new type name is recognized
// if used in the constraint of one of its own typeparams (see #48280).
r.declare(obj)
diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go
new file mode 100644
index 0000000..7586bfa
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go
@@ -0,0 +1,53 @@
+// 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.
+
+//go:build go1.22 && !go1.24
+
+package gcimporter
+
+import (
+ "go/token"
+ "go/types"
+ "unsafe"
+)
+
+// TODO(rfindley): delete this workaround once go1.24 is assured.
+
+func init() {
+ // Update markBlack so that it correctly sets the color
+ // of imported TypeNames.
+ //
+ // See the doc comment for markBlack for details.
+
+ type color uint32
+ const (
+ white color = iota
+ black
+ grey
+ )
+ type object struct {
+ _ *types.Scope
+ _ token.Pos
+ _ *types.Package
+ _ string
+ _ types.Type
+ _ uint32
+ color_ color
+ _ token.Pos
+ }
+ type typeName struct {
+ object
+ }
+
+ // If the size of types.TypeName changes, this will fail to compile.
+ const delta = int64(unsafe.Sizeof(typeName{})) - int64(unsafe.Sizeof(types.TypeName{}))
+ var _ [-delta * delta]int
+
+ markBlack = func(obj *types.TypeName) {
+ type uP = unsafe.Pointer
+ var ptr *typeName
+ *(*uP)(uP(&ptr)) = uP(obj)
+ ptr.color_ = black
+ }
+}
diff --git a/vendor/golang.org/x/tools/internal/imports/fix.go b/vendor/golang.org/x/tools/internal/imports/fix.go
index c151081..5ae5769 100644
--- a/vendor/golang.org/x/tools/internal/imports/fix.go
+++ b/vendor/golang.org/x/tools/internal/imports/fix.go
@@ -27,7 +27,6 @@ import (
"unicode"
"unicode/utf8"
- "golang.org/x/sync/errgroup"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/gocommand"
@@ -91,18 +90,6 @@ type ImportFix struct {
Relevance float64 // see pkg
}
-// An ImportInfo represents a single import statement.
-type ImportInfo struct {
- ImportPath string // import path, e.g. "crypto/rand".
- Name string // import name, e.g. "crand", or "" if none.
-}
-
-// A packageInfo represents what's known about a package.
-type packageInfo struct {
- name string // real package name, if known.
- exports map[string]bool // known exports.
-}
-
// parseOtherFiles parses all the Go files in srcDir except filename, including
// test files if filename looks like a test.
//
@@ -162,8 +149,8 @@ func addGlobals(f *ast.File, globals map[string]bool) {
// collectReferences builds a map of selector expressions, from
// left hand side (X) to a set of right hand sides (Sel).
-func collectReferences(f *ast.File) references {
- refs := references{}
+func collectReferences(f *ast.File) References {
+ refs := References{}
var visitor visitFn
visitor = func(node ast.Node) ast.Visitor {
@@ -233,7 +220,7 @@ func (p *pass) findMissingImport(pkg string, syms map[string]bool) *ImportInfo {
allFound := true
for right := range syms {
- if !pkgInfo.exports[right] {
+ if !pkgInfo.Exports[right] {
allFound = false
break
}
@@ -246,11 +233,6 @@ func (p *pass) findMissingImport(pkg string, syms map[string]bool) *ImportInfo {
return nil
}
-// references is set of references found in a Go file. The first map key is the
-// left hand side of a selector expression, the second key is the right hand
-// side, and the value should always be true.
-type references map[string]map[string]bool
-
// A pass contains all the inputs and state necessary to fix a file's imports.
// It can be modified in some ways during use; see comments below.
type pass struct {
@@ -258,27 +240,29 @@ type pass struct {
fset *token.FileSet // fset used to parse f and its siblings.
f *ast.File // the file being fixed.
srcDir string // the directory containing f.
- env *ProcessEnv // the environment to use for go commands, etc.
- loadRealPackageNames bool // if true, load package names from disk rather than guessing them.
- otherFiles []*ast.File // sibling files.
+ logf func(string, ...any)
+ source Source // the environment to use for go commands, etc.
+ loadRealPackageNames bool // if true, load package names from disk rather than guessing them.
+ otherFiles []*ast.File // sibling files.
+ goroot string
// Intermediate state, generated by load.
existingImports map[string][]*ImportInfo
- allRefs references
- missingRefs references
+ allRefs References
+ missingRefs References
// Inputs to fix. These can be augmented between successive fix calls.
lastTry bool // indicates that this is the last call and fix should clean up as best it can.
candidates []*ImportInfo // candidate imports in priority order.
- knownPackages map[string]*packageInfo // information about all known packages.
+ knownPackages map[string]*PackageInfo // information about all known packages.
}
// loadPackageNames saves the package names for everything referenced by imports.
-func (p *pass) loadPackageNames(imports []*ImportInfo) error {
- if p.env.Logf != nil {
- p.env.Logf("loading package names for %v packages", len(imports))
+func (p *pass) loadPackageNames(ctx context.Context, imports []*ImportInfo) error {
+ if p.logf != nil {
+ p.logf("loading package names for %v packages", len(imports))
defer func() {
- p.env.Logf("done loading package names for %v packages", len(imports))
+ p.logf("done loading package names for %v packages", len(imports))
}()
}
var unknown []string
@@ -289,20 +273,17 @@ func (p *pass) loadPackageNames(imports []*ImportInfo) error {
unknown = append(unknown, imp.ImportPath)
}
- resolver, err := p.env.GetResolver()
- if err != nil {
- return err
- }
-
- names, err := resolver.loadPackageNames(unknown, p.srcDir)
+ names, err := p.source.LoadPackageNames(ctx, p.srcDir, unknown)
if err != nil {
return err
}
+ // TODO(rfindley): revisit this. Why do we need to store known packages with
+ // no exports? The inconsistent data is confusing.
for path, name := range names {
- p.knownPackages[path] = &packageInfo{
- name: name,
- exports: map[string]bool{},
+ p.knownPackages[path] = &PackageInfo{
+ Name: name,
+ Exports: map[string]bool{},
}
}
return nil
@@ -330,8 +311,8 @@ func (p *pass) importIdentifier(imp *ImportInfo) string {
return imp.Name
}
known := p.knownPackages[imp.ImportPath]
- if known != nil && known.name != "" {
- return withoutVersion(known.name)
+ if known != nil && known.Name != "" {
+ return withoutVersion(known.Name)
}
return ImportPathToAssumedName(imp.ImportPath)
}
@@ -339,9 +320,9 @@ 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.
-func (p *pass) load() ([]*ImportFix, bool) {
- p.knownPackages = map[string]*packageInfo{}
- p.missingRefs = references{}
+func (p *pass) load(ctx context.Context) ([]*ImportFix, bool) {
+ p.knownPackages = map[string]*PackageInfo{}
+ p.missingRefs = References{}
p.existingImports = map[string][]*ImportInfo{}
// Load basic information about the file in question.
@@ -364,9 +345,11 @@ func (p *pass) load() ([]*ImportFix, bool) {
// f's imports by the identifier they introduce.
imports := collectImports(p.f)
if p.loadRealPackageNames {
- err := p.loadPackageNames(append(imports, p.candidates...))
+ err := p.loadPackageNames(ctx, append(imports, p.candidates...))
if err != nil {
- p.env.logf("loading package names: %v", err)
+ if p.logf != nil {
+ p.logf("loading package names: %v", err)
+ }
return nil, false
}
}
@@ -535,9 +518,10 @@ func (p *pass) assumeSiblingImportsValid() {
// We have the stdlib in memory; no need to guess.
rights = symbolNameSet(m)
}
- p.addCandidate(imp, &packageInfo{
+ // TODO(rfindley): we should set package name here, for consistency.
+ p.addCandidate(imp, &PackageInfo{
// no name; we already know it.
- exports: rights,
+ Exports: rights,
})
}
}
@@ -546,14 +530,14 @@ func (p *pass) assumeSiblingImportsValid() {
// addCandidate adds a candidate import to p, and merges in the information
// in pkg.
-func (p *pass) addCandidate(imp *ImportInfo, pkg *packageInfo) {
+func (p *pass) addCandidate(imp *ImportInfo, pkg *PackageInfo) {
p.candidates = append(p.candidates, imp)
if existing, ok := p.knownPackages[imp.ImportPath]; ok {
- if existing.name == "" {
- existing.name = pkg.name
+ if existing.Name == "" {
+ existing.Name = pkg.Name
}
- for export := range pkg.exports {
- existing.exports[export] = true
+ for export := range pkg.Exports {
+ existing.Exports[export] = true
}
} else {
p.knownPackages[imp.ImportPath] = pkg
@@ -581,19 +565,42 @@ func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *P
// getFixes gets the import fixes that need to be made to f in order to fix the imports.
// It does not modify the ast.
func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) ([]*ImportFix, error) {
+ source, err := NewProcessEnvSource(env, filename, f.Name.Name)
+ if err != nil {
+ return nil, err
+ }
+ goEnv, err := env.goEnv()
+ if err != nil {
+ return nil, err
+ }
+ return getFixesWithSource(ctx, fset, f, filename, goEnv["GOROOT"], env.logf, source)
+}
+
+func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, goroot string, logf func(string, ...any), source Source) ([]*ImportFix, error) {
+ // This logic is defensively duplicated from getFixes.
abs, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
srcDir := filepath.Dir(abs)
- env.logf("fixImports(filename=%q), abs=%q, srcDir=%q ...", filename, abs, srcDir)
+
+ if logf != nil {
+ logf("fixImports(filename=%q), srcDir=%q ...", filename, abs, srcDir)
+ }
// First pass: looking only at f, and using the naive algorithm to
// derive package names from import paths, see if the file is already
// complete. We can't add any imports yet, because we don't know
// if missing references are actually package vars.
- p := &pass{fset: fset, f: f, srcDir: srcDir, env: env}
- if fixes, done := p.load(); done {
+ p := &pass{
+ fset: fset,
+ f: f,
+ srcDir: srcDir,
+ logf: logf,
+ goroot: goroot,
+ source: source,
+ }
+ if fixes, done := p.load(ctx); done {
return fixes, nil
}
@@ -605,7 +612,7 @@ func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename st
// Second pass: add information from other files in the same package,
// like their package vars and imports.
p.otherFiles = otherFiles
- if fixes, done := p.load(); done {
+ if fixes, done := p.load(ctx); done {
return fixes, nil
}
@@ -618,10 +625,17 @@ func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename st
// Third pass: get real package names where we had previously used
// the naive algorithm.
- p = &pass{fset: fset, f: f, srcDir: srcDir, env: env}
+ p = &pass{
+ fset: fset,
+ f: f,
+ srcDir: srcDir,
+ logf: logf,
+ goroot: goroot,
+ source: p.source, // safe to reuse, as it's just a wrapper around env
+ }
p.loadRealPackageNames = true
p.otherFiles = otherFiles
- if fixes, done := p.load(); done {
+ if fixes, done := p.load(ctx); done {
return fixes, nil
}
@@ -835,7 +849,7 @@ func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchP
return true
},
dirFound: func(pkg *pkg) bool {
- return pkgIsCandidate(filename, references{searchPkg: nil}, pkg)
+ return pkgIsCandidate(filename, References{searchPkg: nil}, pkg)
},
packageNameLoaded: func(pkg *pkg) bool {
return pkg.packageName == searchPkg
@@ -1086,11 +1100,7 @@ func (e *ProcessEnv) invokeGo(ctx context.Context, verb string, args ...string)
return e.GocmdRunner.Run(ctx, inv)
}
-func addStdlibCandidates(pass *pass, refs references) error {
- goenv, err := pass.env.goEnv()
- if err != nil {
- return err
- }
+func addStdlibCandidates(pass *pass, refs References) error {
localbase := func(nm string) string {
ans := path.Base(nm)
if ans[0] == 'v' {
@@ -1105,13 +1115,13 @@ func addStdlibCandidates(pass *pass, refs references) error {
}
add := func(pkg string) {
// Prevent self-imports.
- if path.Base(pkg) == pass.f.Name.Name && filepath.Join(goenv["GOROOT"], "src", pkg) == pass.srcDir {
+ if path.Base(pkg) == pass.f.Name.Name && filepath.Join(pass.goroot, "src", pkg) == pass.srcDir {
return
}
exports := symbolNameSet(stdlib.PackageSymbols[pkg])
pass.addCandidate(
&ImportInfo{ImportPath: pkg},
- &packageInfo{name: localbase(pkg), exports: exports})
+ &PackageInfo{Name: localbase(pkg), Exports: exports})
}
for left := range refs {
if left == "rand" {
@@ -1175,91 +1185,14 @@ 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) error {
ctx, done := event.Start(ctx, "imports.addExternalCandidates")
defer done()
- var mu sync.Mutex
- found := make(map[string][]pkgDistance)
- callback := &scanCallback{
- rootFound: func(gopathwalk.Root) bool {
- return true // We want everything.
- },
- dirFound: func(pkg *pkg) bool {
- return pkgIsCandidate(filename, refs, pkg)
- },
- packageNameLoaded: func(pkg *pkg) bool {
- if _, want := refs[pkg.packageName]; !want {
- return false
- }
- if pkg.dir == pass.srcDir && pass.f.Name.Name == pkg.packageName {
- // The candidate is in the same directory and has the
- // same package name. Don't try to import ourselves.
- return false
- }
- if !canUse(filename, pkg.dir) {
- return false
- }
- mu.Lock()
- defer mu.Unlock()
- found[pkg.packageName] = append(found[pkg.packageName], pkgDistance{pkg, distance(pass.srcDir, pkg.dir)})
- return false // We'll do our own loading after we sort.
- },
- }
- resolver, err := pass.env.GetResolver()
+ results, err := pass.source.ResolveReferences(ctx, filename, refs)
if err != nil {
return err
}
- if err = resolver.scan(ctx, callback); err != nil {
- return err
- }
-
- // Search for imports matching potential package references.
- type result struct {
- imp *ImportInfo
- pkg *packageInfo
- }
- results := make([]*result, len(refs))
-
- g, ctx := errgroup.WithContext(ctx)
-
- searcher := symbolSearcher{
- logf: pass.env.logf,
- srcDir: pass.srcDir,
- xtest: strings.HasSuffix(pass.f.Name.Name, "_test"),
- loadExports: resolver.loadExports,
- }
-
- i := 0
- for pkgName, symbols := range refs {
- index := i // claim an index in results
- i++
- pkgName := pkgName
- symbols := symbols
-
- g.Go(func() error {
- found, err := searcher.search(ctx, found[pkgName], pkgName, symbols)
- if err != nil {
- return err
- }
- if found == nil {
- return nil // No matching package.
- }
-
- imp := &ImportInfo{
- ImportPath: found.importPathShort,
- }
- pkg := &packageInfo{
- name: pkgName,
- exports: symbols,
- }
- results[index] = &result{imp, pkg}
- return nil
- })
- }
- if err := g.Wait(); err != nil {
- return err
- }
for _, result := range results {
if result == nil {
@@ -1267,7 +1200,7 @@ func addExternalCandidates(ctx context.Context, pass *pass, refs references, fil
}
// Don't offer completions that would shadow predeclared
// names, such as github.com/coreos/etcd/error.
- if types.Universe.Lookup(result.pkg.name) != nil { // predeclared
+ if types.Universe.Lookup(result.Package.Name) != nil { // predeclared
// Ideally we would skip this candidate only
// if the predeclared name is actually
// referenced by the file, but that's a lot
@@ -1276,7 +1209,7 @@ func addExternalCandidates(ctx context.Context, pass *pass, refs references, fil
// user before long.
continue
}
- pass.addCandidate(result.imp, result.pkg)
+ pass.addCandidate(result.Import, result.Package)
}
return nil
}
@@ -1801,7 +1734,7 @@ func (s *symbolSearcher) searchOne(ctx context.Context, c pkgDistance, symbols m
// filename is the file being formatted.
// pkgIdent is the package being searched for, like "client" (if
// searching for "client.New")
-func pkgIsCandidate(filename string, refs references, pkg *pkg) bool {
+func pkgIsCandidate(filename string, refs References, pkg *pkg) bool {
// Check "internal" and "vendor" visibility:
if !canUse(filename, pkg.dir) {
return false
diff --git a/vendor/golang.org/x/tools/internal/imports/imports.go b/vendor/golang.org/x/tools/internal/imports/imports.go
index ff6b59a..2215a12 100644
--- a/vendor/golang.org/x/tools/internal/imports/imports.go
+++ b/vendor/golang.org/x/tools/internal/imports/imports.go
@@ -47,7 +47,14 @@ type Options struct {
// Process implements golang.org/x/tools/imports.Process with explicit context in opt.Env.
func Process(filename string, src []byte, opt *Options) (formatted []byte, err error) {
fileSet := token.NewFileSet()
- file, adjust, err := parse(fileSet, filename, src, opt)
+ var parserMode parser.Mode
+ if opt.Comments {
+ parserMode |= parser.ParseComments
+ }
+ if opt.AllErrors {
+ parserMode |= parser.AllErrors
+ }
+ file, adjust, err := parse(fileSet, filename, src, parserMode, opt.Fragment)
if err != nil {
return nil, err
}
@@ -66,17 +73,19 @@ 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, opt *Options) (fixes []*ImportFix, err error) {
+func FixImports(ctx context.Context, filename string, src []byte, goroot string, logf func(string, ...any), source Source) (fixes []*ImportFix, err error) {
ctx, done := event.Start(ctx, "imports.FixImports")
defer done()
fileSet := token.NewFileSet()
- file, _, err := parse(fileSet, filename, src, opt)
+ // TODO(rfindley): these default values for ParseComments and AllErrors were
+ // extracted from gopls, but are they even needed?
+ file, _, err := parse(fileSet, filename, src, parser.ParseComments|parser.AllErrors, true)
if err != nil {
return nil, err
}
- return getFixes(ctx, fileSet, file, filename, opt.Env)
+ return getFixesWithSource(ctx, fileSet, file, filename, goroot, logf, source)
}
// ApplyFixes applies all of the fixes to the file and formats it. extraMode
@@ -114,7 +123,7 @@ func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, e
// formatted file, and returns the postpocessed result.
func formatFile(fset *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) {
mergeImports(file)
- sortImports(opt.LocalPrefix, fset.File(file.Pos()), file)
+ sortImports(opt.LocalPrefix, fset.File(file.FileStart), file)
var spacesBefore []string // import paths we need spaces before
for _, impSection := range astutil.Imports(fset, file) {
// Within each block of contiguous imports, see if any
@@ -164,13 +173,9 @@ func formatFile(fset *token.FileSet, file *ast.File, src []byte, adjust func(ori
// parse parses src, which was read from filename,
// as a Go source file or statement list.
-func parse(fset *token.FileSet, filename string, src []byte, opt *Options) (*ast.File, func(orig, src []byte) []byte, error) {
- var parserMode parser.Mode // legacy ast.Object resolution is required here
- if opt.Comments {
- parserMode |= parser.ParseComments
- }
- if opt.AllErrors {
- parserMode |= parser.AllErrors
+func parse(fset *token.FileSet, filename string, src []byte, parserMode parser.Mode, fragment bool) (*ast.File, func(orig, src []byte) []byte, error) {
+ if parserMode&parser.SkipObjectResolution != 0 {
+ panic("legacy ast.Object resolution is required")
}
// Try as whole source file.
@@ -181,7 +186,7 @@ func parse(fset *token.FileSet, filename string, src []byte, opt *Options) (*ast
// If the error is that the source file didn't begin with a
// package line and we accept fragmented input, fall through to
// try as a source fragment. Stop and return on any other error.
- if !opt.Fragment || !strings.Contains(err.Error(), "expected 'package'") {
+ if !fragment || !strings.Contains(err.Error(), "expected 'package'") {
return nil, nil, err
}
diff --git a/vendor/golang.org/x/tools/internal/imports/source.go b/vendor/golang.org/x/tools/internal/imports/source.go
new file mode 100644
index 0000000..cbe4f3c
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/imports/source.go
@@ -0,0 +1,63 @@
+// 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"
+
+// These types document the APIs below.
+//
+// TODO(rfindley): consider making these defined types rather than aliases.
+type (
+ ImportPath = string
+ PackageName = string
+ Symbol = string
+
+ // References is set of References found in a Go file. The first map key is the
+ // left hand side of a selector expression, the second key is the right hand
+ // side, and the value should always be true.
+ References = map[PackageName]map[Symbol]bool
+)
+
+// A Result satisfies a missing import.
+//
+// The Import field describes the missing import spec, and the Package field
+// summarizes the package exports.
+type Result struct {
+ Import *ImportInfo
+ Package *PackageInfo
+}
+
+// An ImportInfo represents a single import statement.
+type ImportInfo struct {
+ ImportPath string // import path, e.g. "crypto/rand".
+ Name string // import name, e.g. "crand", or "" if none.
+}
+
+// A PackageInfo represents what's known about a package.
+type PackageInfo struct {
+ Name string // package name in the package declaration, if known
+ Exports map[string]bool // set of names of known package level sortSymbols
+}
+
+// A Source provides imports to satisfy unresolved references in the file being
+// fixed.
+type Source interface {
+ // LoadPackageNames queries PackageName information for the requested import
+ // paths, when operating from the provided srcDir.
+ //
+ // TODO(rfindley): try to refactor to remove this operation.
+ LoadPackageNames(ctx context.Context, srcDir string, paths []ImportPath) (map[ImportPath]PackageName, error)
+
+ // ResolveReferences asks the Source for the best package name to satisfy
+ // each of the missing references, in the context of fixing the given
+ // filename.
+ //
+ // Returns a map from package name to a [Result] for that package name that
+ // provides the required symbols. Keys may be omitted in the map if no
+ // candidates satisfy all missing references for that package name. It is up
+ // to each data source to select the best result for each entry in the
+ // missing map.
+ ResolveReferences(ctx context.Context, filename string, missing References) ([]*Result, error)
+}
diff --git a/vendor/golang.org/x/tools/internal/imports/source_env.go b/vendor/golang.org/x/tools/internal/imports/source_env.go
new file mode 100644
index 0000000..d14abaa
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/imports/source_env.go
@@ -0,0 +1,129 @@
+// 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"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "golang.org/x/sync/errgroup"
+ "golang.org/x/tools/internal/gopathwalk"
+)
+
+// ProcessEnvSource implements the [Source] interface using the legacy
+// [ProcessEnv] abstraction.
+type ProcessEnvSource struct {
+ env *ProcessEnv
+ srcDir string
+ filename string
+ pkgName string
+}
+
+// NewProcessEnvSource returns a [ProcessEnvSource] wrapping the given
+// env, to be used for fixing imports in the file with name filename in package
+// named pkgName.
+func NewProcessEnvSource(env *ProcessEnv, filename, pkgName string) (*ProcessEnvSource, error) {
+ abs, err := filepath.Abs(filename)
+ if err != nil {
+ return nil, err
+ }
+ srcDir := filepath.Dir(abs)
+ return &ProcessEnvSource{
+ env: env,
+ srcDir: srcDir,
+ filename: filename,
+ pkgName: pkgName,
+ }, nil
+}
+
+func (s *ProcessEnvSource) LoadPackageNames(ctx context.Context, srcDir string, unknown []string) (map[string]string, error) {
+ r, err := s.env.GetResolver()
+ if err != nil {
+ return nil, err
+ }
+ return r.loadPackageNames(unknown, srcDir)
+}
+
+func (s *ProcessEnvSource) ResolveReferences(ctx context.Context, filename string, refs map[string]map[string]bool) ([]*Result, error) {
+ var mu sync.Mutex
+ found := make(map[string][]pkgDistance)
+ callback := &scanCallback{
+ rootFound: func(gopathwalk.Root) bool {
+ return true // We want everything.
+ },
+ dirFound: func(pkg *pkg) bool {
+ return pkgIsCandidate(filename, refs, pkg)
+ },
+ packageNameLoaded: func(pkg *pkg) bool {
+ if _, want := refs[pkg.packageName]; !want {
+ return false
+ }
+ if pkg.dir == s.srcDir && s.pkgName == pkg.packageName {
+ // The candidate is in the same directory and has the
+ // same package name. Don't try to import ourselves.
+ return false
+ }
+ if !canUse(filename, pkg.dir) {
+ return false
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ found[pkg.packageName] = append(found[pkg.packageName], pkgDistance{pkg, distance(s.srcDir, pkg.dir)})
+ return false // We'll do our own loading after we sort.
+ },
+ }
+ resolver, err := s.env.GetResolver()
+ if err != nil {
+ return nil, err
+ }
+ if err := resolver.scan(ctx, callback); err != nil {
+ return nil, err
+ }
+
+ g, ctx := errgroup.WithContext(ctx)
+
+ searcher := symbolSearcher{
+ logf: s.env.logf,
+ srcDir: s.srcDir,
+ xtest: strings.HasSuffix(s.pkgName, "_test"),
+ loadExports: resolver.loadExports,
+ }
+
+ var resultMu sync.Mutex
+ results := make(map[string]*Result, len(refs))
+ for pkgName, symbols := range refs {
+ g.Go(func() error {
+ found, err := searcher.search(ctx, found[pkgName], pkgName, symbols)
+ if err != nil {
+ return err
+ }
+ if found == nil {
+ return nil // No matching package.
+ }
+
+ imp := &ImportInfo{
+ ImportPath: found.importPathShort,
+ }
+ pkg := &PackageInfo{
+ Name: pkgName,
+ Exports: symbols,
+ }
+ resultMu.Lock()
+ results[pkgName] = &Result{Import: imp, Package: pkg}
+ resultMu.Unlock()
+ return nil
+ })
+ }
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+ var ans []*Result
+ for _, x := range results {
+ ans = append(ans, x)
+ }
+ return ans, nil
+}
diff --git a/vendor/golang.org/x/tools/internal/imports/source_modindex.go b/vendor/golang.org/x/tools/internal/imports/source_modindex.go
new file mode 100644
index 0000000..05229f0
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/imports/source_modindex.go
@@ -0,0 +1,103 @@
+// 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
+
+// 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
+ mutex sync.Mutex
+ ix *modindex.Index
+ 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) {
+ if err := s.maybeReadIndex(); err != nil {
+ return nil, err
+ }
+ var cs []modindex.Candidate
+ for pkg, nms := range missing {
+ for nm := range nms {
+ x := s.ix.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) maybeReadIndex() error {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ var readIndex bool
+ if time.Now().After(s.expires) {
+ ok, err := modindex.Update(s.modcachedir)
+ if err != nil {
+ return err
+ }
+ if ok {
+ readIndex = true
+ }
+ }
+
+ if readIndex || s.ix == nil {
+ ix, err := modindex.ReadIndex(s.modcachedir)
+ if err != nil {
+ return err
+ }
+ s.ix = ix
+ // for now refresh every 15 minutes
+ s.expires = time.Now().Add(time.Minute * 15)
+ }
+
+ return nil
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/directories.go b/vendor/golang.org/x/tools/internal/modindex/directories.go
new file mode 100644
index 0000000..1e1a02f
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/directories.go
@@ -0,0 +1,135 @@
+// 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 modindex
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/mod/semver"
+ "golang.org/x/tools/internal/gopathwalk"
+)
+
+type directory struct {
+ path Relpath
+ importPath string
+ version string // semantic version
+ syms []symbol
+}
+
+// filterDirs groups the directories by import path,
+// sorting the ones with the same import path by semantic version,
+// most recent first.
+func byImportPath(dirs []Relpath) (map[string][]*directory, error) {
+ ans := make(map[string][]*directory) // key is import path
+ for _, d := range dirs {
+ ip, sv, err := DirToImportPathVersion(d)
+ if err != nil {
+ return nil, err
+ }
+ ans[ip] = append(ans[ip], &directory{
+ path: d,
+ importPath: ip,
+ version: sv,
+ })
+ }
+ for k, v := range ans {
+ semanticSort(v)
+ ans[k] = v
+ }
+ return ans, nil
+}
+
+// sort the directories by semantic version, latest first
+func semanticSort(v []*directory) {
+ slices.SortFunc(v, func(l, r *directory) int {
+ if n := semver.Compare(l.version, r.version); n != 0 {
+ return -n // latest first
+ }
+ return strings.Compare(string(l.path), string(r.path))
+ })
+}
+
+// modCacheRegexp splits a relpathpath into module, module version, and package.
+var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
+
+// DirToImportPathVersion computes import path and semantic version
+func DirToImportPathVersion(dir Relpath) (string, string, error) {
+ m := modCacheRegexp.FindStringSubmatch(string(dir))
+ // m[1] is the module path
+ // m[2] is the version major.minor.patch(-= 4 {
+ sig := strings.Split(flds[3], " ")
+ for i := 0; i < len(sig); i++ {
+ // $ cannot otherwise occur. removing the spaces
+ // almost works, but for chan struct{}, e.g.
+ sig[i] = strings.Replace(sig[i], "$", " ", -1)
+ }
+ px.Sig = toFields(sig)
+ }
+ }
+ ans = append(ans, px)
+ }
+ }
+ return ans
+}
+
+func toFields(sig []string) []Field {
+ ans := make([]Field, len(sig)/2)
+ for i := 0; i < len(ans); i++ {
+ ans[i] = Field{Arg: sig[2*i], Type: sig[2*i+1]}
+ }
+ return ans
+}
+
+// benchmarks show this is measurably better than strings.Split
+func fastSplit(x string) []string {
+ ans := make([]string, 0, 4)
+ nxt := 0
+ start := 0
+ for i := 0; i < len(x); i++ {
+ if x[i] != ' ' {
+ continue
+ }
+ ans = append(ans, x[start:i])
+ nxt++
+ start = i + 1
+ if nxt >= 3 {
+ break
+ }
+ }
+ ans = append(ans, x[start:])
+ return ans
+}
+
+func asLexType(c byte) LexType {
+ switch c {
+ case 'C':
+ return Const
+ case 'V':
+ return Var
+ case 'T':
+ return Type
+ case 'F':
+ return Func
+ }
+ return -1
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/modindex.go b/vendor/golang.org/x/tools/internal/modindex/modindex.go
new file mode 100644
index 0000000..355a53e
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/modindex.go
@@ -0,0 +1,164 @@
+// 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 modindex contains code for building and searching an index to
+// the Go module cache. The directory containing the index, returned by
+// IndexDir(), contains a file index-name- that contains the name
+// of the current index. We believe writing that short file is atomic.
+// ReadIndex reads that file to get the file name of the index.
+// WriteIndex writes an index with a unique name and then
+// writes that name into a new version of index-name-.
+// ( stands for the CurrentVersion of the index format.)
+package modindex
+
+import (
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "golang.org/x/mod/semver"
+)
+
+// Create always creates a new index for the go module cache that is in cachedir.
+func Create(cachedir string) error {
+ _, err := indexModCache(cachedir, true)
+ return err
+}
+
+// Update the index for the go module cache that is in cachedir,
+// If there is no existing index it will build one.
+// If there are changed directories since the last index, it will
+// write a new one and return true. Otherwise it returns false.
+func Update(cachedir string) (bool, error) {
+ return indexModCache(cachedir, false)
+}
+
+// indexModCache writes an index current as of when it is called.
+// If clear is true the index is constructed from all of GOMODCACHE
+// otherwise the index is constructed from the last previous index
+// and the updates to the cache. It returns true if it wrote an index,
+// false otherwise.
+func indexModCache(cachedir string, clear bool) (bool, error) {
+ cachedir, err := filepath.Abs(cachedir)
+ if err != nil {
+ return false, err
+ }
+ cd := Abspath(cachedir)
+ future := time.Now().Add(24 * time.Hour) // safely in the future
+ ok, err := modindexTimed(future, cd, clear)
+ if err != nil {
+ return false, err
+ }
+ return ok, nil
+}
+
+// modindexTimed writes an index current as of onlyBefore.
+// If clear is true the index is constructed from all of GOMODCACHE
+// otherwise the index is constructed from the last previous index
+// and all the updates to the cache before onlyBefore.
+// It returns true if it wrote a new index, false if it wrote nothing.
+func modindexTimed(onlyBefore time.Time, cachedir Abspath, clear bool) (bool, error) {
+ var curIndex *Index
+ if !clear {
+ var err error
+ curIndex, err = ReadIndex(string(cachedir))
+ if clear && err != nil {
+ return false, err
+ }
+ // TODO(pjw): check that most of those directories still exist
+ }
+ cfg := &work{
+ onlyBefore: onlyBefore,
+ oldIndex: curIndex,
+ cacheDir: cachedir,
+ }
+ if curIndex != nil {
+ cfg.onlyAfter = curIndex.Changed
+ }
+ if err := cfg.buildIndex(); err != nil {
+ return false, err
+ }
+ if len(cfg.newIndex.Entries) == 0 && curIndex != nil {
+ // no changes from existing curIndex, don't write a new index
+ return false, nil
+ }
+ if err := cfg.writeIndex(); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+type work struct {
+ onlyBefore time.Time // do not use directories later than this
+ onlyAfter time.Time // only interested in directories after this
+ // directories from before onlyAfter come from oldIndex
+ oldIndex *Index
+ newIndex *Index
+ cacheDir Abspath
+}
+
+func (w *work) buildIndex() error {
+ // The effective date of the new index should be at least
+ // slightly earlier than when the directories are scanned
+ // so set it now.
+ w.newIndex = &Index{Changed: time.Now(), Cachedir: w.cacheDir}
+ dirs := findDirs(string(w.cacheDir), w.onlyAfter, w.onlyBefore)
+ if len(dirs) == 0 {
+ return nil
+ }
+ newdirs, err := byImportPath(dirs)
+ if err != nil {
+ return err
+ }
+ // for each import path it might occur only in newdirs,
+ // only in w.oldIndex, or in both.
+ // If it occurs in both, use the semantically later one
+ if w.oldIndex != nil {
+ for _, e := range w.oldIndex.Entries {
+ found, ok := newdirs[e.ImportPath]
+ if !ok {
+ w.newIndex.Entries = append(w.newIndex.Entries, e)
+ continue // use this one, there is no new one
+ }
+ if semver.Compare(found[0].version, e.Version) > 0 {
+ // use the new one
+ } else {
+ // use the old one, forget the new one
+ w.newIndex.Entries = append(w.newIndex.Entries, e)
+ delete(newdirs, e.ImportPath)
+ }
+ }
+ }
+ // get symbol information for all the new diredtories
+ getSymbols(w.cacheDir, newdirs)
+ // assemble the new index entries
+ for k, v := range newdirs {
+ d := v[0]
+ pkg, names := processSyms(d.syms)
+ if pkg == "" {
+ continue // PJW: does this ever happen?
+ }
+ entry := Entry{
+ PkgName: pkg,
+ Dir: d.path,
+ ImportPath: k,
+ Version: d.version,
+ Names: names,
+ }
+ w.newIndex.Entries = append(w.newIndex.Entries, entry)
+ }
+ // sort the entries in the new index
+ slices.SortFunc(w.newIndex.Entries, func(l, r Entry) int {
+ if n := strings.Compare(l.PkgName, r.PkgName); n != 0 {
+ return n
+ }
+ return strings.Compare(l.ImportPath, r.ImportPath)
+ })
+ return nil
+}
+
+func (w *work) writeIndex() error {
+ return writeIndex(w.cacheDir, w.newIndex)
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/symbols.go b/vendor/golang.org/x/tools/internal/modindex/symbols.go
new file mode 100644
index 0000000..2e285ed
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/symbols.go
@@ -0,0 +1,189 @@
+// 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 modindex
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "golang.org/x/sync/errgroup"
+)
+
+// The name of a symbol contains information about the symbol:
+// T for types
+// C for consts
+// V for vars
+// and for funcs: F ( )*
+// any spaces in are replaced by $s so that the fields
+// of the name are space separated
+type symbol struct {
+ pkg string // name of the symbols's package
+ name string // declared name
+ kind string // T, C, V, or F
+ sig string // signature information, for F
+}
+
+// find the symbols for the best directories
+func getSymbols(cd Abspath, dirs map[string][]*directory) {
+ var g errgroup.Group
+ g.SetLimit(-1) // maybe throttle this some day
+ for _, vv := range dirs {
+ // throttling some day?
+ d := vv[0]
+ g.Go(func() error {
+ thedir := filepath.Join(string(cd), string(d.path))
+ mode := parser.SkipObjectResolution
+
+ fi, err := os.ReadDir(thedir)
+ if err != nil {
+ return nil // log this someday?
+ }
+ for _, fx := range fi {
+ if !strings.HasSuffix(fx.Name(), ".go") || strings.HasSuffix(fx.Name(), "_test.go") {
+ continue
+ }
+ fname := filepath.Join(thedir, fx.Name())
+ tr, err := parser.ParseFile(token.NewFileSet(), fname, nil, mode)
+ if err != nil {
+ continue // ignore errors, someday log them?
+ }
+ d.syms = append(d.syms, getFileExports(tr)...)
+ }
+ return nil
+ })
+ }
+ g.Wait()
+}
+
+func getFileExports(f *ast.File) []symbol {
+ pkg := f.Name.Name
+ if pkg == "main" {
+ return nil
+ }
+ var ans []symbol
+ // should we look for //go:build ignore?
+ for _, decl := range f.Decls {
+ switch decl := decl.(type) {
+ case *ast.FuncDecl:
+ if decl.Recv != nil {
+ // ignore methods, as we are completing package selections
+ continue
+ }
+ name := decl.Name.Name
+ dtype := decl.Type
+ // not looking at dtype.TypeParams. That is, treating
+ // generic functions just like non-generic ones.
+ sig := dtype.Params
+ kind := "F"
+ result := []string{fmt.Sprintf("%d", dtype.Results.NumFields())}
+ for _, x := range sig.List {
+ // This code creates a string representing the type.
+ // TODO(pjw): it may be fragile:
+ // 1. x.Type could be nil, perhaps in ill-formed code
+ // 2. ExprString might someday change incompatibly to
+ // include struct tags, which can be arbitrary strings
+ if x.Type == nil {
+ // Can this happen without a parse error? (Files with parse
+ // errors are ignored in getSymbols)
+ continue // maybe report this someday
+ }
+ tp := types.ExprString(x.Type)
+ if len(tp) == 0 {
+ // Can this happen?
+ continue // maybe report this someday
+ }
+ // This is only safe if ExprString never returns anything with a $
+ // The only place a $ can occur seems to be in a struct tag, which
+ // can be an arbitrary string literal, and ExprString does not presently
+ // print struct tags. So for this to happen the type of a formal parameter
+ // has to be a explict struct, e.g. foo(x struct{a int "$"}) and ExprString
+ // would have to show the struct tag. Even testing for this case seems
+ // a waste of effort, but let's not ignore such pathologies
+ if strings.Contains(tp, "$") {
+ continue
+ }
+ tp = strings.Replace(tp, " ", "$", -1)
+ if len(x.Names) == 0 {
+ result = append(result, "_")
+ result = append(result, tp)
+ } else {
+ for _, y := range x.Names {
+ result = append(result, y.Name)
+ result = append(result, tp)
+ }
+ }
+ }
+ sigs := strings.Join(result, " ")
+ if s := newsym(pkg, name, kind, sigs); s != nil {
+ ans = append(ans, *s)
+ }
+ case *ast.GenDecl:
+ switch decl.Tok {
+ case token.CONST, token.VAR:
+ tp := "V"
+ if decl.Tok == token.CONST {
+ tp = "C"
+ }
+ for _, sp := range decl.Specs {
+ for _, x := range sp.(*ast.ValueSpec).Names {
+ if s := newsym(pkg, x.Name, tp, ""); s != nil {
+ ans = append(ans, *s)
+ }
+ }
+ }
+ case token.TYPE:
+ for _, sp := range decl.Specs {
+ if s := newsym(pkg, sp.(*ast.TypeSpec).Name.Name, "T", ""); s != nil {
+ ans = append(ans, *s)
+ }
+ }
+ }
+ }
+ }
+ return ans
+}
+
+func newsym(pkg, name, kind, sig string) *symbol {
+ if len(name) == 0 || !ast.IsExported(name) {
+ return nil
+ }
+ sym := symbol{pkg: pkg, name: name, kind: kind, sig: sig}
+ return &sym
+}
+
+// return the package name and the value for the symbols.
+// if there are multiple packages, choose one arbitrarily
+// the returned slice is sorted lexicographically
+func processSyms(syms []symbol) (string, []string) {
+ if len(syms) == 0 {
+ return "", nil
+ }
+ slices.SortFunc(syms, func(l, r symbol) int {
+ return strings.Compare(l.name, r.name)
+ })
+ pkg := syms[0].pkg
+ var names []string
+ for _, s := range syms {
+ var nx string
+ if s.pkg == pkg {
+ if s.sig != "" {
+ nx = fmt.Sprintf("%s %s %s", s.name, s.kind, s.sig)
+ } else {
+ nx = fmt.Sprintf("%s %s", s.name, s.kind)
+ }
+ names = append(names, nx)
+ } else {
+ continue // PJW: do we want to keep track of these?
+ }
+ }
+ return pkg, names
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/types.go b/vendor/golang.org/x/tools/internal/modindex/types.go
new file mode 100644
index 0000000..ece4488
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/types.go
@@ -0,0 +1,25 @@
+// 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 modindex
+
+import (
+ "strings"
+)
+
+// some special types to avoid confusions
+
+// distinguish various types of directory names. It's easy to get confused.
+type Abspath string // absolute paths
+type Relpath string // paths with GOMODCACHE prefix removed
+
+func toRelpath(cachedir Abspath, s string) Relpath {
+ if strings.HasPrefix(s, string(cachedir)) {
+ if s == string(cachedir) {
+ return Relpath("")
+ }
+ return Relpath(s[len(cachedir)+1:])
+ }
+ return Relpath(s)
+}
diff --git a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go
index 44719de..66e69b4 100644
--- a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go
+++ b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go
@@ -5,7 +5,6 @@
// Package packagesinternal exposes internal-only fields from go/packages.
package packagesinternal
-var GetForTest = func(p interface{}) string { return "" }
var GetDepsErrors = func(p interface{}) []*PackageError { return nil }
type PackageError struct {
@@ -16,7 +15,6 @@ type PackageError struct {
var TypecheckCgo int
var DepsErrors int // must be set as a LoadMode to call GetDepsErrors
-var ForTest int // must be set as a LoadMode to call GetForTest
var SetModFlag = func(config interface{}, value string) {}
var SetModFile = func(config interface{}, value string) {}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/free.go b/vendor/golang.org/x/tools/internal/typeparams/free.go
index 3581082..0ade5c2 100644
--- a/vendor/golang.org/x/tools/internal/typeparams/free.go
+++ b/vendor/golang.org/x/tools/internal/typeparams/free.go
@@ -6,6 +6,8 @@ package typeparams
import (
"go/types"
+
+ "golang.org/x/tools/internal/aliases"
)
// Free is a memoization of the set of free type parameters within a
@@ -36,6 +38,18 @@ func (w *Free) Has(typ types.Type) (res bool) {
break
case *types.Alias:
+ if aliases.TypeParams(t).Len() > aliases.TypeArgs(t).Len() {
+ return true // This is an uninstantiated Alias.
+ }
+ // The expansion of an alias can have free type parameters,
+ // whether or not the alias itself has type parameters:
+ //
+ // func _[K comparable]() {
+ // type Set = map[K]bool // free(Set) = {K}
+ // type MapTo[V] = map[K]V // free(Map[foo]) = {V}
+ // }
+ //
+ // So, we must Unalias.
return w.Has(types.Unalias(t))
case *types.Array:
@@ -96,9 +110,8 @@ func (w *Free) Has(typ types.Type) (res bool) {
case *types.Named:
args := t.TypeArgs()
- // TODO(taking): this does not match go/types/infer.go. Check with rfindley.
if params := t.TypeParams(); params.Len() > args.Len() {
- return true
+ return true // this is an uninstantiated named type.
}
for i, n := 0, args.Len(); i < n; i++ {
if w.Has(args.At(i)) {
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go
index 8392328..df3ea52 100644
--- a/vendor/golang.org/x/tools/internal/typesinternal/types.go
+++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go
@@ -11,6 +11,8 @@ import (
"go/types"
"reflect"
"unsafe"
+
+ "golang.org/x/tools/internal/aliases"
)
func SetUsesCgo(conf *types.Config) bool {
@@ -63,3 +65,57 @@ func NameRelativeTo(pkg *types.Package) types.Qualifier {
return other.Name()
}
}
+
+// A NamedOrAlias is a [types.Type] that is named (as
+// defined by the spec) and capable of bearing type parameters: it
+// abstracts aliases ([types.Alias]) and defined types
+// ([types.Named]).
+//
+// Every type declared by an explicit "type" declaration is a
+// NamedOrAlias. (Built-in type symbols may additionally
+// have type [types.Basic], which is not a NamedOrAlias,
+// though the spec regards them as "named".)
+//
+// NamedOrAlias cannot expose the Origin method, because
+// [types.Alias.Origin] and [types.Named.Origin] have different
+// (covariant) result types; use [Origin] instead.
+type NamedOrAlias interface {
+ types.Type
+ Obj() *types.TypeName
+}
+
+// TypeParams is a light shim around t.TypeParams().
+// (go/types.Alias).TypeParams requires >= 1.23.
+func TypeParams(t NamedOrAlias) *types.TypeParamList {
+ switch t := t.(type) {
+ case *types.Alias:
+ return aliases.TypeParams(t)
+ case *types.Named:
+ return t.TypeParams()
+ }
+ return nil
+}
+
+// TypeArgs is a light shim around t.TypeArgs().
+// (go/types.Alias).TypeArgs requires >= 1.23.
+func TypeArgs(t NamedOrAlias) *types.TypeList {
+ switch t := t.(type) {
+ case *types.Alias:
+ return aliases.TypeArgs(t)
+ case *types.Named:
+ return t.TypeArgs()
+ }
+ return nil
+}
+
+// Origin returns the generic type of the Named or Alias type t if it
+// is instantiated, otherwise it returns t.
+func Origin(t NamedOrAlias) NamedOrAlias {
+ switch t := t.(type) {
+ case *types.Alias:
+ return aliases.Origin(t)
+ case *types.Named:
+ return t.Origin()
+ }
+ return t
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go
new file mode 100644
index 0000000..1066980
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go
@@ -0,0 +1,282 @@
+// 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 typesinternal
+
+import (
+ "fmt"
+ "go/ast"
+ "go/token"
+ "go/types"
+ "strconv"
+ "strings"
+)
+
+// ZeroString returns the string representation of the "zero" value of the type t.
+// This string can be used on the right-hand side of an assignment where the
+// left-hand side has that explicit type.
+// Exception: This does not apply to tuples. Their string representation is
+// informational only and cannot be used in an assignment.
+// When assigning to a wider type (such as 'any'), it's the caller's
+// responsibility to handle any necessary type conversions.
+// See [ZeroExpr] for a variant that returns an [ast.Expr].
+func ZeroString(t types.Type, qf types.Qualifier) string {
+ switch t := t.(type) {
+ case *types.Basic:
+ switch {
+ case t.Info()&types.IsBoolean != 0:
+ return "false"
+ case t.Info()&types.IsNumeric != 0:
+ return "0"
+ case t.Info()&types.IsString != 0:
+ return `""`
+ case t.Kind() == types.UnsafePointer:
+ fallthrough
+ case t.Kind() == types.UntypedNil:
+ return "nil"
+ default:
+ panic(fmt.Sprint("ZeroString for unexpected type:", t))
+ }
+
+ case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
+ return "nil"
+
+ case *types.Named, *types.Alias:
+ switch under := t.Underlying().(type) {
+ case *types.Struct, *types.Array:
+ return types.TypeString(t, qf) + "{}"
+ default:
+ return ZeroString(under, qf)
+ }
+
+ case *types.Array, *types.Struct:
+ return types.TypeString(t, qf) + "{}"
+
+ case *types.TypeParam:
+ // Assumes func new is not shadowed.
+ return "*new(" + types.TypeString(t, qf) + ")"
+
+ case *types.Tuple:
+ // Tuples are not normal values.
+ // We are currently format as "(t[0], ..., t[n])". Could be something else.
+ components := make([]string, t.Len())
+ for i := 0; i < t.Len(); i++ {
+ components[i] = ZeroString(t.At(i).Type(), qf)
+ }
+ return "(" + strings.Join(components, ", ") + ")"
+
+ case *types.Union:
+ // Variables of these types cannot be created, so it makes
+ // no sense to ask for their zero value.
+ panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+ default:
+ panic(t) // unreachable.
+ }
+}
+
+// ZeroExpr returns the ast.Expr representation of the "zero" value of the type t.
+// ZeroExpr is defined for types that are suitable for variables.
+// It may panic for other types such as Tuple or Union.
+// See [ZeroString] for a variant that returns a string.
+func ZeroExpr(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
+ switch t := typ.(type) {
+ case *types.Basic:
+ switch {
+ case t.Info()&types.IsBoolean != 0:
+ return &ast.Ident{Name: "false"}
+ case t.Info()&types.IsNumeric != 0:
+ return &ast.BasicLit{Kind: token.INT, Value: "0"}
+ case t.Info()&types.IsString != 0:
+ return &ast.BasicLit{Kind: token.STRING, Value: `""`}
+ case t.Kind() == types.UnsafePointer:
+ fallthrough
+ case t.Kind() == types.UntypedNil:
+ return ast.NewIdent("nil")
+ default:
+ panic(fmt.Sprint("ZeroExpr for unexpected type:", t))
+ }
+
+ case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
+ return ast.NewIdent("nil")
+
+ case *types.Named, *types.Alias:
+ switch under := t.Underlying().(type) {
+ case *types.Struct, *types.Array:
+ return &ast.CompositeLit{
+ Type: TypeExpr(f, pkg, typ),
+ }
+ default:
+ return ZeroExpr(f, pkg, under)
+ }
+
+ case *types.Array, *types.Struct:
+ return &ast.CompositeLit{
+ Type: TypeExpr(f, pkg, typ),
+ }
+
+ case *types.TypeParam:
+ return &ast.StarExpr{ // *new(T)
+ X: &ast.CallExpr{
+ // Assumes func new is not shadowed.
+ Fun: ast.NewIdent("new"),
+ Args: []ast.Expr{
+ ast.NewIdent(t.Obj().Name()),
+ },
+ },
+ }
+
+ case *types.Tuple:
+ // Unlike ZeroString, there is no ast.Expr can express tuple by
+ // "(t[0], ..., t[n])".
+ panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+ case *types.Union:
+ // Variables of these types cannot be created, so it makes
+ // no sense to ask for their zero value.
+ panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+ default:
+ panic(t) // unreachable.
+ }
+}
+
+// IsZeroExpr uses simple syntactic heuristics to report whether expr
+// is a obvious zero value, such as 0, "", nil, or false.
+// It cannot do better without type information.
+func IsZeroExpr(expr ast.Expr) bool {
+ switch e := expr.(type) {
+ case *ast.BasicLit:
+ return e.Value == "0" || e.Value == `""`
+ case *ast.Ident:
+ return e.Name == "nil" || e.Name == "false"
+ default:
+ return false
+ }
+}
+
+// TypeExpr returns syntax for the specified type. References to named types
+// from packages other than pkg are qualified by an appropriate package name, as
+// defined by the import environment of file.
+// It may panic for types such as Tuple or Union.
+func TypeExpr(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
+ switch t := typ.(type) {
+ case *types.Basic:
+ switch t.Kind() {
+ case types.UnsafePointer:
+ // TODO(hxjiang): replace the implementation with types.Qualifier.
+ return &ast.SelectorExpr{X: ast.NewIdent("unsafe"), Sel: ast.NewIdent("Pointer")}
+ default:
+ return ast.NewIdent(t.Name())
+ }
+
+ case *types.Pointer:
+ return &ast.UnaryExpr{
+ Op: token.MUL,
+ X: TypeExpr(f, pkg, t.Elem()),
+ }
+
+ case *types.Array:
+ return &ast.ArrayType{
+ Len: &ast.BasicLit{
+ Kind: token.INT,
+ Value: fmt.Sprintf("%d", t.Len()),
+ },
+ Elt: TypeExpr(f, pkg, t.Elem()),
+ }
+
+ case *types.Slice:
+ return &ast.ArrayType{
+ Elt: TypeExpr(f, pkg, t.Elem()),
+ }
+
+ case *types.Map:
+ return &ast.MapType{
+ Key: TypeExpr(f, pkg, t.Key()),
+ Value: TypeExpr(f, pkg, t.Elem()),
+ }
+
+ case *types.Chan:
+ dir := ast.ChanDir(t.Dir())
+ if t.Dir() == types.SendRecv {
+ dir = ast.SEND | ast.RECV
+ }
+ return &ast.ChanType{
+ Dir: dir,
+ Value: TypeExpr(f, pkg, t.Elem()),
+ }
+
+ case *types.Signature:
+ var params []*ast.Field
+ for i := 0; i < t.Params().Len(); i++ {
+ params = append(params, &ast.Field{
+ Type: TypeExpr(f, pkg, t.Params().At(i).Type()),
+ Names: []*ast.Ident{
+ {
+ Name: t.Params().At(i).Name(),
+ },
+ },
+ })
+ }
+ if t.Variadic() {
+ last := params[len(params)-1]
+ last.Type = &ast.Ellipsis{Elt: last.Type.(*ast.ArrayType).Elt}
+ }
+ var returns []*ast.Field
+ for i := 0; i < t.Results().Len(); i++ {
+ returns = append(returns, &ast.Field{
+ Type: TypeExpr(f, pkg, t.Results().At(i).Type()),
+ })
+ }
+ return &ast.FuncType{
+ Params: &ast.FieldList{
+ List: params,
+ },
+ Results: &ast.FieldList{
+ List: returns,
+ },
+ }
+
+ case interface{ Obj() *types.TypeName }: // *types.{Alias,Named,TypeParam}
+ switch t.Obj().Pkg() {
+ case pkg, nil:
+ return ast.NewIdent(t.Obj().Name())
+ }
+ pkgName := t.Obj().Pkg().Name()
+
+ // TODO(hxjiang): replace the implementation with types.Qualifier.
+ // If the file already imports the package under another name, use that.
+ for _, cand := range f.Imports {
+ if path, _ := strconv.Unquote(cand.Path.Value); path == t.Obj().Pkg().Path() {
+ if cand.Name != nil && cand.Name.Name != "" {
+ pkgName = cand.Name.Name
+ }
+ }
+ }
+ if pkgName == "." {
+ return ast.NewIdent(t.Obj().Name())
+ }
+ return &ast.SelectorExpr{
+ X: ast.NewIdent(pkgName),
+ Sel: ast.NewIdent(t.Obj().Name()),
+ }
+
+ case *types.Struct:
+ return ast.NewIdent(t.String())
+
+ case *types.Interface:
+ return ast.NewIdent(t.String())
+
+ case *types.Union:
+ // TODO(hxjiang): handle the union through syntax (~A | ... | ~Z).
+ // Remove nil check when calling typesinternal.TypeExpr.
+ return nil
+
+ case *types.Tuple:
+ panic("invalid input type types.Tuple")
+
+ default:
+ panic("unreachable")
+ }
+}
diff --git a/vendor/golang.org/x/tools/internal/versions/constraint.go b/vendor/golang.org/x/tools/internal/versions/constraint.go
deleted file mode 100644
index 179063d..0000000
--- a/vendor/golang.org/x/tools/internal/versions/constraint.go
+++ /dev/null
@@ -1,13 +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 versions
-
-import "go/build/constraint"
-
-// ConstraintGoVersion is constraint.GoVersion (if built with go1.21+).
-// Otherwise nil.
-//
-// Deprecate once x/tools is after go1.21.
-var ConstraintGoVersion func(x constraint.Expr) string
diff --git a/vendor/golang.org/x/tools/internal/versions/types.go b/vendor/golang.org/x/tools/internal/versions/types.go
index f0bb0d1..0fc10ce 100644
--- a/vendor/golang.org/x/tools/internal/versions/types.go
+++ b/vendor/golang.org/x/tools/internal/versions/types.go
@@ -31,8 +31,3 @@ func FileVersion(info *types.Info, file *ast.File) string {
// This would act as a max version on what a tool can support.
return Future
}
-
-// InitFileVersions initializes info to record Go versions for Go files.
-func InitFileVersions(info *types.Info) {
- info.FileVersions = make(map[*ast.File]string)
-}
diff --git a/vendor/gorm.io/driver/postgres/migrator.go b/vendor/gorm.io/driver/postgres/migrator.go
index df18db1..2293a7c 100644
--- a/vendor/gorm.io/driver/postgres/migrator.go
+++ b/vendor/gorm.io/driver/postgres/migrator.go
@@ -142,6 +142,10 @@ func (m Migrator) CreateIndex(value interface{}, name string) error {
createIndexSQL += " ?"
}
+ if idx.Option != "" {
+ createIndexSQL += " " + idx.Option
+ }
+
if idx.Where != "" {
createIndexSQL += " WHERE " + idx.Where
}
@@ -385,10 +389,16 @@ func (m Migrator) AlterColumn(value interface{}, field string) error {
return err
}
} else {
- if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? DROP DEFAULT", m.CurrentTable(stmt), clause.Column{Name: field.DBName}, clause.Expr{SQL: field.DefaultValue}).Error; err != nil {
+ if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? DROP DEFAULT", m.CurrentTable(stmt), clause.Column{Name: field.DBName}).Error; err != nil {
return err
}
}
+ } else if !field.HasDefaultValue {
+ // case - as-is column has default value and to-be column has no default value
+ // need to drop default
+ if err := m.DB.Exec("ALTER TABLE ? ALTER COLUMN ? DROP DEFAULT", m.CurrentTable(stmt), clause.Column{Name: field.DBName}).Error; err != nil {
+ return err
+ }
}
}
return nil
diff --git a/vendor/modules.txt b/vendor/modules.txt
index cba1d71..76fac16 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -22,11 +22,7 @@ github.com/dgryski/go-rendezvous
# github.com/fatih/color v1.18.0
## explicit; go 1.17
github.com/fatih/color
-# github.com/go-chi/chi v4.1.2+incompatible
-## explicit
-github.com/go-chi/chi
-github.com/go-chi/chi/middleware
-# github.com/go-chi/chi/v5 v5.1.0
+# github.com/go-chi/chi/v5 v5.2.0
## explicit; go 1.14
github.com/go-chi/chi/v5
github.com/go-chi/chi/v5/middleware
@@ -58,7 +54,7 @@ github.com/go-task/slim-sprig/v3
# github.com/gocarina/gocsv v0.0.0-20240520201108-78e41c74b4b1
## explicit; go 1.13
github.com/gocarina/gocsv
-# github.com/google/pprof v0.0.0-20241017200806-017d972448fc
+# github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad
## explicit; go 1.22
github.com/google/pprof/profile
# github.com/google/uuid v1.6.0
@@ -106,8 +102,8 @@ github.com/jinzhu/now
# github.com/json-iterator/go v1.1.12
## explicit; go 1.12
github.com/json-iterator/go
-# github.com/klauspost/cpuid/v2 v2.2.8
-## explicit; go 1.15
+# github.com/klauspost/cpuid/v2 v2.2.9
+## explicit; go 1.20
github.com/klauspost/cpuid/v2
# github.com/klauspost/reedsolomon v1.12.4
## explicit; go 1.21
@@ -134,8 +130,8 @@ github.com/modern-go/concurrent
# github.com/modern-go/reflect2 v1.0.2
## explicit; go 1.12
github.com/modern-go/reflect2
-# github.com/onsi/ginkgo/v2 v2.20.2
-## explicit; go 1.22
+# github.com/onsi/ginkgo/v2 v2.22.0
+## explicit; go 1.22.0
github.com/onsi/ginkgo/v2/config
github.com/onsi/ginkgo/v2/formatter
github.com/onsi/ginkgo/v2/ginkgo
@@ -161,7 +157,7 @@ github.com/pkg/errors
# github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2
## explicit
github.com/pmezard/go-difflib/difflib
-# github.com/quic-go/quic-go v0.48.0
+# github.com/quic-go/quic-go v0.48.2
## explicit; go 1.22
github.com/quic-go/quic-go
github.com/quic-go/quic-go/internal/ackhandler
@@ -183,7 +179,7 @@ github.com/quic-go/quic-go/quicvarint
## explicit; go 1.13
github.com/sirupsen/logrus
github.com/sirupsen/logrus/hooks/syslog
-# github.com/skycoin/dmsg v1.3.29-0.20241217193208-d32ec623e670
+# github.com/skycoin/dmsg v1.3.29-0.20241218010226-56d92f2ef624
## explicit; go 1.23
github.com/skycoin/dmsg/internal/servermetrics
github.com/skycoin/dmsg/pkg/direct
@@ -203,7 +199,7 @@ github.com/skycoin/skycoin/src/cipher/ripemd160
github.com/skycoin/skycoin/src/cipher/secp256k1-go
github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2
github.com/skycoin/skycoin/src/util/logging
-# github.com/skycoin/skywire v1.3.29-rc1.0.20241217192205-cb65518c5522
+# github.com/skycoin/skywire v1.3.29-rc1.0.20241217211947-72c9d0b82083
## explicit; go 1.23
github.com/skycoin/skywire
github.com/skycoin/skywire/internal/httpauth
@@ -240,9 +236,10 @@ github.com/spf13/pflag
# github.com/stretchr/objx v0.5.2
## explicit; go 1.20
github.com/stretchr/objx
-# github.com/stretchr/testify v1.9.0
+# github.com/stretchr/testify v1.10.0
## explicit; go 1.17
github.com/stretchr/testify/assert
+github.com/stretchr/testify/assert/yaml
github.com/stretchr/testify/mock
github.com/stretchr/testify/require
# github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161
@@ -270,7 +267,7 @@ go.etcd.io/bbolt
## explicit; go 1.22
go.uber.org/mock/mockgen
go.uber.org/mock/mockgen/model
-# golang.org/x/crypto v0.28.0
+# golang.org/x/crypto v0.31.0
## explicit; go 1.20
golang.org/x/crypto/blake2b
golang.org/x/crypto/blake2s
@@ -289,36 +286,36 @@ golang.org/x/crypto/ssh/terminal
golang.org/x/crypto/tea
golang.org/x/crypto/twofish
golang.org/x/crypto/xtea
-# golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c
+# golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67
## explicit; go 1.22.0
golang.org/x/exp/rand
-# golang.org/x/mod v0.21.0
+# golang.org/x/mod v0.22.0
## explicit; go 1.22.0
golang.org/x/mod/internal/lazyregexp
golang.org/x/mod/modfile
golang.org/x/mod/module
golang.org/x/mod/semver
-# golang.org/x/net v0.30.0
+# golang.org/x/net v0.32.0
## explicit; go 1.18
golang.org/x/net/bpf
golang.org/x/net/internal/iana
golang.org/x/net/internal/socket
golang.org/x/net/ipv4
golang.org/x/net/ipv6
-# golang.org/x/sync v0.8.0
+# golang.org/x/sync v0.10.0
## explicit; go 1.18
golang.org/x/sync/errgroup
golang.org/x/sync/semaphore
-# golang.org/x/sys v0.26.0
+# golang.org/x/sys v0.28.0
## explicit; go 1.18
golang.org/x/sys/cpu
golang.org/x/sys/plan9
golang.org/x/sys/unix
golang.org/x/sys/windows
-# golang.org/x/term v0.25.0
+# golang.org/x/term v0.27.0
## explicit; go 1.18
golang.org/x/term
-# golang.org/x/text v0.19.0
+# golang.org/x/text v0.21.0
## explicit; go 1.18
golang.org/x/text/cases
golang.org/x/text/internal
@@ -333,7 +330,7 @@ golang.org/x/text/transform
golang.org/x/text/unicode/bidi
golang.org/x/text/unicode/norm
golang.org/x/text/width
-# golang.org/x/tools v0.26.0
+# golang.org/x/tools v0.28.0
## explicit; go 1.22.0
golang.org/x/tools/cover
golang.org/x/tools/go/ast/astutil
@@ -352,6 +349,7 @@ golang.org/x/tools/internal/gcimporter
golang.org/x/tools/internal/gocommand
golang.org/x/tools/internal/gopathwalk
golang.org/x/tools/internal/imports
+golang.org/x/tools/internal/modindex
golang.org/x/tools/internal/packagesinternal
golang.org/x/tools/internal/pkgbits
golang.org/x/tools/internal/stdlib
@@ -361,7 +359,7 @@ golang.org/x/tools/internal/versions
# gopkg.in/yaml.v3 v3.0.1
## explicit
gopkg.in/yaml.v3
-# gorm.io/driver/postgres v1.5.9
+# gorm.io/driver/postgres v1.5.11
## explicit; go 1.19
gorm.io/driver/postgres
# gorm.io/gorm v1.25.12