mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-21 08:03:38 +00:00
feat(project-tree): Reformat Code on a directory or several selected files (#3822)
The Project view only ever passed one file to code.reformatFile. A directory or a multi-selection now opens a Reformat Code dialog (Include subdirectories, Optimize imports, File mask with ! excludes, Only VCS changed text); Run reformats and saves every matching file as one cancellable background task, and a single file still reformats straight away. The batch reuses Code Cleanup's per-file step through a shared runOverFiles runner; formatDocument accepts ranges for changed text and reports noFormatter, including when the file's formatter tool is not installed, so skipped files are named in the summary. Ignored, excluded, hidden, symlinked and binary entries are skipped. Closes #3804 Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
This commit is contained in:
co-authored by
bertyhell
parent
fcc8467657
commit
55e89eac1a
@@ -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
|
||||
|
||||
@@ -52,6 +52,7 @@ description: "编辑器和问题工具窗口中的问题、快速修复与意图
|
||||
- **代码 › 检查代码…** 在指定范围内运行语言服务器的诊断,结果按严重性、检查项和文件分组显示在 **检查结果** 工具窗口中。范围可以是整个项目、某个模块或目录、当前文件、未提交的文件或自定义范围。没有语言服务器的文件会被跳过。
|
||||
- **代码 › 分析代码 › 检查当前文件** 对当前打开的文件做同样的检查。
|
||||
- **代码 › 代码清理…** 在指定范围内逐个文件应用语言服务器的自动修复、优化导入并重新格式化,然后保存。超过 100 个文件时会先确认,可以在后台任务弹窗中取消。
|
||||
- 在项目视图中对目录或多个文件执行**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`,或右键菜单)会打开**重新格式化代码**对话框:可选择包含子目录、优化导入、文件掩码(`*.sh, *.py`)和**仅 VCS 更改的文本**。文件以同样方式重新格式化并保存;没有格式化程序的文件会被跳过并在结果中列出。单个文件会直接重新格式化。
|
||||
- **代码 › 分析代码 › 查找重复代码…** 用基于词法单元(token)的克隆检测查找重复代码。可以设置以 token 计的最小长度,以及是否把标识符和字面量匿名化(这样只有名字不同的代码也能匹配)。结果显示在 **重复项** 工具窗口中。
|
||||
|
||||
## 结构化搜索与替换
|
||||
|
||||
+50
-12
@@ -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<TextEditorHandl
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The editor of `path` (opened first), else the active editor. */
|
||||
async function editorAt(path: unknown): Promise<TextEditorHandle | null> {
|
||||
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<Array<{ from: number; to: number }>> {
|
||||
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<FormatResult | null> {
|
||||
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<FormatResult | null> {
|
||||
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). */
|
||||
|
||||
@@ -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<typeof indentExtension>) =>
|
||||
@@ -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<typeof IpcError>[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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+54
-15
@@ -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<Fo
|
||||
// The server formats the backend's copy: let pending keystrokes reach it first.
|
||||
await whenSynced(view);
|
||||
const state = view.state;
|
||||
const sel = state.selection.main;
|
||||
const useSelection = (opts.selectionOnly ?? true) && !sel.empty;
|
||||
const range = useSelection ? { start: offsetToPos(state.doc, sel.from), end: offsetToPos(state.doc, sel.to) } : null;
|
||||
const targets = targetRanges(state, opts);
|
||||
if (!targets.length) return NOTHING;
|
||||
const options = formatOptionsOf(state);
|
||||
let edits;
|
||||
const formatted: Change[] = [];
|
||||
try {
|
||||
edits = await lspRequest(() =>
|
||||
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<Fo
|
||||
const tool = e.data.tool;
|
||||
if (e.kind === "notFound" && e.data.missing) {
|
||||
await executeAction("tools.promptInstall", { name: tool, sticky: !opts.onSave, formatter: true });
|
||||
// The formatter is not installed: a batch counts the file as having none.
|
||||
return { ...NOTHING, noFormatter: true };
|
||||
} else if (e.kind !== "cancelled") {
|
||||
notifications().notify({
|
||||
group: "tools",
|
||||
@@ -162,13 +199,13 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise<Fo
|
||||
});
|
||||
}
|
||||
} else reportLspError(view, e, opts.explicit);
|
||||
return NOTHING;
|
||||
return isUnavailable(e) ? { ...NOTHING, noFormatter: true } : NOTHING;
|
||||
}
|
||||
if (view.state.doc !== state.doc) {
|
||||
if (opts.explicit) showHint(view, "The file changed while formatting; try again");
|
||||
return NOTHING;
|
||||
}
|
||||
const changes = guardFormatChanges(state.doc.toString(), textEditsToChanges(state.doc, edits), guard);
|
||||
const changes = guardFormatChanges(state.doc.toString(), disjoint(formatted), guard);
|
||||
if (!changes.length) {
|
||||
if (opts.explicit) showHint(view, "No lines changed: content is already properly formatted");
|
||||
return NOTHING;
|
||||
@@ -236,13 +273,15 @@ function applyContributedFormat(
|
||||
): FormatResult {
|
||||
const state = view.state;
|
||||
if (state.readOnly) return NOTHING;
|
||||
const sel = state.selection.main;
|
||||
const useSelection = (opts.selectionOnly ?? true) && !sel.empty;
|
||||
const changes = guardFormatChanges(
|
||||
state.doc.toString(),
|
||||
format(state, useSelection ? { from: sel.from, to: sel.to } : null)
|
||||
.filter((c) => 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) {
|
||||
|
||||
@@ -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 (
|
||||
<Dialog
|
||||
open
|
||||
title="Reformat Code"
|
||||
onClose={onClose}
|
||||
width={440}
|
||||
buttons={[
|
||||
{ label: "Run", role: "default", onClick: ok },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.hint}>{subject}</div>
|
||||
{targets.some((t) => t.dir) && (
|
||||
<Checkbox
|
||||
checked={options.recursive}
|
||||
onChange={(recursive) => setOptions({ ...options, recursive })}
|
||||
label="Include subdirectories"
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
checked={options.optimizeImports}
|
||||
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
|
||||
label="Optimize imports"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={options.changedTextOnly}
|
||||
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
|
||||
label="Only VCS changed text"
|
||||
/>
|
||||
<div className={styles.fieldRow}>
|
||||
<Checkbox
|
||||
checked={options.useMask}
|
||||
onChange={(useMask) => setOptions({ ...options, useMask })}
|
||||
label="File mask:"
|
||||
/>
|
||||
<Input
|
||||
className={styles.grow}
|
||||
value={options.mask}
|
||||
disabled={!options.useMask}
|
||||
placeholder="*.sh, *.py"
|
||||
onChange={(e) => setOptions({ ...options, mask: e.target.value })}
|
||||
aria-label="File mask"
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.hint}>
|
||||
<T>Files are reformatted by their language's formatter and saved; files without one are skipped.</T>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DuplicatesDialog({ onClose }: { onClose: () => void }) {
|
||||
const [scope, setScope] = useState<ScopeChoice>(() => defaultScope());
|
||||
const [options, setOptions] = useState<DuplicateOptions>(loadDuplicateOptions);
|
||||
@@ -397,6 +471,8 @@ function ReplacePreviewDialog({
|
||||
export const showInspectCodeDialog = () => openDialog((close) => <InspectCodeDialog onClose={close} />);
|
||||
export const showDuplicatesDialog = () => openDialog((close) => <DuplicatesDialog onClose={close} />);
|
||||
export const showCodeCleanupDialog = () => openDialog((close) => <CodeCleanupDialog onClose={close} />);
|
||||
export const showReformatCodeDialog = (targets: readonly ReformatTarget[]) =>
|
||||
openDialog((close) => <ReformatCodeDialog targets={targets} onClose={close} />);
|
||||
export const showStructuralDialog = (replace: boolean) =>
|
||||
openDialog((close) => <StructuralDialog replace={replace} onClose={close} />);
|
||||
export const showReplacePreview = async (files: StructuralFile[]) => {
|
||||
|
||||
@@ -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> = {}): 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<string, FileEntry[]> = {
|
||||
"/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);
|
||||
});
|
||||
});
|
||||
@@ -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<Set<string>> {
|
||||
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<FileEntry[]>,
|
||||
accept: (path: string) => boolean,
|
||||
limit = 5000,
|
||||
{ limit = 5000, recursive = true }: { limit?: number; recursive?: boolean } = {},
|
||||
): Promise<string[]> {
|
||||
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<string[] | stri
|
||||
|
||||
let running: { cancelled: boolean } | null = null;
|
||||
|
||||
interface RunSummary {
|
||||
/** Files processed before the end or a cancel. */
|
||||
done: number;
|
||||
/** Files the reformat changed. */
|
||||
formatted: number;
|
||||
/** Files no formatter handles. */
|
||||
noFormatter: string[];
|
||||
cancelled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans `files` up one after another as one background task; `null` when another
|
||||
* run is going on or the user declined a large run.
|
||||
*/
|
||||
async function runOverFiles(
|
||||
files: readonly string[],
|
||||
task: { id: string; title: string; confirm: string; ok: string },
|
||||
options: FileCleanupOptions,
|
||||
): Promise<RunSummary | null> {
|
||||
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<void> {
|
||||
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<string>();
|
||||
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<FileEntry[]>;
|
||||
/** 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<string[]>;
|
||||
}
|
||||
|
||||
/** The files Reformat Code on `targets` (files and directories) touches, sorted. */
|
||||
export async function reformatTargets(
|
||||
targets: readonly ReformatTarget[],
|
||||
options: Pick<ReformatOptions, "recursive" | "mask" | "changedTextOnly">,
|
||||
sources: ReformatSources,
|
||||
): Promise<string[]> {
|
||||
const mask = maskMatcher(options.mask);
|
||||
const accept = (p: string) => sources.isText(p) && mask(nameOf(p));
|
||||
const found = new Set<string>();
|
||||
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<void> {
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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…",
|
||||
|
||||
@@ -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<typeof import("./cleanup")>()),
|
||||
runReformat: mocks.runReformat,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.runReformat.mockReset();
|
||||
});
|
||||
|
||||
it("runs Reformat Code on a directory with the chosen options", () => {
|
||||
render(<AnalysisDialogHost />);
|
||||
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(<AnalysisDialogHost />);
|
||||
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();
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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") && {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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}"
|
||||
}
|
||||
|
||||
@@ -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}"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user