From 75781a57310926b3262c2dac308a7f680bebccec Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 02:25:17 +0800 Subject: [PATCH] fix(project): rename the type of a copied Java file to the copy's name (#5668) Copying a .java file kept the type under its old name, so the copy failed to compile, and the default name "Foo copy.java" could never be a type name. A Java source now gets a default copy name its type can take (FooCopy.java, FooCopy2.java), and a copy under a new name renames the top-level type in it: its declaration, constructors and the copy's own references, not strings, comments or same-named members. Applies to Copy (F5) and to copy and paste in the Project view. Fixes #5647 --- src/features/project-tree/javaCopy.test.ts | 78 ++++++++++++++++++++++ src/features/project-tree/javaCopy.ts | 77 +++++++++++++++++++++ src/features/project-tree/operations.ts | 6 +- src/features/project-tree/paths.test.ts | 4 ++ src/features/project-tree/paths.ts | 9 ++- 5 files changed, 171 insertions(+), 3 deletions(-) create mode 100644 src/features/project-tree/javaCopy.test.ts create mode 100644 src/features/project-tree/javaCopy.ts diff --git a/src/features/project-tree/javaCopy.test.ts b/src/features/project-tree/javaCopy.test.ts new file mode 100644 index 0000000000..6df1f77a7a --- /dev/null +++ b/src/features/project-tree/javaCopy.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { commands, type DocumentInfo } from "@/platform/ipc"; +import { copiedJavaType, renameCopiedJavaType, renameJavaTypeEdits } from "./javaCopy"; + +const SOURCE = `package a; + +/** Foo, the original. */ +public class Foo extends Base { + static final Foo INSTANCE = new Foo(); + private Foo() { this(1); } + Foo(int x) {} + static Foo of() { return Foo.INSTANCE; } + Object me() { return Foo.this; } + String s = "Foo"; // Foo + List all = Foo.list(Foo::of); + void Foo() {} +} +class Helper { Foo f; } +`; + +function apply(text: string, edits: { from: number; to: number; insert: string }[]): string { + return [...edits].reverse().reduce((t, e) => t.slice(0, e.from) + e.insert + t.slice(e.to), text); +} + +describe("copying a Java source (#5647)", () => { + afterEach(() => vi.restoreAllMocks()); + + it("renames the type, its constructors and references, not strings, comments or a same-named method", () => { + const out = apply(SOURCE, renameJavaTypeEdits(SOURCE, "Foo", "Bar")); + expect(out).toContain("public class Bar extends Base {"); + expect(out).toContain("static final Bar INSTANCE = new Bar();"); + expect(out).toContain("private Bar() { this(1); }"); + expect(out).toContain(" Bar(int x) {}"); + expect(out).toContain("static Bar of() { return Bar.INSTANCE; }"); + expect(out).toContain("return Bar.this;"); + expect(out).toContain('String s = "Foo"; // Foo'); + expect(out).toContain("/** Foo, the original. */"); + expect(out).toContain("List all = Bar.list(Bar::of);"); + expect(out).toContain("void Foo() {}"); + expect(out).toContain("class Helper { Bar f; }"); + }); + + it("leaves a file that declares no top-level type of the old name", () => { + expect(renameJavaTypeEdits("class Other { Foo f; }", "Foo", "Bar")).toEqual([]); + }); + + it("renames only between two Java names that differ", () => { + expect(copiedJavaType("Foo.java", "FooCopy.java")).toEqual({ oldName: "Foo", newName: "FooCopy" }); + expect(copiedJavaType("Foo.java", "Foo copy.java")).toBeNull(); + expect(copiedJavaType("Foo.java", "Foo.java")).toBeNull(); + expect(copiedJavaType("Foo.kt", "Bar.kt")).toBeNull(); + expect(copiedJavaType("Foo.java", "Bar.txt")).toBeNull(); + }); + + it("saves the renamed copy through a document", async () => { + const info = { id: 4, version: 1, text: "public class Foo { Foo() {} }\n" } as DocumentInfo; + const open = vi.spyOn(commands, "docOpen").mockResolvedValue({ status: "ok", data: info }); + const edit = vi.spyOn(commands, "docEdit").mockResolvedValue({ status: "ok", data: 2 } as never); + const save = vi.spyOn(commands, "docSave").mockResolvedValue({ status: "ok", data: null } as never); + const close = vi.spyOn(commands, "docClose").mockResolvedValue({ status: "ok", data: null } as never); + await renameCopiedJavaType("/p/src/Foo.java", "/p/src/FooCopy.java"); + expect(open).toHaveBeenCalledWith("/p/src/FooCopy.java"); + expect(edit).toHaveBeenCalledWith(4, 1, { + changes: [ + { from: 13, to: 16, insert: "FooCopy" }, + { from: 19, to: 22, insert: "FooCopy" }, + ], + }); + expect(save).toHaveBeenCalledWith(4); + expect(close).toHaveBeenCalledWith(4); + }); + + it("does not open a copy that keeps its name", async () => { + const open = vi.spyOn(commands, "docOpen"); + await renameCopiedJavaType("/p/a/Foo.java", "/p/b/Foo.java"); + expect(open).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/project-tree/javaCopy.ts b/src/features/project-tree/javaCopy.ts new file mode 100644 index 0000000000..234185f0b9 --- /dev/null +++ b/src/features/project-tree/javaCopy.ts @@ -0,0 +1,77 @@ +// IDEA's Copy Class: a copied `.java` file under a new name declares its type under that name, +// and the copy's own references to the type (constructors, `Foo.this`, `new Foo()`) follow it. +import { javaLanguage } from "@codemirror/lang-java"; +import type { SyntaxNode } from "@lezer/common"; +import { call, commands } from "@/platform/ipc"; +import { nameOf, splitExtension } from "./paths"; + +const JAVA_IDENTIFIER = /^[\p{L}_$][\p{L}\p{N}_$]*$/u; + +const TYPE_DECLARATIONS = new Set([ + "ClassDeclaration", + "InterfaceDeclaration", + "EnumDeclaration", + "RecordDeclaration", + "AnnotationTypeDeclaration", +]); + +export interface TextEdit { + from: number; + to: number; + insert: string; +} + +/** The type a copy named `to` renames, or null when the copy is not a Java type under a new name. */ +export function copiedJavaType(from: string, to: string): { oldName: string; newName: string } | null { + const [oldName, oldExt] = splitExtension(from); + const [newName, newExt] = splitExtension(to); + if (oldExt !== ".java" || newExt !== ".java" || oldName === newName) return null; + return JAVA_IDENTIFIER.test(oldName) && JAVA_IDENTIFIER.test(newName) ? { oldName, newName } : null; +} + +function isTypeDefinition(node: SyntaxNode): boolean { + const parent = node.parent; + return !!parent && (TYPE_DECLARATIONS.has(parent.name) || parent.name === "ConstructorDeclaration"); +} + +/** + * Renames the top-level type `oldName` to `newName` in `text`: its declaration, constructors and + * references, but not strings, comments or members that happen to share the name. Empty when the + * file declares no top-level type of that name. + */ +export function renameJavaTypeEdits(text: string, oldName: string, newName: string): TextEdit[] { + const tree = javaLanguage.parser.parse(text); + const declared = [...TYPE_DECLARATIONS] + .flatMap((name) => tree.topNode.getChildren(name).flatMap((d) => d.getChildren("Definition"))) + .some((d) => text.slice(d.from, d.to) === oldName); + if (!declared) return []; + const edits: TextEdit[] = []; + tree.iterate({ + enter(ref) { + if (ref.to - ref.from !== oldName.length || text.slice(ref.from, ref.to) !== oldName) return; + const node = ref.node; + const renamed = + ref.name === "TypeName" || + (ref.name === "Definition" && isTypeDefinition(node)) || + // A qualifier: `Foo.CONSTANT`, `Foo.this`, `Foo.of()`. + (ref.name === "Identifier" && /^\s*(\.|::)/.test(text.slice(ref.to, ref.to + 8))); + if (renamed) edits.push({ from: ref.from, to: ref.to, insert: newName }); + }, + }); + return edits; +} + +/** After copying `source` to `copy`, renames the copied type to the copy's name. */ +export async function renameCopiedJavaType(source: string, copy: string): Promise { + const names = copiedJavaType(nameOf(source), nameOf(copy)); + if (!names) return; + const info = await call(commands.docOpen(copy)); + try { + const edits = renameJavaTypeEdits(info.text, names.oldName, names.newName); + if (!edits.length) return; + await call(commands.docEdit(info.id, info.version, { changes: edits })); + await call(commands.docSave(info.id)); + } finally { + void commands.docClose(info.id); + } +} diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts index 8963ca13b5..68369982d2 100644 --- a/src/features/project-tree/operations.ts +++ b/src/features/project-tree/operations.ts @@ -19,6 +19,7 @@ import { osClipboard } from "./clipboard"; import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor"; import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs"; import { beginLocalImport, projectFs } from "./fs"; +import { renameCopiedJavaType } from "./javaCopy"; import { IpcError, isCancelled } from "@/platform/ipc"; import { MEMBER_PREFIX, type ProjectNode } from "./model"; import { @@ -776,7 +777,10 @@ export async function transfer( if (source === "local") { const skipped = await fs.importLocal(src, to, upload); errors.push(...skipped); - } else await fs.copy(src, to); + } else { + await fs.copy(src, to); + if (!srcIsDir) await renameCopiedJavaType(src, to).catch(() => undefined); + } taken.add(caseInsensitive ? finalName.toLowerCase() : finalName); first ??= to; } catch (e) { diff --git a/src/features/project-tree/paths.test.ts b/src/features/project-tree/paths.test.ts index 5bfee0dad5..4187414008 100644 --- a/src/features/project-tree/paths.test.ts +++ b/src/features/project-tree/paths.test.ts @@ -54,6 +54,10 @@ describe("path helpers", () => { expect(uniqueName("Bar.kt", (n) => taken.has(n))).toBe("Bar.kt"); expect(uniqueName("Foo.kt", (n) => taken.has(n))).toBe("Foo copy 2.kt"); expect(uniqueName("src", (n) => taken.has(n), true)).toBe("src copy"); + // A Java source keeps a name its public type can take (#5647). + const java = new Set(["Foo.java", "FooCopy.java"]); + expect(uniqueName("Foo.java", (n) => java.has(n))).toBe("FooCopy2.java"); + expect(uniqueName("Foo.java", (n) => n === "Foo.java")).toBe("FooCopy.java"); }); }); diff --git a/src/features/project-tree/paths.ts b/src/features/project-tree/paths.ts index 5bd05766ed..ba2686d3aa 100644 --- a/src/features/project-tree/paths.ts +++ b/src/features/project-tree/paths.ts @@ -75,12 +75,17 @@ export function splitExtension(name: string): [string, string] { return [name.slice(0, i), name.slice(i)]; } -/** Finder-style non-conflicting name: `Foo.kt` → `Foo copy.kt` → `Foo copy 2.kt`. */ +/** + * Finder-style non-conflicting name: `Foo.kt` → `Foo copy.kt` → `Foo copy 2.kt`. A Java source + * keeps a name its type can take: `Foo.java` → `FooCopy.java` → `FooCopy2.java`. + */ export function uniqueName(name: string, taken: (candidate: string) => boolean, isDir = false): string { if (!taken(name)) return name; const [stem, ext] = isDir ? [name, ""] : splitExtension(name); + const java = ext === ".java"; for (let n = 1; ; n++) { - const candidate = `${stem} copy${n > 1 ? ` ${n}` : ""}${ext}`; + const suffix = n > 1 ? (java ? `${n}` : ` ${n}`) : ""; + const candidate = java ? `${stem}Copy${suffix}${ext}` : `${stem} copy${suffix}${ext}`; if (!taken(candidate)) return candidate; } }