feat(go): go from a go.mod dependency to its folder under External Libraries (#4379)

⌘-click / ⌘B on the module path of a require entry (single line or block, quoted or not) or the replaced module of a replace entry in go.mod selects that module's folder under External Libraries › Go Modules: the module cache folder (path@version) or vendor/<path>. Modules that aren't downloaded, versions, comments and other directives fall through to gopls as before.

Closes #4378

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
This commit is contained in:
Mansur Akhmadi
2026-11-19 08:50:09 +08:00
committed by GitHub
co-authored by mansur-akhmadi
parent 72c84b9131
commit 42b99b9df7
3 changed files with 261 additions and 1 deletions
@@ -0,0 +1,144 @@
import { describe, expect, it, vi } from "vitest";
const actions = vi.hoisted(() => ({ executeAction: vi.fn() }));
vi.mock("@/platform/actions", () => actions);
vi.mock("@/editor/api", () => ({ CONTRIBUTED_DEFINITION: "openideaDefinition" }));
import { EditorState, Text } from "@codemirror/state";
import { goModModuleAt, goModNavigationExtension } from "./goModNavigation";
import { goModuleRoot } from "./index";
const DEFINITION = "openideaDefinition";
const gomod = `module example.com/app // require x.dev/not v1
go 1.24
require golang.org/x/text v0.21.0
require (
\tgithub.com/Org/Lib/v2 v2.1.0 // indirect
\t"example.com/quoted" v1.0.0
\t\`example.com/raw\` v1.0.0
\t// github.com/commented/out v1.0.0
)
replace example.com/old => ../old
replace (
\texample.com/a v1.0.0 => example.com/b v1.1.0
)
exclude example.com/bad v0.1.0
tool golang.org/x/tools/cmd/stringer
`;
const at = (needle: string, delta = 0) => gomod.indexOf(needle) + delta;
const doc = Text.of(gomod.split("\n"));
const moduleAt = (offset: number) => goModModuleAt(doc, offset)?.path ?? null;
describe("goModModuleAt", () => {
it("finds the module path of single-line and block require entries, edges included", () => {
const start = at("golang.org/x/text");
expect(goModModuleAt(doc, start)).toEqual({
path: "golang.org/x/text",
version: "v0.21.0",
from: start,
to: start + "golang.org/x/text".length,
});
expect(moduleAt(start + "golang.org/x/text".length)).toBe("golang.org/x/text");
expect(moduleAt(at("Org/Lib"))).toBe("github.com/Org/Lib/v2");
expect(moduleAt(at("example.com/quoted", 3))).toBe("example.com/quoted");
expect(moduleAt(at("example.com/raw", 3))).toBe("example.com/raw");
expect(moduleAt(at("`example.com/raw"))).toBeNull();
});
it("finds the replaced module of replace entries, not the replacement", () => {
expect(moduleAt(at("example.com/old"))).toBe("example.com/old");
expect(moduleAt(at("example.com/a v1"))).toBe("example.com/a");
expect(moduleAt(at("example.com/b"))).toBeNull();
expect(goModModuleAt(doc, at("example.com/old"))?.version).toBeNull();
expect(goModModuleAt(doc, at("example.com/a v1"))?.version).toBe("v1.0.0");
expect(moduleAt(at("../old"))).toBeNull();
});
it("ignores versions, keywords, comments and other directives", () => {
expect(moduleAt(at("v0.21.0", 2))).toBeNull();
expect(moduleAt(at("require golang", 2))).toBeNull();
expect(moduleAt(at("x.dev/not"))).toBeNull();
expect(moduleAt(at("github.com/commented"))).toBeNull();
expect(moduleAt(at("example.com/app"))).toBeNull();
expect(moduleAt(at("example.com/bad"))).toBeNull();
expect(moduleAt(at("golang.org/x/tools"))).toBeNull();
expect(moduleAt(at("require (", 8))).toBeNull();
expect(moduleAt(at(")\n\nreplace"))).toBeNull();
});
});
describe("goModuleRoot", () => {
const groups = [
{ name: "Go SDK 1.24", kind: "go", roots: [{ name: "src", path: "/go/src" }] },
{
name: "Go Modules",
kind: "goModules",
roots: [
{ name: "golang.org/x/text@v0.21.0", path: "/mod/golang.org/x/text@v0.21.0" },
{ name: "golang.org/x/text/v2@v2.0.0", path: "/mod/golang.org/x/text/v2@v2.0.0" },
{ name: "example.com/vendored", path: "/p/vendor/example.com/vendored" },
],
},
];
it("finds the downloaded version of a module, or its vendored folder", () => {
expect(goModuleRoot(groups, "golang.org/x/text", "v0.21.0")).toBe("/mod/golang.org/x/text@v0.21.0");
expect(goModuleRoot(groups, "golang.org/x/text/v2", "v2.0.0")).toBe("/mod/golang.org/x/text/v2@v2.0.0");
expect(goModuleRoot(groups, "example.com/vendored", "v1.0.0")).toBe("/p/vendor/example.com/vendored");
// A replace without a version names every version of the module.
expect(goModuleRoot(groups, "golang.org/x/text", null)).toBe("/mod/golang.org/x/text@v0.21.0");
});
it("finds no folder for another version, a path prefix or another group", () => {
expect(goModuleRoot(groups, "golang.org/x/text", "v0.3.0")).toBeNull();
expect(goModuleRoot(groups, "golang.org/x", null)).toBeNull();
expect(goModuleRoot(groups, "src", null)).toBeNull();
expect(goModuleRoot([], "golang.org/x/text", "v0.21.0")).toBeNull();
});
});
describe("goModNavigationExtension", () => {
const roots: Record<string, string> = { "golang.org/x/text@v0.21.0": "/mod/golang.org/x/text@v0.21.0" };
const state = (path = "/p/app/go.mod", virtual = false) =>
EditorState.create({
doc: gomod,
extensions: [
goModNavigationExtension(
(m, v) => roots[`${m}@${v}`] ?? null,
(p) => p.startsWith("/mod/"),
)({ path, virtual } as Parameters<ReturnType<typeof goModNavigationExtension>>[0]),
],
});
const definitionAt = (s: EditorState, pos: number) =>
s.languageDataAt<(v: { state: EditorState }, p: number) => boolean>(DEFINITION, pos)[0];
it("selects a downloaded module's folder in the project view", () => {
actions.executeAction.mockClear();
const s = state();
const pos = at("golang.org/x/text", 4);
expect(definitionAt(s, pos)!({ state: s }, pos)).toBe(true);
expect(actions.executeAction).toHaveBeenCalledWith(
"navigate.selectInProjectView",
"/mod/golang.org/x/text@v0.21.0",
);
});
it("leaves modules that are not downloaded, other positions and other files to the language server", () => {
expect(definitionAt(state(), at("Org/Lib"))).toBeUndefined();
expect(definitionAt(state(), at("v0.21.0"))).toBeUndefined();
expect(definitionAt(state("/p/app/go.work"), at("golang.org/x/text"))).toBeUndefined();
expect(definitionAt(state("/p/app/not-go.mod.txt"), at("golang.org/x/text"))).toBeUndefined();
expect(definitionAt(state("/p/app/go.mod", true), at("golang.org/x/text"))).toBeUndefined();
// A dependency's own go.mod resolves in its own module graph, not the project's.
expect(definitionAt(state("/mod/example.com/dep@v1.0.0/go.mod"), at("golang.org/x/text"))).toBeUndefined();
});
});
+85
View File
@@ -0,0 +1,85 @@
/**
* Go to declaration in `go.mod`, as in GoLand: ⌘/Ctrl-click (or ⌘B) on the module path of
* a `require` or `replace` line selects that module's folder under External Libraries
* (the module cache, or `vendor/`). A module that is not downloaded has no folder there
* and is left to the language server (its documentation link).
*/
import { EditorState, type Extension, type Text } from "@codemirror/state";
import { CONTRIBUTED_DEFINITION, type ContributedDefinition, type EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
interface GoModEntry {
path: string;
/** The required version; null on a `replace` without one. */
version: string | null;
from: number;
to: number;
}
const ENTRY = /^(\s*)(["`]?)([^\s"`()]+)\2(?:\s+([^\s=]+))?/;
const entries = new WeakMap<Text, GoModEntry[]>();
/** The module paths of the `require` / `replace` entries of `doc` (a replacement's own path excluded). */
function goModEntries(doc: Text): GoModEntry[] {
let list = entries.get(doc);
if (list) return list;
list = [];
let block: string | null = null;
for (let n = 1; n <= doc.lines; n++) {
const line = doc.line(n);
const comment = line.text.indexOf("//");
let code = comment < 0 ? line.text : line.text.slice(0, comment);
let offset = 0;
if (!block) {
const directive = /^\s*(\w+)\s*/.exec(code);
if (!directive) continue;
if (code.slice(directive[0].length).trim() === "(") {
block = directive[1]!;
continue;
}
if (directive[1] !== "require" && directive[1] !== "replace") continue;
offset = directive[0].length;
code = code.slice(offset);
} else if (code.trim() === ")") {
block = null;
continue;
} else if (block !== "require" && block !== "replace") continue;
const m = ENTRY.exec(code);
if (!m) continue;
const from = line.from + offset + m[1]!.length + m[2]!.length;
list.push({ path: m[3]!, version: m[4] ?? null, from, to: from + m[3]!.length });
}
entries.set(doc, list);
return list;
}
/** The `require` / `replace` entry whose module path covers `offset`. */
export function goModModuleAt(doc: Text, offset: number): GoModEntry | null {
return goModEntries(doc).find((e) => e.from <= offset && offset <= e.to) ?? null;
}
/**
* Go to declaration in the project's `go.mod` files; `moduleRoot` finds a module's External
* Libraries folder, `isLibrary` tells a library's own `go.mod` (whose graph is not the project's).
*/
export function goModNavigationExtension(
moduleRoot: (path: string, version: string | null) => string | null,
isLibrary: (path: string) => boolean,
) {
return (ctx: EditorDocContext): Extension => {
if (ctx.virtual || !/(^|[\\/])go\.mod$/.test(ctx.path) || isLibrary(ctx.path)) return [];
const rootAt = (state: EditorState, pos: number) => {
const entry = goModModuleAt(state.doc, pos);
return entry && moduleRoot(entry.path, entry.version);
};
const definition: ContributedDefinition = (view, pos) => {
const root = rootAt(view.state, pos);
if (!root) return false;
void executeAction("navigate.selectInProjectView", root);
return true;
};
return EditorState.languageData.of((state, pos) =>
rootAt(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
);
};
}
+32 -1
View File
@@ -12,10 +12,12 @@ import { commands, type LibraryGroup, type RequestId } from "@/bindings";
import { mergeLibraryGroups } from "@/platform/libraries";
import { isGradleBuildInput } from "@/platform/buildFiles";
import { registerActions } from "@/platform/actions";
import { setLibraryRoots } from "@/editor/api";
import { isLibraryPath, registerEditorContribution, setLibraryRoots } from "@/editor/api";
import { invalidateNavigationProviders } from "@/editor/navigationProviders";
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import { goModNavigationExtension } from "./goModNavigation";
export const EXTERNAL_LIBRARIES_LABEL = "External Libraries";
@@ -118,6 +120,24 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
};
}
/**
* The External Libraries folder of Go module `path` in `groups`: `path@version` in the module
* cache (any version when `version` is null), or `path` when vendored.
*/
export function goModuleRoot(groups: readonly LibraryGroup[], path: string, version: string | null): string | null {
for (const g of groups) {
if (g.kind !== "goModules") continue;
const versioned = version ? `${path}@${version}` : `${path}@`;
const root = g.roots.find(
(r) => r.name === path || (version ? r.name === versioned : r.name.startsWith(versioned)),
);
if (root) return root.path;
}
return null;
}
const goModules = (groups: readonly LibraryGroup[]) => JSON.stringify(groups.filter((g) => g.kind === "goModules"));
/** Settings that change which SDKs the project uses. */
const sdkKey = (s: ReturnType<typeof useProject.getState>) => {
const l = s.settings?.languages;
@@ -145,6 +165,8 @@ export function activate(): () => void {
let disposeRoot = () => {};
let disposeReadOnly = () => {};
let seq = 0;
/** The groups shown now. */
let shownGroups: LibraryGroup[] = [];
let shown = "";
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
@@ -156,6 +178,7 @@ export function activate(): () => void {
disposeReadOnly();
disposeRoot = disposeReadOnly = () => {};
shown = "";
shownGroups = [];
settled = [];
shownFor = null;
};
@@ -180,6 +203,9 @@ export function activate(): () => void {
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(groups) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = groups;
const root = librariesRoot(groups);
if (root) {
disposeReadOnly = setLibraryRoots(
@@ -212,6 +238,10 @@ export function activate(): () => void {
});
};
refresh();
const disposeGoMod = registerEditorContribution({
id: "libraries.goModNavigation",
extensions: goModNavigationExtension((path, version) => goModuleRoot(shownGroups, path, version), isLibraryPath),
});
const disposeActions = registerActions([
{ id: "libraries.reload", title: "Reload External Libraries", category: "Go", hidden: true, run: refresh },
]);
@@ -237,6 +267,7 @@ export function activate(): () => void {
unsubFs();
unsubRoots();
disposeActions();
disposeGoMod();
clear();
};
}