mirror of
https://github.com/giancarloerra/socraticode.git
synced 2026-07-03 14:05:21 +02:00
Merge pull request #48 from giancarloerra/fix/go-module-resolution
fix(graph): resolve Go imports via go.mod module path
This commit is contained in:
@@ -13,7 +13,7 @@ import type {
|
||||
} from "../types.js";
|
||||
import { loadPathAliases } from "./graph-aliases.js";
|
||||
import { extractImports } from "./graph-imports.js";
|
||||
import { buildCsNamespaceMap, buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
|
||||
import { buildCsNamespaceMap, buildGoModuleInfo, buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
|
||||
import { computeUnresolvedPct, resolveCallSites } from "./graph-symbol-resolution.js";
|
||||
import { extractSymbolsAndCalls, rawCallsToUnresolvedEdges } from "./graph-symbols.js";
|
||||
import { createIgnoreFilter, shouldIgnore } from "./ignore.js";
|
||||
@@ -668,6 +668,14 @@ export async function buildCodeGraph(
|
||||
const hasCs = files.some((f) => path.extname(f).toLowerCase() === ".cs");
|
||||
const csNamespaceMap = hasCs ? buildCsNamespaceMap(fileSet, resolvedPath) : undefined;
|
||||
|
||||
// Build Go module-resolution info from go.mod (issue #45). Without this,
|
||||
// every Go import resolved to null and Go projects produced an empty
|
||||
// file graph. The info is null when go.mod is missing or unparseable;
|
||||
// the resolver treats null as "no Go resolution available" and behaves
|
||||
// exactly as it did before this PR for those cases.
|
||||
const hasGo = files.some((f) => f.endsWith(".go"));
|
||||
const goModuleInfo = hasGo ? buildGoModuleInfo(fileSet, resolvedPath) : undefined;
|
||||
|
||||
for (const relPath of files) {
|
||||
const ext = path.extname(relPath).toLowerCase();
|
||||
const lang = getAstGrepLang(ext);
|
||||
@@ -738,7 +746,7 @@ export async function buildCodeGraph(
|
||||
// Try to resolve to a project file
|
||||
// CSS imports from <style> blocks use CSS resolution even when the source file is Svelte/Vue
|
||||
const resolutionLanguage = imp.isCssImport ? "css" : language;
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap, csNamespaceMap);
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap, csNamespaceMap, goModuleInfo);
|
||||
if (resolved) {
|
||||
node.dependencies.push(resolved);
|
||||
|
||||
|
||||
@@ -118,6 +118,88 @@ export function buildCsNamespaceMap(
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Information needed to resolve Go imports to local files.
|
||||
*
|
||||
* Built once per graph build by parsing the project's `go.mod` and walking
|
||||
* the file set. `modulePath` is the value of the `module` directive in
|
||||
* `go.mod` (e.g. `github.com/user/repo`); imports starting with this
|
||||
* prefix are local to the project. `packageMap` maps a Go package's
|
||||
* directory (relative to the project root, with "." for the root package)
|
||||
* to the lex-smallest non-test `.go` file in that directory, used as a
|
||||
* representative target for file-level edges in the graph.
|
||||
*
|
||||
* Returns null when `go.mod` is missing or malformed (no parseable
|
||||
* `module` directive). Callers must treat null as "no Go resolution
|
||||
* available" and return null for all Go imports.
|
||||
*/
|
||||
export interface GoModuleInfo {
|
||||
modulePath: string;
|
||||
packageMap: Map<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Go module-resolution info for a project.
|
||||
*
|
||||
* Reads `<projectPath>/go.mod` once, parses the module path with a regex,
|
||||
* and constructs a directory-to-representative-file map across all `.go`
|
||||
* files in the file set. `_test.go` files are excluded — Go does not
|
||||
* allow them to be imported from non-test code in other packages. Files
|
||||
* are sorted lexicographically before the map is built so the
|
||||
* representative chosen for each multi-file package is deterministic
|
||||
* across machines and runs.
|
||||
*
|
||||
* Cost: one `readFileSync` plus an O(n) walk over `.go` files at
|
||||
* graph-build time. Lookups during resolution are O(1).
|
||||
*
|
||||
* Limitations (deferred to follow-up issues if reported):
|
||||
* - Parenthesized `module ( ... )` form (rare; not used by any
|
||||
* mainstream Go project).
|
||||
* - `vendor/` directory shadowing of external imports.
|
||||
* - `replace` directives in `go.mod`.
|
||||
* - `go.work` multi-module workspaces.
|
||||
*/
|
||||
export function buildGoModuleInfo(
|
||||
fileSet: Set<string>,
|
||||
projectPath: string,
|
||||
): GoModuleInfo | null {
|
||||
let goModSource: string;
|
||||
try {
|
||||
goModSource = readFileSync(path.join(projectPath, "go.mod"), "utf-8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Match `module <path>` at the start of a line, allowing leading
|
||||
// horizontal whitespace and capturing the path token greedily up to
|
||||
// the next whitespace. Module paths are non-whitespace tokens (e.g.
|
||||
// `github.com/user/repo`, `go.uber.org/zap`).
|
||||
const match = goModSource.match(/^[ \t]*module[ \t]+(\S+)/m);
|
||||
if (!match) return null;
|
||||
const modulePath = match[1];
|
||||
|
||||
const goFiles = [...fileSet]
|
||||
.filter((f) => f.endsWith(".go") && !f.endsWith("_test.go"))
|
||||
.sort();
|
||||
|
||||
const packageMap = new Map<string, string>();
|
||||
for (const f of goFiles) {
|
||||
// Normalize the directory key to forward slashes. Go import paths
|
||||
// always use forward slashes regardless of host OS, so the key must
|
||||
// be in the same form for the lookup in resolveImport to succeed on
|
||||
// Windows (where path.dirname produces backslash separators for
|
||||
// nested directories like `pkg\subpkg`). The map value keeps the
|
||||
// file's native-separator form so it matches fileSet entries used
|
||||
// elsewhere as graph node keys.
|
||||
const dir = path.dirname(f).replace(/\\/g, "/"); // "." for files at the project root
|
||||
if (!packageMap.has(dir)) {
|
||||
packageMap.set(dir, f);
|
||||
}
|
||||
}
|
||||
|
||||
return { modulePath, packageMap };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a module specifier to a relative file path within the project.
|
||||
* Returns null if the module is external (e.g., npm package, stdlib).
|
||||
@@ -131,9 +213,16 @@ export function resolveImport(
|
||||
aliases?: PathAliases,
|
||||
jvmSuffixMap?: Map<string, string>,
|
||||
csNamespaceMap?: Map<string, string[]>,
|
||||
goModuleInfo?: GoModuleInfo | null,
|
||||
): string | null {
|
||||
// Skip obvious external/stdlib modules
|
||||
if (isExternalModule(moduleSpecifier, language)) return null;
|
||||
// Skip obvious external/stdlib modules. Go is excluded from this
|
||||
// pre-check because its external classifier in `isExternalModule`
|
||||
// treats any `golang.org/...` import as external, which would block
|
||||
// valid local imports for projects whose own module path starts with
|
||||
// `golang.org/` (e.g. someone working on `golang.org/x/sync` itself).
|
||||
// The Go case below performs its own module-path-aware classification
|
||||
// and returns null for everything outside the local module.
|
||||
if (language !== "go" && isExternalModule(moduleSpecifier, language)) return null;
|
||||
|
||||
const sourceDir = path.dirname(sourceFile);
|
||||
|
||||
@@ -206,9 +295,31 @@ export function resolveImport(
|
||||
}
|
||||
|
||||
case "go": {
|
||||
// Go imports are package paths; only track if it looks like a local module
|
||||
// (contains the module name or starts with ./)
|
||||
return null; // Go resolution requires go.mod analysis
|
||||
// Local Go imports are rooted at the module path declared in go.mod
|
||||
// (built by buildGoModuleInfo at graph-build time). When the import
|
||||
// starts with that prefix, strip it to get the package's directory
|
||||
// relative to the project root, then look up the representative
|
||||
// file for that directory. Anything else (stdlib like "fmt",
|
||||
// third-party packages like "github.com/x/y", or sibling-module
|
||||
// paths that share a prefix textually but not structurally)
|
||||
// resolves to null.
|
||||
if (!goModuleInfo) return null;
|
||||
if (!moduleSpecifier.startsWith(goModuleInfo.modulePath)) return null;
|
||||
const rest = moduleSpecifier.slice(goModuleInfo.modulePath.length);
|
||||
// rest === "" → the root package (the directory containing go.mod).
|
||||
// rest starts with "/" → a subpackage; strip the leading slash.
|
||||
// Anything else (e.g. an import that happens to share the prefix
|
||||
// but isn't actually a subpackage, like
|
||||
// `github.com/user/repo-other`) is external.
|
||||
let dir: string;
|
||||
if (rest === "") {
|
||||
dir = ".";
|
||||
} else if (rest.startsWith("/")) {
|
||||
dir = rest.slice(1);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return goModuleInfo.packageMap.get(dir) ?? null;
|
||||
}
|
||||
|
||||
case "java":
|
||||
|
||||
@@ -7,6 +7,7 @@ import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildCsNamespaceMap,
|
||||
buildGoModuleInfo,
|
||||
buildJvmSuffixMap,
|
||||
resolveImport,
|
||||
} from "../../src/services/graph-resolution.js";
|
||||
@@ -771,7 +772,10 @@ describe("graph-resolution", () => {
|
||||
// ── Go resolution ──────────────────────────────────────────────────────
|
||||
|
||||
describe("Go resolution", () => {
|
||||
it("returns null (Go requires go.mod analysis)", () => {
|
||||
it("returns null when no goModuleInfo is supplied (no go.mod path active)", () => {
|
||||
// Back-compat: when the resolver is called without Go module info
|
||||
// (e.g. for projects with no go.mod), every Go import resolves to
|
||||
// null. This is the path before issue #45's fix.
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
@@ -787,6 +791,326 @@ describe("graph-resolution", () => {
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves a subpackage import to the representative .go file (#45)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
"internal/util.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
expect(goInfo).not.toBeNull();
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/internal",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
// helper.go is the lexically smallest non-test .go file in
|
||||
// internal/, so it's picked as the package's representative.
|
||||
expect(result).toBe("internal/helper.go");
|
||||
});
|
||||
|
||||
it("resolves the root-package import to a project-root .go file", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"doc.go": "",
|
||||
"internal/helper.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp",
|
||||
path.join(project.root, "internal/helper.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("doc.go");
|
||||
});
|
||||
|
||||
it("returns null for external imports (not under module path)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"github.com/spf13/cobra",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod is missing", () => {
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
// No go.mod → buildGoModuleInfo returns null → resolver returns null
|
||||
// for any Go import.
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod has no module directive", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "go 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("excludes _test.go files from representative selection", () => {
|
||||
// service/foo.go and service/foo_test.go both exist in the same
|
||||
// directory. The map's representative should be foo.go (the
|
||||
// non-test file), not foo_test.go.
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"service/foo.go": "",
|
||||
"service/foo_test.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/service",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("service/foo.go");
|
||||
});
|
||||
|
||||
it("uses lexically smallest non-test file as the representative (determinism)", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"pkg/zeta.go": "",
|
||||
"pkg/alpha.go": "",
|
||||
"pkg/middle.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/pkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("pkg/alpha.go");
|
||||
});
|
||||
|
||||
it("resolves local imports when the module path starts with golang.org/", () => {
|
||||
// Real-world case: someone working ON one of the Go-team packages
|
||||
// like golang.org/x/sync. Their go.mod declares
|
||||
// `module golang.org/x/sync` and internal subpackages must resolve
|
||||
// locally, even though isExternalModule treats `golang.org/...`
|
||||
// imports as external for non-local-module projects.
|
||||
project = createTempProject({
|
||||
"go.mod": "module golang.org/x/custom\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/foo.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"golang.org/x/custom/internal",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("internal/foo.go");
|
||||
});
|
||||
|
||||
it("returns null for a similar-prefix import that is not a subpackage", () => {
|
||||
// `example.com/myapp-other/pkg` shares the prefix `example.com/myapp`
|
||||
// textually but is a separate module. Must not resolve to anything
|
||||
// inside the local project.
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"pkg/foo.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp-other/pkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGoModuleInfo", () => {
|
||||
it("parses a simple go.mod and returns module path + package map", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
"internal/helper.go": "",
|
||||
"internal/util.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).not.toBeNull();
|
||||
expect(goInfo?.modulePath).toBe("example.com/myapp");
|
||||
// Root package
|
||||
expect(goInfo?.packageMap.get(".")).toBe("main.go");
|
||||
// Subpackage — first lex-sorted file wins
|
||||
expect(goInfo?.packageMap.get("internal")).toBe("internal/helper.go");
|
||||
});
|
||||
|
||||
it("parses go.mod with leading whitespace and trailing content", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": " module github.com/user/repo\n\ngo 1.21\n\nrequire (\n\tgithub.com/x/y v1.0.0\n)\n",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.modulePath).toBe("github.com/user/repo");
|
||||
});
|
||||
|
||||
it("returns null when go.mod is missing", () => {
|
||||
project = createTempProject({
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when go.mod has no module directive", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "// no module line\ngo 1.21\n",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo).toBeNull();
|
||||
});
|
||||
|
||||
it("excludes _test.go files from the package map representatives", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"service/foo_test.go": "",
|
||||
"service/foo.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.packageMap.get("service")).toBe("service/foo.go");
|
||||
});
|
||||
|
||||
it("does not include directories that contain only _test.go files", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"internal/only_test.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
// Map has "." (for main.go) but no "internal" entry, because the
|
||||
// only file there is a test file.
|
||||
expect(goInfo?.packageMap.has(".")).toBe(true);
|
||||
expect(goInfo?.packageMap.has("internal")).toBe(false);
|
||||
});
|
||||
|
||||
it("uses forward-slash keys for nested packages (cross-platform lookup)", () => {
|
||||
// Go imports always use forward slashes; the map keys must match
|
||||
// that form so resolution works on Windows, where path.dirname
|
||||
// would otherwise produce backslash-separated keys for nested
|
||||
// packages. The map value preserves the fileSet's native form
|
||||
// (test fixtures use forward slashes since createTempProject keys
|
||||
// its fileSet by the input relPath).
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"pkg/subpkg/file.go": "",
|
||||
});
|
||||
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
expect(goInfo?.packageMap.has("pkg/subpkg")).toBe(true);
|
||||
expect(goInfo?.packageMap.get("pkg/subpkg")).toBe("pkg/subpkg/file.go");
|
||||
});
|
||||
|
||||
it("resolves nested-package imports", () => {
|
||||
project = createTempProject({
|
||||
"go.mod": "module example.com/myapp\n",
|
||||
"pkg/subpkg/file.go": "",
|
||||
"main.go": "",
|
||||
});
|
||||
const goInfo = buildGoModuleInfo(project.fileSet, project.root);
|
||||
|
||||
const result = resolveImport(
|
||||
"example.com/myapp/pkg/subpkg",
|
||||
path.join(project.root, "main.go"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"go",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
goInfo,
|
||||
);
|
||||
|
||||
expect(result).toBe("pkg/subpkg/file.go");
|
||||
});
|
||||
});
|
||||
|
||||
// ── C# resolution ─────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user