дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 02:44:37 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
aa1fd84a1d |
No files matched your search
@@ -3469,10 +3469,7 @@ impl LspManager {
|
||||
virtual_doc::is_decompiled(&text)
|
||||
};
|
||||
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
|
||||
let mut detected = self.languages.detect(Path::new(&title), None);
|
||||
if let Some(stem) = title.strip_suffix(".class").filter(|_| virtual_doc::is_java_class_stub(&text)) {
|
||||
detected = self.languages.detect(Path::new(&format!("{stem}.java")), None);
|
||||
}
|
||||
let detected = self.languages.detect(Path::new(&title), None);
|
||||
let language_id = if detected == LanguageId::plain_text() {
|
||||
languages.first().cloned().unwrap_or(detected)
|
||||
} else {
|
||||
|
||||
@@ -110,17 +110,6 @@ pub fn is_decompiled(text: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a `.class` stub is written in Java: its first `package` or `import` line ends with `;`.
|
||||
/// The Kotlin language server shows Java classes from jars as Java and Kotlin ones as Kotlin, under
|
||||
/// the same `.class` name.
|
||||
pub fn is_java_class_stub(text: &str) -> bool {
|
||||
text.lines()
|
||||
.take(200)
|
||||
.map(str::trim)
|
||||
.find(|line| line.starts_with("package ") || line.starts_with("import "))
|
||||
.is_some_and(|line| line.ends_with(';'))
|
||||
}
|
||||
|
||||
/// `scheme` of a URI (`jdt` for `jdt://…`).
|
||||
pub fn scheme(uri: &str) -> &str {
|
||||
uri.split_once(':').map(|(s, _)| s).unwrap_or("")
|
||||
@@ -216,17 +205,6 @@ mod tests {
|
||||
|
||||
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
|
||||
|
||||
#[test]
|
||||
fn class_stubs_in_java_or_kotlin() {
|
||||
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
|
||||
let kotlin = "// IntelliJ API Decompiler stub source generated from a class file\n// Implementation of methods is not available\n\npackage kotlin.collections\n\npublic fun <T> listOf(): List<T> { /* compiled code */ }\n";
|
||||
let imports_only = "import java.util.List;\n\npublic class A {}\n";
|
||||
assert!(is_java_class_stub(java));
|
||||
assert!(is_java_class_stub(imports_only));
|
||||
assert!(!is_java_class_stub(kotlin));
|
||||
assert!(!is_java_class_stub("public class A {}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharp_metadata_titles_and_kinds() {
|
||||
for (uri, expected) in [
|
||||
|
||||
@@ -75,7 +75,7 @@ import { resetAllEditorsFontZoom, stepAllEditorsFontZoom } from "./cm/prefs";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { menuGroupItems, notifications } from "@/workbench/contributions";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
@@ -529,29 +529,7 @@ function copyReference(reference: Promise<string>) {
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { doc, selection } = view.state;
|
||||
const line = doc.lineAt(selection.main.head).number;
|
||||
const { from, to } = selection.main;
|
||||
// The selected lines, leaving out the one a selection ends at the start of.
|
||||
const first = doc.lineAt(from).number;
|
||||
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
line: first - 1,
|
||||
endLine: last > first ? last - 1 : undefined,
|
||||
}).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
const line = view.state.doc.lineAt(view.state.selection.main.head).number;
|
||||
const flavours = [
|
||||
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
|
||||
{ id: "project.copyFileName", label: "File Name", value: pathToCopy("name", path) },
|
||||
@@ -579,7 +557,6 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
void executeAction(f.id, f.id === "editor.copyPathWithLineNumber" ? f.value : path);
|
||||
},
|
||||
})),
|
||||
...contributed,
|
||||
{
|
||||
id: "editor.copyReference",
|
||||
label: tx("Reference"),
|
||||
|
||||
@@ -10,7 +10,7 @@ import { LspPopups } from "@/editor/lsp/Popups";
|
||||
import { registerProjectActions } from "@/features/project-tree/actions";
|
||||
import { useProjectTree } from "@/features/project-tree/store";
|
||||
import { useContextMenuStore } from "@/ui";
|
||||
import { provideNotificationService, registerMenuGroup, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import * as controller from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { registerEditorActions } from "./actions";
|
||||
@@ -189,44 +189,6 @@ describe("editor Copy Path/Reference chooser", () => {
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
});
|
||||
|
||||
it("lists contributed links before Reference, for the selected lines", async () => {
|
||||
const contexts: MenuGroupContext[] = [];
|
||||
const run = vi.fn();
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => {
|
||||
contexts.push(ctx);
|
||||
return [{ id: "test.copyLink", label: "Host Link", verbatim: true, preview: "https://host/a#L1", run }];
|
||||
},
|
||||
}),
|
||||
);
|
||||
const view = ctrl.activeSlot!.view!;
|
||||
await executeAction("editor.copyPathReference");
|
||||
expect(
|
||||
popup()
|
||||
.items.map((item) => item.label)
|
||||
.slice(-2),
|
||||
).toEqual(["Host Link", "Reference"]);
|
||||
expect(popup().items.at(-2)).toMatchObject({
|
||||
preview: "https://host/a#L1",
|
||||
shortcut: shortcutLabel("test.copyLink"),
|
||||
});
|
||||
await popup().items.at(-2)!.run();
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
// From the first line into the second; then ending at the start of the second line.
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
expect(contexts.map(({ paths, line, endLine }) => [paths, line, endLine])).toEqual([
|
||||
[[path], 1, undefined],
|
||||
[[path], 0, 1],
|
||||
[[path], 0, undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds the chooser to Copy / Paste Special", () => {
|
||||
vi.spyOn(ctrl.activeSlot!.view!, "posAtCoords").mockReturnValue(null);
|
||||
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
|
||||
|
||||
@@ -499,7 +499,6 @@ describe("launch", () => {
|
||||
path: "/x/b.txt",
|
||||
left: { type: "file", path: "/x/a.txt", label: "/x/a.txt" },
|
||||
right: { type: "worktree", label: "/x/b.txt" },
|
||||
swappable: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -515,7 +514,6 @@ describe("launch", () => {
|
||||
path: "/p/b.txt",
|
||||
left: { type: "file", path: "/p/a.txt", label: "a.txt" },
|
||||
right: { type: "worktree", label: "b.txt" },
|
||||
swappable: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -78,9 +78,7 @@ export function appActions(): Action[] {
|
||||
id,
|
||||
title: t(key),
|
||||
category: t("app.category.edit"),
|
||||
// The native ⌘C / Ctrl+C keep working unbound; listed so another key can be added (IDEA's $Copy…).
|
||||
hidden: true,
|
||||
keymap: true,
|
||||
run: editCommand(command),
|
||||
});
|
||||
return [
|
||||
|
||||
@@ -100,25 +100,6 @@ describe("project view context menu", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference…", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [
|
||||
{ label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"Path From Content Root",
|
||||
"-",
|
||||
"Link /p/src true",
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows IDEA's order for a file", () => {
|
||||
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
|
||||
expect(labels(items)).toEqual([
|
||||
|
||||
@@ -215,8 +215,6 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -267,11 +267,6 @@ describe("shortcut search", () => {
|
||||
{ id: "internal.x", title: "Internal", hidden: true, run },
|
||||
];
|
||||
const draft = { preset: "intellij-macos", overrides: {} };
|
||||
// Hidden from Search Everywhere but keymap-listed (Cut / Copy / Paste) still shows.
|
||||
const copy = { id: "edit.copy", title: "Copy", category: "Edit", hidden: true, keymap: true, run };
|
||||
const withCopy = buildKeymapTree([...actions, copy], draft, "copy", "");
|
||||
const edit = withCopy[0]!.kind === "group" ? withCopy[0]!.children[0] : undefined;
|
||||
expect(edit?.kind === "group" && edit.children.map((n) => n.key)).toEqual(["edit.copy"]);
|
||||
const all = buildKeymapTree(actions, draft, "", "");
|
||||
expect(all.map((n) => n.key)).toEqual(["grp:Main Menu"]);
|
||||
const menu = all[0]!.kind === "group" ? all[0]!.children : [];
|
||||
|
||||
@@ -14,9 +14,4 @@ describe("settings window bridge", () => {
|
||||
expect(info).toEqual({ id: "a.b", title: "B", when: "editorFocus" });
|
||||
expect(JSON.parse(JSON.stringify(info))).toEqual(info);
|
||||
});
|
||||
|
||||
it("keeps the keymap flag so hidden Cut / Copy / Paste stay in the settings window's Keymap", () => {
|
||||
const [info] = describeActions([{ id: "edit.copy", title: "Copy", hidden: true, keymap: true, run: () => {} }]);
|
||||
expect(info).toMatchObject({ hidden: true, keymap: true });
|
||||
});
|
||||
});
|
||||
@@ -29,12 +29,7 @@ export function resolveBindings(draft: KeymapDraft, id: string): string[] {
|
||||
|
||||
/** Hidden actions with shortcuts stay configurable even after their bindings are removed. */
|
||||
export function isKeymapAction(action: Action, draft: KeymapDraft): boolean {
|
||||
return (
|
||||
!action.hidden ||
|
||||
!!action.keymap ||
|
||||
action.id in draft.overrides ||
|
||||
presetBindings(draft.preset, action.id).length > 0
|
||||
);
|
||||
return !action.hidden || action.id in draft.overrides || presetBindings(draft.preset, action.id).length > 0;
|
||||
}
|
||||
|
||||
export function isModified(draft: KeymapDraft, id: string): boolean {
|
||||
|
||||
@@ -21,7 +21,7 @@ const EXEC = "openidea://settings/exec";
|
||||
|
||||
export type ActionInfo = Pick<
|
||||
Action,
|
||||
"id" | "title" | "category" | "description" | "icon" | "when" | "keywords" | "hidden" | "keymap"
|
||||
"id" | "title" | "category" | "description" | "icon" | "when" | "keywords" | "hidden"
|
||||
>;
|
||||
|
||||
function currentLabel(): string | null {
|
||||
@@ -39,7 +39,7 @@ export function settingsWindowParent(label = currentLabel()): string | null {
|
||||
}
|
||||
|
||||
export function describeActions(actions: Iterable<Action> = allActions()): ActionInfo[] {
|
||||
return [...actions].map(({ id, title, category, description, icon, when, keywords, hidden, keymap }) => ({
|
||||
return [...actions].map(({ id, title, category, description, icon, when, keywords, hidden }) => ({
|
||||
id,
|
||||
title,
|
||||
category,
|
||||
@@ -48,7 +48,6 @@ export function describeActions(actions: Iterable<Action> = allActions()): Actio
|
||||
when,
|
||||
keywords,
|
||||
hidden,
|
||||
keymap,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { executeAction, registerActions, registerAction } from "@/platform/actions";
|
||||
import { clearContext, setContext } from "@/platform/context";
|
||||
import { menuGroupItems, provideNotificationService } from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
|
||||
const config = vi.hoisted(() => new Map<string, string>());
|
||||
const configReads = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
call: vi.fn(async (request: Promise<unknown>) => request),
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsConfigGet: async (root: string, key: string) => {
|
||||
configReads(root, key);
|
||||
return config.get(`${root} ${key}`) ?? null;
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { openOnRemoteActions, registerOpenOnRemote } from "../openOnRemote";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const writeText = vi.fn(async (_text: string) => undefined);
|
||||
const hint = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
type Item = Extract<MenuItem, { kind?: "item" }>;
|
||||
const items = (ctx: Parameters<typeof menuGroupItems>[1]) =>
|
||||
menuGroupItems("copyPath", ctx).filter((i): i is Item => i.kind !== "separator" && "run" in i);
|
||||
|
||||
async function start() {
|
||||
disposers.push(registerOpenOnRemote());
|
||||
await vi.waitFor(() => expect(items({ paths: ["/p/a.ts"] })).not.toEqual([]));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
config.clear();
|
||||
config.set("/p remote.origin.url", "[email protected]:group/sub/app.git");
|
||||
vi.stubGlobal("navigator", { clipboard: { writeText }, userAgent: navigator.userAgent });
|
||||
provideNotificationService({ notify });
|
||||
setContext("vcsAvailable", true);
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
repo: "/p",
|
||||
roots: ["/p"],
|
||||
branch: { name: "feature/x", upstream: "origin/feature/x" } as never,
|
||||
heads: {},
|
||||
});
|
||||
disposers.push(
|
||||
registerActions(openOnRemoteActions),
|
||||
registerAction({ id: "editor.showHint", title: "Hint", run: ({ arg }) => hint(arg) }),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
disposers
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((dispose) => dispose());
|
||||
useVcs.setState({ root: null, repo: null, roots: [], branch: null, heads: {} } as never);
|
||||
clearContext("vcsAvailable");
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Copy Path/Reference… › <hosting> Link", () => {
|
||||
it("offers the file's link at the selected lines and copies it", async () => {
|
||||
await start();
|
||||
const [item] = items({ paths: ["/p/src/a b.ts"], line: 9, endLine: 19 });
|
||||
expect(item).toMatchObject({
|
||||
id: "vcs.copyRemoteLink",
|
||||
label: "GitLab Link",
|
||||
preview: "https://gitlab.example.com/group/sub/app/-/blob/feature/x/src/a%20b.ts#L10-20",
|
||||
});
|
||||
item!.run!();
|
||||
await vi.waitFor(() => expect(writeText).toHaveBeenCalledExactlyOnceWith(item!.preview));
|
||||
expect(hint).toHaveBeenCalledWith({ text: `Copied ${item!.preview}` });
|
||||
});
|
||||
|
||||
it("links a single line, a directory, and the HEAD commit without an upstream", async () => {
|
||||
await start();
|
||||
expect(items({ paths: ["/p/a.ts"], line: 0 })[0]?.preview).toBe(
|
||||
"https://gitlab.example.com/group/sub/app/-/blob/feature/x/a.ts#L1",
|
||||
);
|
||||
expect(items({ paths: ["/p/src"], dirs: [true] })[0]?.preview).toBe(
|
||||
"https://gitlab.example.com/group/sub/app/-/tree/feature/x/src",
|
||||
);
|
||||
useVcs.setState({
|
||||
branch: { name: "main", upstream: null } as never,
|
||||
heads: { "/p": { headCommit: "abc123" } as never },
|
||||
});
|
||||
expect(items({ paths: ["/p/a.ts"], line: 2 })[0]?.preview).toBe(
|
||||
"https://gitlab.example.com/group/sub/app/-/blob/abc123/a.ts#L3",
|
||||
);
|
||||
});
|
||||
|
||||
it("offers nothing outside a repository, without a web remote, or for several paths", async () => {
|
||||
await start();
|
||||
expect(items({ paths: ["/elsewhere/a.ts"] })).toEqual([]);
|
||||
expect(items({ paths: ["/p/a.ts", "/p/b.ts"] })).toEqual([]);
|
||||
disposers.splice(-1).forEach((dispose) => dispose());
|
||||
config.set("/p remote.origin.url", "/srv/git/app.git");
|
||||
configReads.mockClear();
|
||||
disposers.push(registerOpenOnRemote());
|
||||
await vi.waitFor(() => expect(configReads).toHaveBeenCalledWith("/p", "remote.origin.url"));
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
expect(items({ paths: ["/p/a.ts"] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("warns instead of copying when the file has no page on a remote", async () => {
|
||||
await executeAction("vcs.copyRemoteLink", { path: "/elsewhere/a.ts", line: 0 });
|
||||
await vi.waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "This file has no page on a Git remote" })),
|
||||
);
|
||||
expect(writeText).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -51,29 +51,4 @@ describe("fileWebUrl", () => {
|
||||
"https://bitbucket.org/team/repo/src/main/a.py#lines-5",
|
||||
);
|
||||
});
|
||||
|
||||
it("selects a range of lines in each hosting's syntax", () => {
|
||||
const opts = { line: 9, endLine: 19 };
|
||||
expect(fileWebUrl("[email protected]:o/r.git", "main", "a.ts", opts)).toBe(
|
||||
"https://github.com/o/r/blob/main/a.ts#L10-L20",
|
||||
);
|
||||
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", opts)).toBe(
|
||||
"https://gitlab.com/g/r/-/blob/main/a.ts#L10-20",
|
||||
);
|
||||
expect(fileWebUrl("[email protected]:o/r.git", "main", "a.ts", opts)).toBe(
|
||||
"https://bitbucket.org/o/r/src/main/a.ts#lines-10:20",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a single line when the range ends on it or before, and none for directories", () => {
|
||||
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", { line: 4, endLine: 4 })).toBe(
|
||||
"https://gitlab.com/g/r/-/blob/main/a.ts#L5",
|
||||
);
|
||||
expect(fileWebUrl("[email protected]:g/r.git", "main", "a.ts", { line: 4, endLine: 2 })).toBe(
|
||||
"https://gitlab.com/g/r/-/blob/main/a.ts#L5",
|
||||
);
|
||||
expect(fileWebUrl("[email protected]:g/r.git", "main", "src", { dir: true, line: 4, endLine: 8 })).toBe(
|
||||
"https://gitlab.com/g/r/-/tree/main/src",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -214,28 +214,26 @@ export function remoteHosting(url: string): { name: string; kind: HostingKind }
|
||||
|
||||
/**
|
||||
* Page of a file or directory at `revision` on the remote's web UI, with the 0-based `line`
|
||||
* (through `endLine`, when later) selected. `relative` is the `/`-separated path inside the
|
||||
* repository ("" for its root).
|
||||
* selected. `relative` is the `/`-separated path inside the repository ("" for its root).
|
||||
*/
|
||||
export function fileWebUrl(
|
||||
remoteUrl: string,
|
||||
revision: string,
|
||||
relative: string,
|
||||
opts: { dir?: boolean; line?: number; endLine?: number } = {},
|
||||
opts: { dir?: boolean; line?: number } = {},
|
||||
): string | null {
|
||||
const base = remoteWebUrl(remoteUrl);
|
||||
const hosting = remoteHosting(remoteUrl);
|
||||
if (!base || !hosting) return null;
|
||||
const path = [...revision.split("/"), ...relative.split("/")].filter(Boolean).map(encodeURIComponent).join("/");
|
||||
const line = opts.line !== undefined && !opts.dir ? opts.line + 1 : null;
|
||||
const end = line && opts.endLine !== undefined && opts.endLine + 1 > line ? opts.endLine + 1 : null;
|
||||
switch (hosting.kind) {
|
||||
case "github":
|
||||
return `${base}/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}${end ? `-L${end}` : ""}` : ""}`;
|
||||
return `${base}/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}` : ""}`;
|
||||
case "gitlab":
|
||||
return `${base}/-/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}${end ? `-${end}` : ""}` : ""}`;
|
||||
return `${base}/-/${opts.dir ? "tree" : "blob"}/${path}${line ? `#L${line}` : ""}`;
|
||||
case "bitbucket":
|
||||
return `${base}/src/${path}${line ? `#lines-${line}${end ? `:${end}` : ""}` : ""}`;
|
||||
return `${base}/src/${path}${line ? `#lines-${line}` : ""}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
/**
|
||||
* Open In › GitHub / GitLab / Bitbucket: the file (at the caret line) or directory on the web UI
|
||||
* of its repository's remote, at the current branch's upstream (else the HEAD commit).
|
||||
* Copy Path/Reference… › <hosting> Link copies that page's address, with the selected lines.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { executeAction, type Action } from "@/platform/actions";
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { notifications, registerMenuGroup } from "@/workbench/contributions";
|
||||
import { openUrl } from "./issueLinks";
|
||||
import { fileWebUrl, remoteHosting, rootOf } from "./model";
|
||||
@@ -16,7 +13,6 @@ interface Target {
|
||||
path: string;
|
||||
dir?: boolean;
|
||||
line?: number;
|
||||
endLine?: number;
|
||||
}
|
||||
|
||||
/** Root → its remote's URL (null: none), read when the repositories change. */
|
||||
@@ -48,40 +44,14 @@ function targetArg(arg: unknown): Target | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The target's page on its remote, from the remote URL read for its root (`url`). */
|
||||
function pageFor(target: Target, root: string, url: string | null | undefined): string | null {
|
||||
const rev = revision(root);
|
||||
return url && rev ? fileWebUrl(url, rev, target.path.slice(root.length).replace(/^\/+/, ""), target) : null;
|
||||
}
|
||||
|
||||
async function remotePage(target: Target): Promise<string | null> {
|
||||
const root = rootOf(target.path, useVcs.getState().roots);
|
||||
return root ? pageFor(target, root, remoteUrls.get(root) ?? (await readRemoteUrl(root))) : null;
|
||||
}
|
||||
|
||||
function noPage() {
|
||||
notifications().notify({ group: "vcs", level: "warning", title: "This file has no page on a Git remote" });
|
||||
}
|
||||
|
||||
async function openOnRemote(target: Target) {
|
||||
const page = await remotePage(target);
|
||||
const root = rootOf(target.path, useVcs.getState().roots);
|
||||
const url = root ? (remoteUrls.get(root) ?? (await readRemoteUrl(root))) : null;
|
||||
const rev = root ? revision(root) : null;
|
||||
const page =
|
||||
root && url && rev ? fileWebUrl(url, rev, target.path.slice(root.length).replace(/^\/+/, ""), target) : null;
|
||||
if (page) await openUrl(page);
|
||||
else noPage();
|
||||
}
|
||||
|
||||
async function copyRemoteLink(target: Target) {
|
||||
const text = await remotePage(target);
|
||||
if (!text) return noPage();
|
||||
try {
|
||||
await writeClipboardText(text);
|
||||
void executeAction("editor.showHint", { text: tx`Copied ${text}` });
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot access the clipboard"),
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
else notifications().notify({ group: "vcs", level: "warning", title: "This file has no page on a Git remote" });
|
||||
}
|
||||
|
||||
export const openOnRemoteActions: Action[] = [
|
||||
@@ -98,19 +68,6 @@ export const openOnRemoteActions: Action[] = [
|
||||
if (target) void openOnRemote(target);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.copyRemoteLink",
|
||||
title: "Copy Link to Git Remote",
|
||||
description: "Copies the address of the file, its selected lines or the directory on its repository's remote.",
|
||||
category: "Git",
|
||||
icon: "copy",
|
||||
when: "vcsAvailable",
|
||||
hidden: true,
|
||||
run: ({ arg }) => {
|
||||
const target = targetArg(arg);
|
||||
if (target) void copyRemoteLink(target);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Open In › <hosting>, for files and directories inside a repository with a web remote. */
|
||||
@@ -125,28 +82,15 @@ export function registerOpenOnRemote(): () => void {
|
||||
});
|
||||
const unregister = registerMenuGroup({
|
||||
id: "vcs.openOnRemote",
|
||||
menus: ["openIn", "copyPath"],
|
||||
items: (menu, { paths, dirs, line, endLine }) => {
|
||||
menus: ["openIn"],
|
||||
items: (_menu, { paths, dirs, line }) => {
|
||||
if (paths.length !== 1) return [];
|
||||
const path = paths[0]!;
|
||||
const root = rootOf(path, useVcs.getState().roots);
|
||||
const url = root ? remoteUrls.get(root) : null;
|
||||
const hosting = url ? remoteHosting(url) : null;
|
||||
if (!root || !hosting) return [];
|
||||
if (!hosting) return [];
|
||||
const target: Target = { path, dir: dirs?.[0] ?? false, line };
|
||||
if (menu === "copyPath") {
|
||||
const page = pageFor({ ...target, endLine }, root, url);
|
||||
if (!page) return [];
|
||||
return [
|
||||
{
|
||||
id: "vcs.copyRemoteLink",
|
||||
label: tx`${hosting.name} Link`,
|
||||
verbatim: true,
|
||||
preview: page,
|
||||
run: () => void executeAction("vcs.copyRemoteLink", { ...target, endLine }),
|
||||
},
|
||||
];
|
||||
}
|
||||
return [
|
||||
{
|
||||
id: "vcs.openOnRemote",
|
||||
|
||||
@@ -49,8 +49,6 @@ export interface Action {
|
||||
verbatim?: boolean;
|
||||
/** Hidden from Search Everywhere (internal / parameterised actions). */
|
||||
hidden?: boolean;
|
||||
/** Listed in Settings › Keymap although `hidden`, so it can get a shortcut (Cut / Copy / Paste). */
|
||||
keymap?: boolean;
|
||||
/**
|
||||
* Marks a toggle action (IDEA's ToggleAction): returns the current state.
|
||||
* Search Everywhere shows an ON/OFF switch and keeps the popup open.
|
||||
|
||||
@@ -1570,9 +1570,6 @@
|
||||
"Open on Git Remote": "Open on Git Remote",
|
||||
"Opens the file or directory on the web page of its repository's remote.": "Opens the file or directory on the web page of its repository's remote.",
|
||||
"This file has no page on a Git remote": "This file has no page on a Git remote",
|
||||
"Copy Link to Git Remote": "Copy Link to Git Remote",
|
||||
"Copies the address of the file, its selected lines or the directory on its repository's remote.": "Copies the address of the file, its selected lines or the directory on its repository's remote.",
|
||||
"{name} Link": "{name} Link",
|
||||
"Run Agent Command": "Run Agent Command",
|
||||
"Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.": "Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.",
|
||||
"Archived agent tabs: {count}": "Archived agent tabs: {count}",
|
||||
|
||||
@@ -7966,9 +7966,6 @@
|
||||
"Open on Git Remote": "在 Git 远程上打开",
|
||||
"Opens the file or directory on the web page of its repository's remote.": "在仓库远程的网页上打开该文件或目录。",
|
||||
"This file has no page on a Git remote": "该文件在 Git 远程上没有对应页面",
|
||||
"Copy Link to Git Remote": "复制 Git 远程链接",
|
||||
"Copies the address of the file, its selected lines or the directory on its repository's remote.": "复制文件、所选行或目录在其仓库远程上的地址。",
|
||||
"{name} Link": "{name} 链接",
|
||||
"Run Agent Command": "运行智能体命令",
|
||||
"Runs `{ name, command, cwd, env }` from the MCP server's `run_command` in the agent tab `name`; throws when it did not start.": "在智能体标签 `name` 中运行 MCP 服务器 `run_command` 传来的 `{ name, command, cwd, env }`;未能启动时抛出错误。",
|
||||
"Archived agent tabs: {count}": "已归档的智能体标签:{count}",
|
||||
|
||||
@@ -51,8 +51,6 @@ export type MenuItem =
|
||||
/** The pointer or the keyboard made it the active item (not on opening the menu). */
|
||||
onActive?: () => void;
|
||||
submenu?: MenuItem[];
|
||||
/** The text the item copies, for choosers that show it (Copy Path/Reference…). */
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
interface Resolved {
|
||||
|
||||
@@ -1206,8 +1206,6 @@ export function projectViewRoots(map: ReadonlyMap<string, ProjectViewRootContrib
|
||||
// `selectIn` is the Select In chooser (⌥F1): targets for a file besides the project view.
|
||||
// `new` is the New popup / New › submenu (IDEA's NewGroup): file kinds a feature creates
|
||||
// in `paths[0]`, the target directory (features/templates: file templates, http-client: HTTP Request).
|
||||
// `copyPath` is the Copy Path/Reference… chooser: more things to copy for a file (features/vcs: its
|
||||
// link on the Git remote), each item's `preview` the copied text.
|
||||
|
||||
export type ContextMenuId =
|
||||
| "editor"
|
||||
@@ -1219,8 +1217,7 @@ export type ContextMenuId =
|
||||
| "openIn"
|
||||
| "stopProcess"
|
||||
| "selectIn"
|
||||
| "new"
|
||||
| "copyPath";
|
||||
| "new";
|
||||
|
||||
/**
|
||||
* Entries of open menu slots: the native main menu's (src-tauri/src/menu.rs
|
||||
@@ -1260,8 +1257,6 @@ export interface MenuGroupContext {
|
||||
text?: string;
|
||||
/** Editor menu: 0-based caret line; gutter menu: the clicked line. */
|
||||
line?: number;
|
||||
/** Copy Path/Reference… in the editor: the selection's last line, when it spans several. */
|
||||
endLine?: number;
|
||||
/** Zero-based UTF-16 column for problem/search result commands. */
|
||||
column?: number;
|
||||
/** The tab's input, when the menu is for an editor tab without a path. */
|
||||
|
||||
Reference in new issue
Заблокувати користувача