diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index b28e82be37..0d762a1d93 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -522,7 +522,7 @@ impl SettingsStore { pub struct JetBrainsSettings { pub entries: Vec, /// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`, - /// `codestyles/*.xml`, `templates/*.xml` and some of `options/`. + /// `codestyles/*.xml`, `templates/*.xml`, `inspection/*.xml` and some of `options/`. pub files: BTreeMap, } @@ -540,8 +540,13 @@ const JETBRAINS_OPTIONS: [&str; 9] = [ "options/linux/keymap.xml", ]; /// Folders whose files are all read: (folder, extension). -const JETBRAINS_READ_DIRS: [(&str, &str); 4] = - [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml"), ("templates/", ".xml")]; +const JETBRAINS_READ_DIRS: [(&str, &str); 5] = [ + ("colors/", ".icls"), + ("keymaps/", ".xml"), + ("codestyles/", ".xml"), + ("templates/", ".xml"), + ("inspection/", ".xml"), +]; const JETBRAINS_MAX_TEXT: u64 = 4 << 20; /// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder @@ -1151,17 +1156,19 @@ mod tests { ("templates/Python.xml", ""), ("templates/nested/ignored.xml", ""), ("templates/ignored.txt", "not XML"), + ("inspection/Strict.xml", ""), ("options/mac/keymap.xml", ""), ("options/terminal-font.xml", ""), ], ); let read = read_jetbrains_settings(&ok).unwrap(); - assert_eq!(read.entries.len(), 12); + assert_eq!(read.entries.len(), 13); assert_eq!( read.files.keys().collect::>(), [ "codestyles/Default.xml", "colors/_@user_Darcula.icls", + "inspection/Strict.xml", "keymaps/macOS.xml", "options/editor-font.xml", "options/mac/keymap.xml", @@ -1192,6 +1199,7 @@ mod tests { put("codestyles/Default.xml", ""); put("templates/Python.xml", ""); put("templates/nested/ignored.xml", ""); + put("inspection/Strict.xml", ""); put("plugins/Tools/lib/tools.jar", "jar"); let read = read_jetbrains_settings(&config).unwrap(); @@ -1200,6 +1208,7 @@ mod tests { [ "codestyles/Default.xml", "colors/_@user_Darcula.icls", + "inspection/Strict.xml", "keymaps/macOS.xml", "options/editor-font.xml", "options/mac/keymap.xml", @@ -1216,6 +1225,7 @@ mod tests { "keymaps/macOS.xml", "codestyles/Default.xml", "templates/Python.xml", + "inspection/Strict.xml", "installed.txt" ] ); diff --git a/src/bindings.ts b/src/bindings.ts index 8541c19e15..ac7dcd7a46 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9358,7 +9358,7 @@ export type JetBrainsSettings = { entries: string[], /** * Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`, - * `codestyles/*.xml`, `templates/*.xml` and some of `options/`. + * `codestyles/*.xml`, `templates/*.xml`, `inspection/*.xml` and some of `options/`. */ files: { [key in string]: string }, }; diff --git a/src/features/app/__tests__/jetbrainsInspections.test.ts b/src/features/app/__tests__/jetbrainsInspections.test.ts new file mode 100644 index 0000000000..405d3b9657 --- /dev/null +++ b/src/features/app/__tests__/jetbrainsInspections.test.ts @@ -0,0 +1,76 @@ +import { expect, it } from "vitest"; +import { parseJetBrainsInspections } from "../jetbrainsInspections"; + +const strict = + '' + + '"; + +it("turns a named profile into an IDE-level copy, and lists what has no counterpart", () => { + const result = parseJetBrainsInspections({ "inspection/Strict.xml": strict, "inspection/bad.xml": " { + const current = { + default: { "builtin:sql": { enabled: false }, "builtin:spelling": { enabled: true } }, + ideProfiles: { strict: { name: "Strict", overrides: { "builtin:sql": { enabled: false } } } }, + }; + const def = + ''; + const result = parseJetBrainsInspections({ "inspection/Default.xml": def, "inspection/Strict.xml": strict }, current); + expect(result.profiles.map((p) => [p.name, p.replaces])).toEqual([ + ["Default", undefined], + ["Strict", true], + ]); + const writes = Object.fromEntries(result.writes); + expect(writes["inspections.default"]).toEqual({ + "builtin:sql": { enabled: false }, + "builtin:spelling": { enabled: false, severity: "typo" }, + }); + const customs = writes["inspections.ideProfiles"] as Record; + expect(Object.keys(customs)).toEqual(["strict"]); + expect(customs.strict!.overrides).not.toHaveProperty("builtin:sql"); +}); diff --git a/src/features/app/__tests__/jetbrainsSettings.test.ts b/src/features/app/__tests__/jetbrainsSettings.test.ts index c8dd3d8a54..023e79e9f7 100644 --- a/src/features/app/__tests__/jetbrainsSettings.test.ts +++ b/src/features/app/__tests__/jetbrainsSettings.test.ts @@ -54,6 +54,11 @@ const webstorm = { showTipsOnStartup: "false", confirmExit: "false", }), + "inspection/Default.xml": + '", }, }; @@ -79,6 +84,7 @@ describe("planJetBrainsImport", () => { "editor.softWrap": false, "console.softWrap": true, "general.confirmExit": false, + "inspections.default": { "builtin:spelling": { enabled: false, severity: "typo" } }, }); expect(plan.rows).toContainEqual({ label: "Color Scheme", @@ -89,7 +95,9 @@ describe("planJetBrainsImport", () => { label: "Remove trailing spaces on:", value: "All lines", }); - expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents", "Inspections", "Plugins"]); + expect(plan.rows).toContainEqual({ label: "Inspection profile", value: "Default (inspections: 1)" }); + expect(plan.unmappedInspections).toEqual(["JSUnusedLocalSymbols"]); + expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents", "Plugins"]); expect(plan.invalid).toEqual([]); }); diff --git a/src/features/app/__tests__/jetbrainsSettingsImport.test.tsx b/src/features/app/__tests__/jetbrainsSettingsImport.test.tsx index 7d0f7d93c3..973e71f6e2 100644 --- a/src/features/app/__tests__/jetbrainsSettingsImport.test.tsx +++ b/src/features/app/__tests__/jetbrainsSettingsImport.test.tsx @@ -85,3 +85,34 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Settings imported" })); } }); + +it("offers an imported inspection profile for the open project", async () => { + const { useProject } = await import("@/platform/project"); + useProject.setState({ project: { root: "/p", name: "p" } as never }); + read.mockResolvedValue({ + status: "ok", + data: { + entries: ["inspection/Strict.xml"], + files: { + "inspection/Strict.xml": + '", + }, + }, + }); + render(); + let done!: Promise; + await act(async () => { + done = importJetBrainsSettings("/settings.zip"); + }); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await done; + }); + const offer = notify.mock.calls.map(([n]) => n).find((n) => n.key === "app.settingsImport.inspections"); + expect(offer.actions.map((a: { label: string }) => a.label)).toEqual(["Use Strict"]); + await act(async () => offer.actions[0].run()); + expect(set).toHaveBeenLastCalledWith("project", "inspections.profile", '"ide:strict"'); + useProject.setState({ project: null }); +}); diff --git a/src/features/app/jetbrainsInspections.ts b/src/features/app/jetbrainsInspections.ts new file mode 100644 index 0000000000..f902656896 --- /dev/null +++ b/src/features/app/jetbrainsInspections.ts @@ -0,0 +1,149 @@ +/** + * JetBrains inspection profiles (`inspection/*.xml`) → OpenIDEA's. `Default` updates the + * `Default` profile; any other profile becomes an IDE-level copy of the same name. Only + * inspections OpenIDEA has a counterpart for are carried over; the rest are listed. + */ +import { + BUILTIN_INSPECTIONS, + customProfileId, + CUCUMBER_UNDEFINED_STEP_INSPECTION, + JAVA_SERIAL_VERSION_INSPECTION, + PYTHON_REQUIREMENTS_INSPECTION, + SPELLING_INSPECTION, + SPELLING_OPTIONS, + newProfileKey, + validateInspections, + type CustomProfiles, + type InspectionLevel, + type InspectionOverride, +} from "@/platform/inspections"; + +/** JetBrains inspection short name → OpenIDEA inspection id. */ +const BY_SHORT_NAME = new Map([ + ["SpellCheckingInspection", SPELLING_INSPECTION], + ["PyPackageRequirementsInspection", PYTHON_REQUIREMENTS_INSPECTION], + ["SerializableHasSerialVersionUIDField", JAVA_SERIAL_VERSION_INSPECTION], + ["CucumberUndefinedStep", CUCUMBER_UNDEFINED_STEP_INSPECTION], + // PyCharm's short names are the `# noinspection` id plus "Inspection". + ...BUILTIN_INSPECTIONS.flatMap((b) => (b.suppressId ? [[`${b.suppressId}Inspection`, b.id] as const] : [])), +]); + +/** pycodestyle and pep8-naming codes PyCharm ignores; Ruff and pylsp report them under the same codes. */ +const CODE_LISTS = new Set(["PyPep8Inspection", "PyPep8NamingInspection"]); +const CODE_SERVERS = ["lsp:ruff", "lsp:pylsp"]; + +const LEVELS: Record = { + ERROR: "error", + WARNING: "warning", + "WEAK WARNING": "weakWarning", + "SERVER PROBLEM": "serverProblem", + TYPO: "typo", + INFORMATION: "none", + INFO: "none", + "TEXT ATTRIBUTES": "none", +}; + +const SPELLING_KEYS = new Set(Object.values(SPELLING_OPTIONS)); + +export interface JetBrainsInspectionsImport { + /** Writes to the global layer: `inspections.default` and/or `inspections.ideProfiles`. */ + writes: [key: string, value: unknown][]; + /** + * Profile name → inspections carried over; `id` of a named profile (`ide:`), and + * whether it replaces an IDE profile of the same name. + */ + profiles: { name: string; count: number; id?: string; replaces?: boolean }[]; + /** Inspections (and parts of them) with no counterpart here. */ + unmapped: string[]; + invalid: string[]; +} + +const attr = (el: Element, name: string) => el.getAttribute(name) ?? undefined; + +/** Adds the tool's overrides to `out`; whether anything of it was carried over. */ +function parseTool(tool: Element, out: Record, unmapped: Set): boolean { + const name = attr(tool, "class"); + if (!name) return false; + for (const scope of Array.from(tool.children).filter((c) => c.tagName === "scope")) + unmapped.add(`${name} (${attr(scope, "name") ?? "scope"})`); + // With scopes, `enabled_by_default` is "everywhere else"; without, it equals `enabled`. + const on = attr(tool, "enabled_by_default") ?? attr(tool, "enabled"); + const enabled = on === undefined ? undefined : on === "true"; + const level = attr(tool, "level"); + const severity = LEVELS[level ?? ""]; + // A severity defined in the JetBrains IDE (Settings › Editor › Inspections › Severities). + if (level && !severity) unmapped.add(`${name} (${level})`); + const options = Array.from(tool.children).filter((c) => c.tagName === "option"); + + if (CODE_LISTS.has(name)) { + const list = options.find((o) => attr(o, "name") === "ignoredErrors"); + const codes = Array.from(list?.querySelectorAll("list > option") ?? []).map((o) => attr(o, "value") ?? ""); + let mapped = false; + for (const code of codes) { + if (!/^[EWN]\d{3}$/.test(code)) { + unmapped.add(`${name}: ${code}`); + continue; + } + for (const server of CODE_SERVERS) out[`${server}:${code}`] = { enabled: false }; + mapped = true; + } + if (enabled === false) unmapped.add(name); + return mapped; + } + + const id = BY_SHORT_NAME.get(name); + if (!id) { + unmapped.add(name); + return false; + } + const entry: InspectionOverride = {}; + if (enabled !== undefined) entry.enabled = enabled; + if (severity) entry.severity = severity; + if (id === SPELLING_INSPECTION) { + const flags = options.filter((o) => SPELLING_KEYS.has(attr(o, "name") ?? "") && attr(o, "value") !== undefined); + if (flags.length) + entry.options = Object.fromEntries(flags.map((o) => [attr(o, "name"), attr(o, "value") === "true"])); + } + if (!Object.keys(entry).length) return false; + out[id] = entry; + return true; +} + +/** `files`: the bundle's `inspection/*.xml`; `current`: the global `inspections` setting. */ +export function parseJetBrainsInspections(files: Record, current: unknown): JetBrainsInspectionsImport { + const settings = validateInspections(current); + let defaults = settings.default; + let customs: CustomProfiles = settings.ideProfiles; + const result: JetBrainsInspectionsImport = { writes: [], profiles: [], unmapped: [], invalid: [] }; + const unmapped = new Set(); + for (const [file, text] of Object.entries(files)) { + const doc = new DOMParser().parseFromString(text, "application/xml"); + // App-level files are a bare ; project ones wrap it in a . + const profile = doc.querySelector("parsererror") ? null : doc.querySelector("profile"); + if (!profile) { + result.invalid.push(file.slice(file.lastIndexOf("/") + 1)); + continue; + } + const named = Array.from(profile.children).find((c) => c.tagName === "option" && attr(c, "name") === "myName"); + const name = (named && attr(named, "value")?.trim()) || file.replace(/^.*\/|\.xml$/g, ""); + const overrides: Record = {}; + let count = 0; + for (const tool of Array.from(profile.children)) + if (tool.tagName === "inspection_tool" && parseTool(tool, overrides, unmapped)) count++; + if (name === "Default") { + defaults = { ...defaults, ...overrides }; + result.profiles.push({ name, count }); + } else { + // Replaces an earlier import of the same profile instead of adding a second one. + const existing = Object.entries(customs).find(([, p]) => p.name === name)?.[0]; + const key = existing ?? newProfileKey(name, customs); + customs = { ...customs, [key]: { name, overrides } }; + const replaces = !!existing && !!settings.ideProfiles[existing]; + result.profiles.push({ name, count, id: customProfileId("ide", key), replaces }); + } + } + if (defaults !== settings.default) result.writes.push(["inspections.default", defaults]); + if (customs !== settings.ideProfiles) result.writes.push(["inspections.ideProfiles", customs]); + result.unmapped = [...unmapped]; + return result; +} diff --git a/src/features/app/jetbrainsSettings.tsx b/src/features/app/jetbrainsSettings.tsx index e281534e3c..71f047f8a0 100644 --- a/src/features/app/jetbrainsSettings.tsx +++ b/src/features/app/jetbrainsSettings.tsx @@ -1,6 +1,6 @@ /** * Import Settings… with a JetBrains `settings.zip`: maps the archive's colour - * schemes, keymaps, fonts, tabs and indents, live templates, and the editor / + * schemes, keymaps, fonts, tabs and indents, live templates, inspection profiles, and the editor / * general options OpenIDEA has to settings writes, after a confirmation listing * them. Only keys present in the archive are written (JetBrains leaves defaults * out). The rest is listed as not imported. @@ -20,6 +20,7 @@ import { ask } from "@/workbench/messages"; import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains"; import { saveImportedTemplates } from "@/features/templates/live/store"; import styles from "./app.module.css"; +import { parseJetBrainsInspections } from "./jetbrainsInspections"; import { CODE_INSIGHT_FLAGS, CODE_INSIGHT_NUMBERS, @@ -41,6 +42,10 @@ export interface JetBrainsImportPlan { invalid: string[]; /** IDEA action ids the imported keymaps bind that have no counterpart here. */ unknownActions: string[]; + /** Inspections of the imported profiles that have no counterpart here. */ + unmappedInspections: string[]; + /** Imported named inspection profiles, offered for the open project after the import. */ + inspectionProfiles?: { id: string; name: string }[]; /** Custom live templates are committed once after confirmation, not through settings writes. */ liveTemplates?: JetBrainsTemplateImport; } @@ -55,6 +60,7 @@ interface CurrentSettings { codeStyle?: { languages?: Record }; }; customKeymaps?: Record; + inspections?: unknown; } const USER_PREFIX = "_@user_"; @@ -148,7 +154,14 @@ export async function planJetBrainsImport( languages?: readonly LanguageInfo[], ): Promise { const { editor } = current; - const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [], unknownActions: [] }; + const plan: JetBrainsImportPlan = { + writes: [], + rows: [], + skipped: [], + invalid: [], + unknownActions: [], + unmappedInspections: [], + }; const add = (key: string, value: string | number | boolean | undefined, label: string, shown?: string) => { if (value === undefined) return; plan.writes.push([key, value]); @@ -369,9 +382,26 @@ export async function planJetBrainsImport( } } + const inspectionFiles = Object.fromEntries( + Object.entries(bundle.files).filter(([file]) => /^inspection\/[^/]+\.xml$/.test(file)), + ); + if (Object.keys(inspectionFiles).length) { + const parsed = parseJetBrainsInspections(inspectionFiles, current.inspections); + plan.writes.push(...parsed.writes); + for (const p of parsed.profiles) + plan.rows.push({ + label: tx("Inspection profile"), + value: p.replaces + ? tx`${p.name} (inspections: ${p.count}, replaces the existing profile)` + : tx`${p.name} (inspections: ${p.count})`, + }); + plan.inspectionProfiles = parsed.profiles.flatMap((p) => (p.id ? [{ id: p.id, name: p.name }] : [])); + plan.unmappedInspections = parsed.unmapped; + plan.invalid.push(...parsed.invalid); + } + const has = (prefix: string) => bundle.entries.some((e) => e.startsWith(prefix)); if (has("codestyles/")) plan.skipped.push(tx("Code Style options other than Tabs and Indents")); - if (has("inspection/")) plan.skipped.push(tx("Inspections")); if (has("installed.txt")) plan.skipped.push(tx("Plugins")); return plan; } @@ -380,6 +410,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) { const left = [...plan.skipped, ...(plan.liveTemplates?.skipped ?? []), ...plan.invalid]; const unknown = plan.unknownActions; const unsupported = plan.liveTemplates?.unsupported.join(", ") ?? ""; + const unmapped = plan.unmappedInspections; return (
{tx("These settings will be imported:")}
@@ -397,6 +428,9 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
)} {unknown.length > 0 &&
{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}
} + {unmapped.length > 0 && ( +
{tx`Inspections without an equivalent in OpenIDEA (${unmapped.length}): ${unmapped.join(", ")}.`}
+ )} {unsupported &&
{tx`Unsupported template expressions (kept as text, not evaluated): ${unsupported}.`}
} ); @@ -430,4 +464,23 @@ export async function importJetBrainsSettings(path: string) { if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates); useProject.setState({ settings }); notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" }); + if (useProject.getState().project && plan.inspectionProfiles?.length) + offerInspectionProfiles(plan.inspectionProfiles); +} + +/** JetBrains keeps the profile in use per project, so the import only offers it for the open one. */ +function offerInspectionProfiles(profiles: { id: string; name: string }[]) { + notifications().notify({ + level: "info", + sticky: true, + key: "app.settingsImport.inspections", + title: tx("Use an imported inspection profile in this project?"), + actions: profiles.slice(0, 3).map(({ id, name: displayName }) => ({ + label: tx`Use ${displayName}`, + run: async () => { + const settings = await call(commands.settingsSet("project", "inspections.profile", JSON.stringify(id))); + useProject.setState({ settings }); + }, + })), + }); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 936e5f90fd..60553269b7 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1148,6 +1148,11 @@ "Not imported:": "Not imported:", "Current color scheme": "Current color scheme", "Current keymap": "Current keymap", + "Inspection profile": "Inspection profile", + "{name} (inspections: {count})": "{name} (inspections: {count})", + "Inspections without an equivalent in OpenIDEA ({length}): {join}.": "Inspections without an equivalent in OpenIDEA ({length}): {join}.", + "{name} (inspections: {count}, replaces the existing profile)": "{name} (inspections: {count}, replaces the existing profile)", + "Use an imported inspection profile in this project?": "Use an imported inspection profile in this project?", "Live templates": "Live templates", "{imported} imported, {skipped} skipped": "{imported} imported, {skipped} skipped", "Unsupported template expressions (kept as text, not evaluated): {unsupported}.": "Unsupported template expressions (kept as text, not evaluated): {unsupported}.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 6a4803e26e..8ae858700a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2363,6 +2363,10 @@ "Line, %": "行,%", "Line:Column Number": "行:列号", "Live Templates": "实时模板", + "{name} (inspections: {count})": "{name}({count} 项检查)", + "Inspections without an equivalent in OpenIDEA ({length}): {join}.": "OpenIDEA 中没有对应项的检查({length}):{join}。", + "{name} (inspections: {count}, replaces the existing profile)": "{name}({count} 项检查,替换现有的同名配置)", + "Use an imported inspection profile in this project?": "要在此项目中使用导入的检查配置吗?", "Live templates": "实时模板", "Loaded classes are up to date. Nothing to reload.": "已加载的类是最新的,无需重新加载。", "Loading packages": "正在加载软件包",