mirror of
https://github.com/giancarloerra/socraticode.git
synced 2026-07-03 14:05:21 +02:00
fix(graph): resolve Go imports via go.mod module path
Resolves #45. Reported by @mrsuit92. Go projects produced 0 dependency edges in codebase_graph_query and codebase_graph_stats even though import extraction worked correctly. The Go case in resolveImport returned null unconditionally, with a comment that resolution required go.mod analysis. This patch adds that analysis and wires it into the resolver, mirroring the existing buildJvmSuffixMap and buildCsNamespaceMap patterns. Mechanism: - buildGoModuleInfo reads <projectPath>/go.mod once at graph-build time, parses the `module <path>` directive, and walks the file set to build a directory-to-representative-file map for every Go package. _test.go files are excluded from representative selection because Go does not allow them to be imported from non-test code in other packages. Files are sorted lexicographically for deterministic representative selection across machines and runs. Returns null when go.mod is missing or has no parseable module directive; the resolver treats null as "no Go resolution available" and behaves exactly as before this patch in those cases. - The Go case in resolveImport now strips the module path prefix from the import (handling the bare-module-path root case as well as subpackage paths) and looks up the resulting directory in the package map. Imports outside the module path return null and are treated as external dependencies (or stdlib already filtered upstream by isExternalModule). - Map keys are forward-slash paths, not OS-native, so resolution works on Windows: Go imports are always forward-slash regardless of host OS, but path.dirname produces backslashes on Windows for nested directories. Normalising the key to forward slashes at build time keeps the lookup correct across platforms. Limitations (deferred to follow-up issues if any user reports them): - The parenthesised module ( path ) form in go.mod is not parsed. Not used by any mainstream Go project (verified against cobra, gin-gonic/gin, uber-go/zap real-world go.mod files). - vendor/ directory shadowing of external imports is not honoured. - replace directives in go.mod are not honoured. - go.work multi-module workspaces are not handled (each workspace module would need its own go.mod read and prefix matching). These are real Go features but each one widens the patch and narrowly affects specific user populations. They can be added as separate small PRs if a real user hits them. Tests: 16 new cases in tests/unit/graph-resolution.test.ts covering the new buildGoModuleInfo function (parses simple go.mod, handles leading whitespace and trailing content, returns null on missing or malformed go.mod, excludes _test.go from representative selection, omits test-only directories, uses forward-slash keys for nested packages) and the Go resolveImport case (back-compat null without goModuleInfo, subpackage import resolves to lex-smallest non-test .go file, root-package import resolves to a project-root .go file, external imports return null, missing or malformed go.mod returns null, _test.go excluded from representative selection, lexically smallest file picked deterministically, similar-prefix imports do not falsely resolve, nested-package imports work cross-platform). Existing 735 unit tests continue to pass unchanged. Total: 751. typecheck, biome, and CodeRabbit local review all clean. CodeRabbit caught a real Windows path-separator bug in the first iteration; the fix and a regression test for it are included. Co-authored-by: mrsuit92 <mrsuit92@users.noreply.github.com>
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,6 +213,7 @@ 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;
|
||||
@@ -206,9 +289,30 @@ 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. Imports outside the module path are
|
||||
// external dependencies (or stdlib already filtered upstream by
|
||||
// isExternalModule) and resolve 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,298 @@ 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("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