diff --git a/docs/en/guide/inspections.mdx b/docs/en/guide/inspections.mdx index 584262983..9a71e45a6 100644 --- a/docs/en/guide/inspections.mdx +++ b/docs/en/guide/inspections.mdx @@ -52,6 +52,7 @@ These commands are in the **Code** menu: - **Code › Inspect Code…** runs the language servers' diagnostics over a scope and lists the results in the **Inspection Results** tool window, grouped by severity, inspection and file. The scope can be the whole project, a module or directory, the current file, the uncommitted files or a custom scope. Files whose language has no server are skipped. - **Code › Analyze Code › Inspect Current File** does the same for the open file. - **Code › Code Cleanup…** applies the language servers' automatic fixes, optimizes imports and reformats over a scope, file by file, and saves the files. Above 100 files it asks first. It can be cancelled from the background tasks popup. +- **Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`, or the context menu) on a directory or on several files in the Project view opens the **Reformat Code** dialog: include subdirectories, optimize imports, a file mask (`*.sh, *.py`) and **Only VCS changed text**. The files are reformatted and saved the same way; files without a formatter are skipped and listed in the result. A single file is reformatted at once. - **Code › Analyze Code › Locate Duplicates…** finds repeated code with a token-based clone detector. Set the minimum size in tokens and whether identifiers and literals are anonymized (so that code differing only in names still matches). Results open in the **Duplicates** tool window. ## Structural search and replace diff --git a/docs/zh/guide/inspections.mdx b/docs/zh/guide/inspections.mdx index 4e7c4494c..4f77f68be 100644 --- a/docs/zh/guide/inspections.mdx +++ b/docs/zh/guide/inspections.mdx @@ -52,6 +52,7 @@ description: "编辑器和问题工具窗口中的问题、快速修复与意图 - **代码 › 检查代码…** 在指定范围内运行语言服务器的诊断,结果按严重性、检查项和文件分组显示在 **检查结果** 工具窗口中。范围可以是整个项目、某个模块或目录、当前文件、未提交的文件或自定义范围。没有语言服务器的文件会被跳过。 - **代码 › 分析代码 › 检查当前文件** 对当前打开的文件做同样的检查。 - **代码 › 代码清理…** 在指定范围内逐个文件应用语言服务器的自动修复、优化导入并重新格式化,然后保存。超过 100 个文件时会先确认,可以在后台任务弹窗中取消。 +- 在项目视图中对目录或多个文件执行**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`,或右键菜单)会打开**重新格式化代码**对话框:可选择包含子目录、优化导入、文件掩码(`*.sh, *.py`)和**仅 VCS 更改的文本**。文件以同样方式重新格式化并保存;没有格式化程序的文件会被跳过并在结果中列出。单个文件会直接重新格式化。 - **代码 › 分析代码 › 查找重复代码…** 用基于词法单元(token)的克隆检测查找重复代码。可以设置以 token 计的最小长度,以及是否把标识符和字面量匿名化(这样只有名字不同的代码也能匹配)。结果显示在 **重复项** 工具窗口中。 ## 结构化搜索与替换 diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index f544d39e7..8ee367413 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -2,7 +2,8 @@ import { isGenerateAction } from "./generate"; import type { EditorView } from "@codemirror/view"; import { executeAction, registerActions, type Action } from "@/platform/actions"; -import { activeEditor, editorsFor, registerSaveParticipant, type TextEditorHandle } from "@/editor/api"; +import { activeEditor, editorsFor, registerSaveParticipant, whenSynced, type TextEditorHandle } from "@/editor/api"; +import { call, commands } from "@/platform/ipc"; import { maybeEditorService } from "@/workbench/contributions"; import { useProject } from "@/platform/project"; import { validateLanguages } from "@/platform/languageSettings"; @@ -18,7 +19,7 @@ import { docOf } from "./lsp"; import { languageSemantics } from "./semantic"; import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings"; import { startRename } from "./rename"; -import { formatDocument, reformatDialog } from "./format"; +import { formatDocument, reformatDialog, type FormatResult } from "./format"; import { showHint } from "./hint"; import { refactorThis, @@ -76,15 +77,20 @@ async function mountedEditor(path: string, frames = 60): Promise { + let ed = activeEditor(); + if (typeof path === "string" && ed?.ctx.path !== path) { + await maybeEditorService()?.openFile(path, { focus: true }); + ed = await mountedEditor(path); + } + return ed ?? null; +} + /** Runs on the file `{ path }` (opened in the editor first, as from the project view), else on the active editor. */ function inFile(run: (view: EditorView) => unknown): Action["run"] { return async ({ arg }) => { - const path = typeof arg === "string" ? arg : (arg as { path?: unknown } | undefined)?.path; - let ed = activeEditor(); - if (typeof path === "string" && ed?.ctx.path !== path) { - await maybeEditorService()?.openFile(path, { focus: true }); - ed = await mountedEditor(path); - } + const ed = await editorAt(typeof arg === "string" ? arg : (arg as { path?: unknown } | undefined)?.path); if (ed) await run(ed.view); }; } @@ -104,17 +110,49 @@ const optimizeImports = (v: EditorView) => label: "Optimize Imports", }); -interface CleanupOptions { +export interface CleanupOptions { fixAll?: boolean; optimizeImports?: boolean; reformat?: boolean; + /** Reformats only the lines changed since the last commit (IDEA's "Only VCS changed text"). */ + changedTextOnly?: boolean; } -/** Code Cleanup of one document: the server's fix-all, organize imports, then reformat. */ -async function cleanup(view: EditorView, o: CleanupOptions) { +/** The lines changed since the last commit, as document ranges; none outside version control. */ +async function vcsChangedRanges(view: EditorView): Promise> { + const path = docOf(view)?.path; + if (!path) return []; + // The hunks are computed against the backend's copy of the text. + await whenSynced(view); + let hunks; + try { + hunks = await call(commands.vcsLineHunks(path)); + } catch { + return []; + } + const doc = view.state.doc; + return hunks + .filter((h) => h.lines > 0 && h.start < doc.lines) + .map((h) => ({ from: doc.line(h.start + 1).from, to: doc.line(Math.min(h.start + h.lines, doc.lines)).to })); +} + +/** Code Cleanup of one document: the server's fix-all, organize imports, then reformat (whose result it returns). */ +async function cleanup(view: EditorView, o: CleanupOptions): Promise { if (o.fixAll !== false) await applyKindSilently(view, "source.fixAll"); if (o.optimizeImports !== false) await applyKindSilently(view, "source.organizeImports"); - if (o.reformat !== false) await formatDocument(view, { explicit: false }); + if (o.reformat === false) return null; + const ranges = o.changedTextOnly ? await vcsChangedRanges(view) : undefined; + return formatDocument(view, { explicit: false, selectionOnly: false, ranges }); +} + +/** + * Code Cleanup of the file at `path`, opened in the editor first: the batch step of + * Code Cleanup and of Reformat Code on a directory. The reformat's result, or `null` + * when the file has no text editor or reformatting was not asked for. + */ +export async function cleanupFile(path: string, o: CleanupOptions): Promise { + const ed = await editorAt(path); + return ed && ed.ctx.path === path ? cleanup(ed.view, o) : null; } /** Code action titles of Implement Methods (⌃I) and Override Methods (⌃O). */ diff --git a/src/editor/lsp/format.test.ts b/src/editor/lsp/format.test.ts index 3d5686142..9e0ff9566 100644 --- a/src/editor/lsp/format.test.ts +++ b/src/editor/lsp/format.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { EditorState, Text } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { CONTRIBUTED_FORMAT } from "@/editor/api"; @@ -12,8 +12,11 @@ import { type FormatGuardOptions, } from "@/platform/formatGuard"; import { indentExtension } from "@/editor/core/cm/setup"; +import { IpcError } from "@/platform/ipc"; +import type { TextEdit } from "@/bindings"; import { dedentsToColumnZero, formatDocument, formatOptionsOf, formattedLines } from "./format"; import { formatsOnSave } from "./actions"; +import * as lsp from "./lsp"; describe("formatOptionsOf", () => { const stateWith = (...args: Parameters) => @@ -184,3 +187,73 @@ describe("format on save provider isolation", () => { expect(formatsOnSave(null, "typescript")).toBe(false); }); }); + +describe("formatting given ranges (Only VCS changed text)", () => { + const lines = ["a = 1", "b = 2", "c = 3"]; + const viewOf = () => + new EditorView({ + state: EditorState.create({ + doc: lines.join("\n"), + extensions: [lsp.lspDoc.of({ doc: 1, path: "/p/a.py", language: "python", uiMode: null, readOnly: false })], + }), + }); + /** A server answering every request, range or not, with edits for the whole file. */ + const wholeFile = (): TextEdit[] => + lines.map((_, line) => ({ range: { start: { line, col: 1 }, end: { line, col: 3 } }, new_text: " " })); + const lineRange = (view: EditorView, n: number) => ({ + from: view.state.doc.line(n).from, + to: view.state.doc.line(n).to, + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("changes only the lines inside the ranges, one request per range", async () => { + const request = vi.spyOn(lsp, "lspRequest").mockImplementation(async () => wholeFile()); + const view = viewOf(); + try { + const ranges = [lineRange(view, 1), lineRange(view, 3)]; + expect((await formatDocument(view, { explicit: false, ranges })).applied).toBe(true); + expect(request).toHaveBeenCalledTimes(2); + expect(view.state.doc.toString()).toBe(["a = 1", "b = 2", "c = 3"].join("\n")); + } finally { + view.destroy(); + } + }); + + it("formats nothing for no ranges, as in a file without changes", async () => { + const request = vi.spyOn(lsp, "lspRequest").mockImplementation(async () => wholeFile()); + const view = viewOf(); + try { + expect((await formatDocument(view, { explicit: false, ranges: [] })).applied).toBe(false); + expect(request).not.toHaveBeenCalled(); + expect(view.state.doc.toString()).toBe(lines.join("\n")); + } finally { + view.destroy(); + } + }); + + it("tells a file without a formatter apart from one already formatted", async () => { + const view = viewOf(); + try { + vi.spyOn(lsp, "lspRequest").mockRejectedValue( + new IpcError({ kind: "unavailable", message: "No language server available" }), + ); + expect(await formatDocument(view, { explicit: false })).toMatchObject({ applied: false, noFormatter: true }); + // The file's formatter (Prettier here) is not installed. + vi.spyOn(lsp, "lspRequest").mockRejectedValue( + new IpcError({ + kind: "notFound", + message: "prettier is not installed", + data: { type: "tool", tool: "prettier", missing: true }, + } as ConstructorParameters[0]), + ); + expect(await formatDocument(view, { explicit: false })).toMatchObject({ applied: false, noFormatter: true }); + vi.spyOn(lsp, "lspRequest").mockResolvedValue([]); + expect((await formatDocument(view, { explicit: false })).noFormatter).toBeUndefined(); + } finally { + view.destroy(); + } + }); +}); diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts index 2193e1257..bb91d16e5 100644 --- a/src/editor/lsp/format.ts +++ b/src/editor/lsp/format.ts @@ -24,7 +24,7 @@ import { } from "@/platform/formatGuard"; import { useProject } from "@/platform/project"; import { CONTRIBUTED_FORMAT, contributedAt, whenSynced, type ContributedFormatter } from "@/editor/api"; -import { docOf, lspRequest, reportLspError } from "./lsp"; +import { docOf, isUnavailable, lspRequest, reportLspError } from "./lsp"; import { formatIndentFacet } from "../core/cm/setup"; import { offsetToPos, textEditsToChanges } from "./positions"; import { tx, txTemplate } from "@/platform/i18n"; @@ -37,6 +37,8 @@ export interface FormatResult { changes: number; /** Lines of the result that the changes touched. */ lines: number; + /** No formatter handles the file (no language server, or one that cannot format). */ + noFormatter?: boolean; } const NOTHING: FormatResult = { applied: false, changes: 0, lines: 0 }; @@ -96,6 +98,36 @@ interface FormatDocumentOptions { onSave?: boolean; /** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt). */ tool?: ExternalFormatter; + /** Formats only these ranges, e.g. the text changed since the last commit; an empty list formats nothing. */ + ranges?: readonly OffsetRange[]; +} + +interface OffsetRange { + from: number; + to: number; +} + +type Change = { from: number; to: number; insert: string }; + +/** `changes` inside `range` (some servers answer a range request with whole-file edits). */ +const within = (changes: readonly Change[], range: OffsetRange | null) => + range ? changes.filter((c) => c.from >= range.from && c.to <= range.to) : changes; + +/** Sorted, without changes overlapping an earlier one. */ +function disjoint(changes: readonly Change[]): Change[] { + const out: Change[] = []; + for (const c of [...changes].sort((a, b) => a.from - b.from || a.to - b.to)) { + const last = out[out.length - 1]; + if (!last || c.from >= last.to) out.push(c); + } + return out; +} + +/** The ranges to format: the given ones, else the selection (when asked for), else the whole file. */ +function targetRanges(state: EditorState, opts: FormatDocumentOptions): readonly (OffsetRange | null)[] { + if (opts.ranges) return opts.ranges; + const sel = state.selection.main; + return (opts.selectionOnly ?? true) && !sel.empty ? [{ from: sel.from, to: sel.to }] : [null]; } export async function formatDocument( @@ -126,15 +158,18 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise - commands.lspFormat(doc.doc, range, { ...options, onSave: opts.onSave, tool: opts.tool }), - ); + for (const target of targets) { + const range = target && { start: offsetToPos(state.doc, target.from), end: offsetToPos(state.doc, target.to) }; + const edits = await lspRequest(() => + commands.lspFormat(doc.doc, range, { ...options, onSave: opts.onSave, tool: opts.tool }), + ); + formatted.push(...within(textEditsToChanges(state.doc, edits), opts.ranges ? target : null)); + } } catch (e) { const formatter = e instanceof IpcError && e.data?.type === "tool" @@ -148,6 +183,8 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise state.sliceDoc(c.from, c.to) !== c.insert) - .sort((a, b) => a.from - b.from), + disjoint( + targetRanges(state, opts).flatMap((target) => + within(format(state, target), opts.ranges ? target : null).filter( + (c) => state.sliceDoc(c.from, c.to) !== c.insert, + ), + ), + ), guard, ); if (!changes.length) { diff --git a/src/features/analysis/AnalysisDialogs.tsx b/src/features/analysis/AnalysisDialogs.tsx index cd9a8ce38..c3b841ca8 100644 --- a/src/features/analysis/AnalysisDialogs.tsx +++ b/src/features/analysis/AnalysisDialogs.tsx @@ -11,12 +11,12 @@ import { } from "@/platform/ipc"; import { executeAction } from "@/platform/actions"; import { activeProfileId, listProfiles, validateInspections, type ProfileId } from "@/platform/inspections"; -import { basename, useProject } from "@/platform/project"; +import { basename, relativePath, useProject } from "@/platform/project"; import { Button, Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui"; import { ScopeFields, openDialog } from "./dialogs"; import { locateDuplicates, loadDuplicateOptions } from "./duplicates"; import { runInspection } from "./inspect"; -import { runCodeCleanup, type CleanupOptions } from "./cleanup"; +import { runCodeCleanup, runReformat, type CleanupOptions, type ReformatOptions, type ReformatTarget } from "./cleanup"; import { currentFile, defaultScope, type ScopeChoice } from "./scope"; import { applyStructuralReplace, @@ -136,6 +136,80 @@ function CodeCleanupDialog({ onClose }: { onClose: () => void }) { ); } +/** The Reformat Code dialog's last choices, remembered as IDEA does. */ +let lastReformat: ReformatOptions & { useMask: boolean } = { + recursive: true, + optimizeImports: false, + mask: "", + useMask: false, + changedTextOnly: false, +}; + +/** IDEA's Reformat Code dialog for a directory or several files of the project view. */ +function ReformatCodeDialog({ targets, onClose }: { targets: readonly ReformatTarget[]; onClose: () => void }) { + const [options, setOptions] = useState(lastReformat); + const root = useProject((s) => s.project?.root ?? ""); + const only = targets.length === 1 ? targets[0]! : null; + const subject = only ? relativePath(root, only.path) || basename(only.path) : tx`${targets.length} selected items`; + const ok = () => { + lastReformat = options; + onClose(); + const { useMask, ...run } = options; + void runReformat(targets, { ...run, mask: useMask ? run.mask : "" }); + }; + return ( + +
+
{subject}
+ {targets.some((t) => t.dir) && ( + setOptions({ ...options, recursive })} + label="Include subdirectories" + /> + )} + setOptions({ ...options, optimizeImports })} + label="Optimize imports" + /> + setOptions({ ...options, changedTextOnly })} + label="Only VCS changed text" + /> +
+ setOptions({ ...options, useMask })} + label="File mask:" + /> + setOptions({ ...options, mask: e.target.value })} + aria-label="File mask" + /> +
+
+ Files are reformatted by their language's formatter and saved; files without one are skipped. +
+
+
+ ); +} + function DuplicatesDialog({ onClose }: { onClose: () => void }) { const [scope, setScope] = useState(() => defaultScope()); const [options, setOptions] = useState(loadDuplicateOptions); @@ -397,6 +471,8 @@ function ReplacePreviewDialog({ export const showInspectCodeDialog = () => openDialog((close) => ); export const showDuplicatesDialog = () => openDialog((close) => ); export const showCodeCleanupDialog = () => openDialog((close) => ); +export const showReformatCodeDialog = (targets: readonly ReformatTarget[]) => + openDialog((close) => ); export const showStructuralDialog = (replace: boolean) => openDialog((close) => ); export const showReplacePreview = async (files: StructuralFile[]) => { diff --git a/src/features/analysis/cleanup.test.ts b/src/features/analysis/cleanup.test.ts new file mode 100644 index 000000000..5a76e052a --- /dev/null +++ b/src/features/analysis/cleanup.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from "vitest"; +import type { FileEntry } from "@/platform/ipc"; +import { maskMatcher, reformatTargets, type ReformatSources } from "./cleanup"; + +const entry = (path: string, kind: "file" | "dir" = "file", extra: Partial = {}): FileEntry => ({ + name: path.slice(path.lastIndexOf("/") + 1), + path, + kind, + size: 1, + mtimeMs: null, + ignored: false, + excluded: false, + hidden: false, + ...extra, +}); + +/** project-a/bin with Bash scripts (one without extension), a nested folder, an image and ignored output. */ +const TREE: Record = { + "/p/bin": [ + entry("/p/bin/build.sh"), + entry("/p/bin/deploy"), + entry("/p/bin/logo.png"), + entry("/p/bin/tool.py"), + entry("/p/bin/lib", "dir"), + entry("/p/bin/out", "dir", { ignored: true }), + entry("/p/bin/.cache", "dir", { hidden: true }), + ], + "/p/bin/lib": [entry("/p/bin/lib/common.sh"), entry("/p/bin/lib/vendor.min.sh")], + "/p/bin/out": [entry("/p/bin/out/gen.sh")], + "/p/bin/.cache": [entry("/p/bin/.cache/x.sh")], +}; + +const sources = (changed: string[] = []): ReformatSources => ({ + readDir: async (path) => TREE[path] ?? [], + isText: (path) => !path.endsWith(".png"), + changedFiles: async () => changed, +}); + +const all = { recursive: true, mask: "", changedTextOnly: false }; + +describe("Reformat Code on a directory or several files", () => { + it("takes every text file under a directory, skipping ignored, hidden and binary files", async () => { + expect(await reformatTargets([{ path: "/p/bin", dir: true }], all, sources())).toEqual([ + "/p/bin/build.sh", + "/p/bin/deploy", + "/p/bin/lib/common.sh", + "/p/bin/lib/vendor.min.sh", + "/p/bin/tool.py", + ]); + }); + + it("stays out of subdirectories unless Include subdirectories is on", async () => { + expect(await reformatTargets([{ path: "/p/bin", dir: true }], { ...all, recursive: false }, sources())).toEqual([ + "/p/bin/build.sh", + "/p/bin/deploy", + "/p/bin/tool.py", + ]); + }); + + it("limits the files to the file mask, for found and selected files alike", async () => { + const targets = [ + { path: "/p/bin", dir: true }, + { path: "/p/README.md", dir: false }, + ]; + expect(await reformatTargets(targets, { ...all, mask: "*.sh, !*.min.sh" }, sources())).toEqual([ + "/p/bin/build.sh", + "/p/bin/lib/common.sh", + ]); + }); + + it("takes selected files as they are and lists a file selected with its folder once", async () => { + const targets = [ + { path: "/p/bin/lib", dir: true }, + { path: "/p/bin/lib/common.sh", dir: false }, + { path: "/p/notes.custom", dir: false }, + ]; + expect(await reformatTargets(targets, all, sources())).toEqual([ + "/p/bin/lib/common.sh", + "/p/bin/lib/vendor.min.sh", + "/p/notes.custom", + ]); + }); + + it("keeps only files with uncommitted changes for Only VCS changed text", async () => { + const changed = sources(["/p/bin/deploy", "/p/bin/lib/common.sh", "/p/elsewhere.sh"]); + expect(await reformatTargets([{ path: "/p/bin", dir: true }], { ...all, changedTextOnly: true }, changed)).toEqual([ + "/p/bin/deploy", + "/p/bin/lib/common.sh", + ]); + }); +}); + +describe("file masks", () => { + it("matches names against comma-separated globs, case-insensitively, with ! excluding", () => { + const m = maskMatcher("*.sh, *.PY; !test_*"); + expect(["a.sh", "b.py", "C.SH"].every(m)).toBe(true); + expect(["a.js", "test_a.py", "sh"].some(m)).toBe(false); + expect(maskMatcher("")("anything.bin")).toBe(true); + expect(maskMatcher("!*.min.js")("app.js")).toBe(true); + expect(maskMatcher("!*.min.js")("app.min.js")).toBe(false); + expect(maskMatcher("?.c")("a.c")).toBe(true); + expect(maskMatcher("?.c")("ab.c")).toBe(false); + }); +}); diff --git a/src/features/analysis/cleanup.ts b/src/features/analysis/cleanup.ts index f6d3b691f..5031577f6 100644 --- a/src/features/analysis/cleanup.ts +++ b/src/features/analysis/cleanup.ts @@ -1,10 +1,10 @@ /** - * Code › Code Cleanup…: the language servers' fix-all, organize imports and - * reformat over a scope, one file after another (opened, cleaned, saved; tabs - * opened only for the cleanup are closed again). Cancellable from the - * Background Tasks popup. + * Code › Code Cleanup… and Reformat Code on directories or several files (project + * view): the language servers' fix-all, organize imports and reformat, one file + * after another (opened, cleaned, saved; tabs opened only for the run are closed + * again). Cancellable from the Background Tasks popup. */ -import { executeAction } from "@/platform/actions"; +import { cleanupFile, type CleanupOptions as FileCleanupOptions } from "@/editor/lsp/actions"; import { call, commands, isTauri, type FileEntry } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { maybeEditorService, notifications } from "@/workbench/contributions"; @@ -36,12 +36,12 @@ async function serverExtensions(): Promise> { return out; } -/** Files under `dir`, skipping ignored, excluded and hidden entries and symlinks. */ +/** Files under `dir` (or only in it, unless `recursive`), skipping ignored, excluded and hidden entries and symlinks. */ export async function walkFiles( dir: string, readDir: (path: string) => Promise, accept: (path: string) => boolean, - limit = 5000, + { limit = 5000, recursive = true }: { limit?: number; recursive?: boolean } = {}, ): Promise { const out: string[] = []; const queue = [dir]; @@ -54,8 +54,9 @@ export async function walkFiles( } for (const e of entries) { if (e.ignored || e.excluded || e.hidden || e.kind === "symlink") continue; - if (e.kind === "dir") queue.push(e.path); - else if (accept(e.path)) out.push(e.path); + if (e.kind === "dir") { + if (recursive) queue.push(e.path); + } else if (accept(e.path)) out.push(e.path); } } return out.sort(); @@ -89,6 +90,63 @@ export async function cleanupFiles(choice: ScopeChoice): Promise { + if (running) return null; + if (files.length > CONFIRM_ABOVE && !(await confirm({ title: task.title, message: task.confirm, ok: task.ok }))) + return null; + const editors = maybeEditorService(); + const wasOpen = new Set(editors?.openPaths?.() ?? []); + const run: { cancelled: boolean } = { cancelled: false }; + running = run; + const summary: RunSummary = { done: 0, formatted: 0, noFormatter: [], cancelled: false }; + try { + for (const path of files) { + if (run.cancelled) break; + upsertTask({ + id: task.id, + title: task.title, + message: nameOf(path), + fraction: summary.done / files.length, + done: false, + cancel: () => (run.cancelled = true), + }); + const result = await cleanupFile(path, options); + if (result?.applied) summary.formatted++; + if (result?.noFormatter) summary.noFormatter.push(path); + await editors?.saveAll(); + if (!wasOpen.has(path) && (await editors?.closePath?.(path)) === false) { + run.cancelled = true; + break; + } + summary.done++; + } + } finally { + running = null; + upsertTask({ id: task.id, title: task.title, message: null, fraction: 1, done: true }); + if (run.cancelled) removeTask(task.id); + } + summary.cancelled = run.cancelled; + return summary; +} + export async function runCodeCleanup(choice: ScopeChoice, options: CleanupOptions): Promise { if (!isTauri() || running) return; const files = await cleanupFiles(choice); @@ -102,47 +160,163 @@ export async function runCodeCleanup(choice: ScopeChoice, options: CleanupOption }); return; } - if ( - files.length > CONFIRM_ABOVE && - !(await confirm({ title: "Code Cleanup", message: tx`Clean up ${files.length} files?`, ok: "Clean Up" })) - ) - return; - const editors = maybeEditorService(); - const wasOpen = new Set(editors?.openPaths?.() ?? []); - const run: { cancelled: boolean } = { cancelled: false }; - running = run; - const id = "code.cleanup"; - let done = 0; - try { - for (const path of files) { - if (run.cancelled) break; - upsertTask({ - id, - title: "Code Cleanup", - message: path.slice(path.lastIndexOf("/") + 1), - fraction: done / files.length, - done: false, - cancel: () => (run.cancelled = true), - }); - await executeAction("code.cleanupFile", { path, ...options }); - await editors?.saveAll(); - if (!wasOpen.has(path) && (await editors?.closePath?.(path)) === false) { - run.cancelled = true; - break; - } - done++; - } - } finally { - running = null; - upsertTask({ id, title: "Code Cleanup", message: null, fraction: 1, done: true }); - if (run.cancelled) removeTask(id); - } + const summary = await runOverFiles( + files, + { id: "code.cleanup", title: "Code Cleanup", confirm: tx`Clean up ${files.length} files?`, ok: "Clean Up" }, + options, + ); + if (!summary) return; + const { done, cancelled } = summary; notifications().notify({ group: "analysis", level: "info", - title: run.cancelled + title: cancelled ? `Code Cleanup cancelled after ${done} of ${files.length} files` : `Code Cleanup processed ${done} files`, key: "code.cleanup", }); } + +// --------------------------------------------------------------------------- +// Reformat Code on directories or several files + +export interface ReformatOptions { + /** Include the files in subdirectories of the chosen directories. */ + recursive: boolean; + optimizeImports: boolean; + /** File name masks (`*.sh, *.py`; `!` excludes); empty for every file. */ + mask: string; + /** Only the lines changed since the last commit, in files with uncommitted changes. */ + changedTextOnly: boolean; +} + +export interface ReformatTarget { + path: string; + dir: boolean; +} + +const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1); + +function maskRegExp(glob: string): RegExp { + const re = glob + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + return new RegExp(`^${re}$`, "i"); +} + +/** Whether a file name matches the comma-separated `mask` (`*.sh, *.py`, `!*.min.js`); an empty mask matches every name. */ +export function maskMatcher(mask: string): (name: string) => boolean { + const globs = mask + .split(/[,;]/) + .map((g) => g.trim()) + .filter(Boolean); + const include = globs.filter((g) => !g.startsWith("!")).map(maskRegExp); + const exclude = globs.filter((g) => g.startsWith("!")).map((g) => maskRegExp(g.slice(1).trim())); + return (name) => (!include.length || include.some((re) => re.test(name))) && !exclude.some((re) => re.test(name)); +} + +/** + * Whether a file found in a directory is text the IDE knows: an extension or file + * name of a language, or no extension at all (scripts recognised by their shebang). + * Anything else (images, archives…) is skipped as binary or data. + */ +async function knownTextFile(): Promise<(path: string) => boolean> { + const extensions = new Set(); + const names: RegExp[] = []; + for (const l of await commands.languages()) { + for (const e of l.extensions) extensions.add(e.replace(/^\./, "").toLowerCase()); + for (const f of l.filenames ?? []) names.push(maskRegExp(f)); + } + return (path) => { + const ext = extOf(path); + return !ext || extensions.has(ext) || names.some((re) => re.test(nameOf(path))); + }; +} + +export interface ReformatSources { + readDir: (path: string) => Promise; + /** Whether a file found in a directory is text to reformat (selected files always are). */ + isText: (path: string) => boolean; + /** Files with uncommitted changes. */ + changedFiles: () => Promise; +} + +/** The files Reformat Code on `targets` (files and directories) touches, sorted. */ +export async function reformatTargets( + targets: readonly ReformatTarget[], + options: Pick, + sources: ReformatSources, +): Promise { + const mask = maskMatcher(options.mask); + const accept = (p: string) => sources.isText(p) && mask(nameOf(p)); + const found = new Set(); + for (const t of targets) { + if (!t.dir) { + if (mask(nameOf(t.path))) found.add(t.path); + continue; + } + for (const p of await walkFiles(t.path, sources.readDir, accept, { recursive: options.recursive })) found.add(p); + } + if (options.changedTextOnly) { + const changed = new Set(await sources.changedFiles()); + for (const p of found) if (!changed.has(p)) found.delete(p); + } + return [...found].sort(); +} + +/** Reformat Code on directories or several files, as from the project view (⌥⌘L). */ +export async function runReformat(targets: readonly ReformatTarget[], options: ReformatOptions): Promise { + if (!isTauri() || running) return; + const key = "code.reformatFiles"; + let files: string[]; + try { + files = await reformatTargets(targets, options, { + readDir: (p) => call(commands.fsReadDir(p)), + isText: await knownTextFile(), + changedFiles, + }); + } catch (e) { + notifications().notify({ + group: "analysis", + level: "warning", + title: "Reformat Code", + body: e instanceof Error ? e.message : String(e), + key, + }); + return; + } + if (!files.length) { + notifications().notify({ + group: "analysis", + level: "info", + title: "Reformat Code", + body: options.changedTextOnly ? "No changed files to reformat" : "No files to reformat", + key, + }); + return; + } + const summary = await runOverFiles( + files, + { id: key, title: "Reformat Code", confirm: tx`Reformat ${files.length} files?`, ok: "Reformat" }, + { + fixAll: false, + optimizeImports: options.optimizeImports, + reformat: true, + changedTextOnly: options.changedTextOnly, + }, + ); + if (!summary) return; + const { done, formatted, noFormatter, cancelled } = summary; + const count = noFormatter.length; + const names = noFormatter.slice(0, 5).map(nameOf).join(", ") + (count > 5 ? ", …" : ""); + notifications().notify({ + group: "analysis", + level: "info", + title: cancelled + ? `Reformat Code cancelled after ${done} of ${files.length} files` + : `Reformatted ${formatted} of ${files.length} files`, + body: count ? tx`Skipped ${count} files without a formatter: ${names}` : undefined, + key, + }); +} diff --git a/src/features/analysis/index.ts b/src/features/analysis/index.ts index a10e01b40..0a1c7d73f 100644 --- a/src/features/analysis/index.ts +++ b/src/features/analysis/index.ts @@ -11,6 +11,7 @@ import { showCodeCleanupDialog, showDuplicatesDialog, showInspectCodeDialog, + showReformatCodeDialog, showStructuralDialog, } from "./AnalysisDialogs"; import { AnalysisDialogHost } from "./dialogs"; @@ -80,6 +81,23 @@ export function activate(): () => void { keywords: ["fix all", "cleanup", "organize imports", "reformat"], run: () => void showCodeCleanupDialog(), }, + { + id: "code.reformatFiles", + title: "Reformat Code…", + description: "Reformat Code dialog for `{ files?, directories? }`, as for a project view selection.", + category: "Code", + hidden: true, + when: "projectOpen", + run: ({ arg }) => { + const a = (arg ?? {}) as { files?: unknown; directories?: unknown }; + const paths = (v: unknown) => (Array.isArray(v) ? v.filter((p): p is string => typeof p === "string") : []); + const targets = [ + ...paths(a.directories).map((path) => ({ path, dir: true })), + ...paths(a.files).map((path) => ({ path, dir: false })), + ]; + if (targets.length) showReformatCodeDialog(targets); + }, + }, { id: "analyze.locateDuplicates", title: "Locate Duplicates…", diff --git a/src/features/analysis/reformatDialog.test.tsx b/src/features/analysis/reformatDialog.test.tsx new file mode 100644 index 000000000..97105f5cd --- /dev/null +++ b/src/features/analysis/reformatDialog.test.tsx @@ -0,0 +1,47 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { AnalysisDialogHost } from "./dialogs"; +import { showReformatCodeDialog } from "./AnalysisDialogs"; + +const mocks = vi.hoisted(() => ({ runReformat: vi.fn() })); +vi.mock("./cleanup", async (original) => ({ + ...(await original()), + runReformat: mocks.runReformat, +})); + +afterEach(() => { + cleanup(); + mocks.runReformat.mockReset(); +}); + +it("runs Reformat Code on a directory with the chosen options", () => { + render(); + act(() => void showReformatCodeDialog([{ path: "/p/bin", dir: true }])); + expect(screen.getByRole("checkbox", { name: "Include subdirectories" })).toBeChecked(); + const mask = screen.getByRole("textbox", { name: "File mask" }); + expect(mask).toBeDisabled(); + fireEvent.click(screen.getByRole("checkbox", { name: "File mask:" })); + fireEvent.change(mask, { target: { value: "*.sh" } }); + fireEvent.click(screen.getByRole("checkbox", { name: "Include subdirectories" })); + fireEvent.click(screen.getByRole("button", { name: "Run" })); + expect(mocks.runReformat).toHaveBeenCalledWith([{ path: "/p/bin", dir: true }], { + recursive: false, + optimizeImports: false, + mask: "*.sh", + changedTextOnly: false, + }); + expect(screen.queryByRole("dialog")).toBeNull(); +}); + +it("offers Include subdirectories only when a directory is chosen", () => { + render(); + act( + () => + void showReformatCodeDialog([ + { path: "/p/a.sh", dir: false }, + { path: "/p/b.sh", dir: false }, + ]), + ); + expect(screen.queryByRole("checkbox", { name: "Include subdirectories" })).toBeNull(); + expect(screen.getByText("2 selected items")).toBeTruthy(); +}); diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index 4b682caa3..ed2279598 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -26,6 +26,7 @@ import { openSelection, openSelectionInRightSplit, paste, + reformatNodes, reloadFromDisk, revealInFinder, selectedFiles, @@ -456,14 +457,11 @@ export function registerProjectActions(): () => void { }, { id: "project.reformatCode", - title: "Reformat File", + title: "Reformat Code", category: "Project View", hidden: true, when: FOCUS, - run: ({ arg }) => { - const node = nodesFrom(arg)[0]; - if (node && !node.dir) delegate("code.reformatFile", { path: node.path }); - }, + run: ({ arg }) => void reformatNodes(nodesFrom(arg)), }, { id: "project.optimizeImports", diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts index ae6b80661..82a02be8f 100644 --- a/src/features/project-tree/contextMenu.test.ts +++ b/src/features/project-tree/contextMenu.test.ts @@ -251,10 +251,39 @@ describe("project view context menu", () => { const l = labels(contextMenuItems([node(`${ROOT}/src`, true)])); expect(l).toContain("Mark Directory as"); expect(sub(contextMenuItems([node(`${ROOT}/src`, true)]), "Refactor")).toContain("Move Directory…"); - for (const fileOnly of ["Find Usages", "Reformat Code", "Optimize Imports", "Run 'a'", "Open in Right Split"]) + for (const fileOnly of ["Find Usages", "Optimize Imports", "Run 'a'", "Open in Right Split"]) expect(l).not.toContain(fileOnly); }); + it("offers Reformat Code for a directory and a multiple selection, through the Reformat Code dialog", () => { + const calls: Array<[string, unknown]> = []; + disposers.push( + registerActions( + ["code.reformatFile", "code.reformatFiles"].map((id) => ({ + id, + title: id, + run: ({ arg }) => void calls.push([id, arg]), + })), + ), + ); + const reformat = (nodes: ProjectNode[]) => { + const item = resolveMenuItems(contextMenuItems(nodes)).find((r) => r.label === "Reformat Code"); + item?.run?.(); + return calls.pop(); + }; + expect(reformat([node("/p/a.py")])).toEqual(["code.reformatFile", { path: "/p/a.py" }]); + expect(reformat([node("/p/bin", true)])).toEqual(["code.reformatFiles", { files: [], directories: ["/p/bin"] }]); + expect(reformat([node("/p/a.sh"), node("/p/b.sh")])).toEqual([ + "code.reformatFiles", + { files: ["/p/a.sh", "/p/b.sh"], directories: [] }, + ]); + expect(reformat([node("/p/a.sh"), node("/p/lib", true)])).toEqual([ + "code.reformatFiles", + { files: ["/p/a.sh"], directories: ["/p/lib"] }, + ]); + expect(reformat([node(ROOT, true, true)])).toEqual(["code.reformatFiles", { files: [], directories: [ROOT] }]); + }); + it("offers Import Module from Existing Sources on the project root only", () => { const off = registerActions([ { id: "maven.importExternal", title: "Import Module from Existing Sources", run: () => undefined }, diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts index c669948a5..027c1abb1 100644 --- a/src/features/project-tree/contextMenu.ts +++ b/src/features/project-tree/contextMenu.ts @@ -28,6 +28,7 @@ import { openRenameDialog, openSelectionInRightSplit, paste, + reformatNodes, reloadFromDisk, revealInFinder, vcsArg, @@ -301,14 +302,14 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] { { kind: "separator" }, ); - // Reformat Code / Optimize Imports / Delete… + // Reformat Code (one file at once, directories or several files through its dialog) / Optimize Imports / Delete… push( - singleFile && - getAction("code.reformatFile") && { + nodes.some((n) => !n.group) && + getAction(singleFile ? "code.reformatFile" : "code.reformatFiles") && { id: "reformat", label: "Reformat Code", shortcut: keyLabel("project.reformatCode"), - run: () => void delegate("code.reformatFile", { path: singleFile.path }), + run: () => void reformatNodes(nodes), }, singleFile && getAction("code.optimizeImportsFile") && { diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts index 18fb5d97d..d1485c860 100644 --- a/src/features/project-tree/operations.ts +++ b/src/features/project-tree/operations.ts @@ -916,6 +916,20 @@ export function delegate(id: string, arg: unknown): boolean { return true; } +/** + * Reformat Code (⌥⌘L) for project view nodes: a single file is reformatted at once, + * a directory or several nodes open the Reformat Code dialog. False when nothing applies. + */ +export function reformatNodes(nodes: readonly ProjectNode[]): boolean { + const targets = nodes.filter((n) => !n.group && !n.readOnly); + if (!targets.length) return false; + if (targets.length === 1 && !targets[0]!.dir) return delegate("code.reformatFile", { path: targets[0]!.path }); + return delegate("code.reformatFiles", { + files: targets.filter((n) => !n.dir).map((n) => n.path), + directories: targets.filter((n) => n.dir).map((n) => n.path), + }); +} + /** Argument for VCS actions: one path or several. */ export function vcsArg(nodes: ProjectNode[] = selectedNodes()): string | string[] { const paths = nodes.map((n) => n.path); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 8d2baf796..3e7b2a38d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2303,5 +2303,17 @@ "Hide Code Author": "Hide Code Author", "Hide Code Vision": "Hide Code Vision", "Code Vision Settings…": "Code Vision Settings…", - "Code Vision": "Code Vision" + "Code Vision": "Code Vision", + "Reformat Code…": "Reformat Code…", + "Reformat Code dialog for `{ files?, directories? }`, as for a project view selection.": "Reformat Code dialog for `{ files?, directories? }`, as for a project view selection.", + "{length} selected items": "{length} selected items", + "Include subdirectories": "Include subdirectories", + "Only VCS changed text": "Only VCS changed text", + "Files are reformatted by their language's formatter and saved; files without one are skipped.": "Files are reformatted by their language's formatter and saved; files without one are skipped.", + "No changed files to reformat": "No changed files to reformat", + "No files to reformat": "No files to reformat", + "Reformat {length} files?": "Reformat {length} files?", + "Reformat Code cancelled after {done} of {length} files": "Reformat Code cancelled after {done} of {length} files", + "Reformatted {formatted} of {length} files": "Reformatted {formatted} of {length} files", + "Skipped {count} files without a formatter: {names}": "Skipped {count} files without a formatter: {names}" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 3d6e6d333..77dcbb226 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8687,5 +8687,17 @@ "Hide Code Author": "隐藏代码作者", "Hide Code Vision": "隐藏 Code Vision", "Code Vision Settings…": "Code Vision 设置…", - "Code Vision": "Code Vision" + "Code Vision": "Code Vision", + "Reformat Code…": "重新格式化代码…", + "Reformat Code dialog for `{ files?, directories? }`, as for a project view selection.": "为 `{ files?, directories? }` 打开“重新格式化代码”对话框,与在项目视图中选择时相同。", + "{length} selected items": "已选择 {length} 项", + "Include subdirectories": "包含子目录", + "Only VCS changed text": "仅 VCS 更改的文本", + "Files are reformatted by their language's formatter and saved; files without one are skipped.": "文件由各自语言的格式化程序重新格式化并保存;没有格式化程序的文件将被跳过。", + "No changed files to reformat": "没有需要重新格式化的已更改文件", + "No files to reformat": "没有需要重新格式化的文件", + "Reformat {length} files?": "是否重新格式化 {length} 个文件?", + "Reformat Code cancelled after {done} of {length} files": "重新格式化代码已在处理 {done}/{length} 个文件后取消", + "Reformatted {formatted} of {length} files": "已重新格式化 {formatted}/{length} 个文件", + "Skipped {count} files without a formatter: {names}": "已跳过 {count} 个没有格式化程序的文件:{names}" }