Skip to content
60 changes: 60 additions & 0 deletions internal/loader/cgo_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package loader

import (
"context"
"go/token"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"golang.org/x/tools/go/packages"
)

// TestLocalCgoDiscoveryFallsBackWithoutLosingConstructors reproduces reuse of metadata that omitted native constructor bodies.
func TestLocalCgoDiscoveryFallsBackWithoutLosingConstructors(t *testing.T) {
setting, err := exec.Command("go", "env", "CGO_ENABLED").Output()
if err != nil {
t.Fatal(err)
}
if strings.TrimSpace(string(setting)) != "1" {
t.Skip("native cgo compiler is disabled")
}
root := t.TempDir()
writeTestFile(t, filepath.Join(root, "go.mod"), "module example.com/native\n\ngo 1.25\n")
writeTestFile(t, filepath.Join(root, "native", "types.go"), "package native\n\ntype Value struct { Number int }\n")
bridge := filepath.Join(root, "native", "bridge.go")
writeTestFile(t, bridge, "package native\n\n/* static int value(void) { return 7; } */\nimport \"C\"\n\nfunc New() *Value { return &Value{Number: int(C.value())} }\n")
writeTestFile(t, filepath.Join(root, "app", "app.go"), "package app\n\nimport \"example.com/native/native\"\n\nfunc Init() *native.Value { return native.New() }\n")
discovery, err := New().LoadRootGraph(context.Background(), RootLoadRequest{WD: root, Env: os.Environ(), Patterns: []string{"./app"}, NeedDeps: true})
if err != nil {
t.Fatal(err)
}
if discovery.Discovery == nil || len(discovery.Discovery.meta["example.com/native/native"].CgoFiles) != 1 {
t.Fatal("discovery lost cgo metadata")
}
result, err := New().LoadPackages(context.Background(), PackageLoadRequest{WD: root, Env: os.Environ(), Patterns: []string{"./app"}, Discovery: discovery.Discovery, Mode: packages.LoadAllSyntax, Fset: token.NewFileSet()})
if err != nil {
t.Fatal(err)
}
if result.Backend != ModeFallback || result.FallbackReason != FallbackReasonCustomUnsupported {
t.Fatalf("native graph backend = %#v", result)
}
for _, pkg := range collectGraph(result.Packages) {
if len(pkg.Errors) != 0 {
t.Fatalf("native package errors: %v", pkg.Errors)
}
if pkg.PkgPath == "example.com/native/native" && pkg.Types.Scope().Lookup("New") == nil {
t.Fatal("native constructor was lost")
}
}
entry, err := buildDiscoveryCacheEntry(goListRequest{WD: root, Env: os.Environ()}, discovery.Discovery.meta)
if err != nil {
t.Fatal(err)
}
writeTestFile(t, bridge, "package native\n\nimport _ \"strings\"\n\nfunc New() *Value { return &Value{Number: 8} }\n")
if validateDiscoveryCacheEntry(entry) {
t.Fatal("native source edit retained stale discovery")
}
}
13 changes: 13 additions & 0 deletions internal/loader/custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,15 @@ type unsupportedError struct {

func (e unsupportedError) Error() string { return e.reason }

// packageMeta preserves Go's file classification so native sources cannot disappear during cached discovery.
type packageMeta struct {
ImportPath string
Name string
Dir string
DepOnly bool
Export string
GoFiles []string
CgoFiles []string
CompiledGoFiles []string
Imports []string
ImportMap map[string]string
Expand Down Expand Up @@ -265,13 +267,20 @@ func loadPackagesCustom(ctx context.Context, req PackageLoadRequest) (*PackageLo
}, nil
}

// loadCustomPackagesFromMeta rejects native source before import errors can hide the fallback signal.
func loadCustomPackagesFromMeta(ctx context.Context, wd string, env []string, fset *token.FileSet, meta map[string]*packageMeta, targets map[string]struct{}, rootPaths []string, parseFile ParseFileFunc, discoveryDuration time.Duration, mode string) ([]*packages.Package, error) {
if len(meta) == 0 {
return nil, unsupportedError{reason: "empty go list result"}
}
if len(rootPaths) == 0 {
return nil, unsupportedError{reason: "no root packages from metadata"}
}
workspace := detectModuleRoot(wd)
for _, pkg := range meta {
if pkg != nil && len(pkg.CgoFiles) != 0 && isLocalSourcePackage(workspace, pkg) {
return nil, unsupportedError{reason: "local cgo source requires the native Go package loader"}
}
}
if fset == nil {
fset = token.NewFileSet()
}
Expand Down Expand Up @@ -1046,13 +1055,17 @@ func normalizeImports(imports []string, importMap map[string]string) []string {
return out
}

// metaFiles retains native import fingerprints when discovery intentionally skips compiled files.
func metaFiles(meta *packageMeta) []string {
if meta == nil {
return nil
}
if len(meta.CompiledGoFiles) > 0 {
return meta.CompiledGoFiles
}
if len(meta.CgoFiles) != 0 {
return append(append([]string(nil), meta.GoFiles...), meta.CgoFiles...)
}
return meta.GoFiles
}

Expand Down
6 changes: 6 additions & 0 deletions internal/loader/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type goListRequest struct {
SkipCompiled bool
}

// runGoList preserves source classifications across live and cached package discovery.
func runGoList(ctx context.Context, req goListRequest) (map[string]*packageMeta, error) {
cacheReadStart := time.Now()
if cached, ok := readDiscoveryCache(req); ok {
Expand Down Expand Up @@ -103,6 +104,11 @@ func runGoList(ctx context.Context, req goListRequest) (map[string]*packageMeta,
meta.GoFiles[i] = filepath.Join(meta.Dir, name)
}
}
for i, name := range meta.CgoFiles {
if !filepath.IsAbs(name) {
meta.CgoFiles[i] = filepath.Join(meta.Dir, name)
}
}
for i, name := range meta.CompiledGoFiles {
if !filepath.IsAbs(name) {
meta.CompiledGoFiles[i] = filepath.Join(meta.Dir, name)
Expand Down
2 changes: 1 addition & 1 deletion internal/loader/discovery_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type discoveryFileFingerprint struct {
Hash string
}

const discoveryCacheVersion = 5
const discoveryCacheVersion = 6

func readDiscoveryCache(req goListRequest) (map[string]*packageMeta, bool) {
entry, err := loadDiscoveryCacheEntry(req)
Expand Down
Loading