feat(settings): import JetBrains inspection profiles (#6725)

Importing JetBrains settings now carries over inspection profiles (inspection/*.xml): Default merges into OpenIDEA's Default profile and other profiles become IDE-level profiles of the same name. Inspections with a counterpart keep their state and level, PEP 8 codes PyCharm ignores are turned off for Ruff and pylsp, and the confirmation lists what has no equivalent.

Closes #6723

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 12:48:26 +08:00
1 джерело 6e37a1a977
коміт 41cb8f993e
9 files changed
+345 -9

No files matched your search

+14 -4
Переглянути файл
@@ -522,7 +522,7 @@ impl SettingsStore {
pub struct JetBrainsSettings {
pub entries: Vec<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/`.
pub files: BTreeMap<String, String>,
}
@@ -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", "<templateSet name=\"Python\"/>"),
("templates/nested/ignored.xml", "<templateSet/>"),
("templates/ignored.txt", "not XML"),
("inspection/Strict.xml", "<profile/>"),
("options/mac/keymap.xml", "<application/>"),
("options/terminal-font.xml", "<application/>"),
],
);
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::<Vec<_>>(),
[
"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", "<code_scheme/>");
put("templates/Python.xml", "<templateSet name=\"Python\"/>");
put("templates/nested/ignored.xml", "<templateSet/>");
put("inspection/Strict.xml", "<profile/>");
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"
]
);
+1 -1
Переглянути файл
@@ -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 },
};
+76
Переглянути файл
@@ -0,0 +1,76 @@
import { expect, it } from "vitest";
import { parseJetBrainsInspections } from "../jetbrainsInspections";
const strict =
'<profile version="1.0">' +
'<option name="myName" value="Strict" />' +
'<inspection_tool class="PyAbstractClassInspection" enabled="true" level="ERROR" enabled_by_default="true" />' +
'<inspection_tool class="PyMethodMayBeStaticInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />' +
'<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">' +
'<option name="ignoredErrors"><list><option value="E501" /><option value="W5" /></list></option>' +
"</inspection_tool>" +
'<inspection_tool class="SpellCheckingInspection" enabled="true" level="INFORMATION" enabled_by_default="true">' +
'<scope name="Tests" level="TYPO" enabled="false" />' +
'<option name="processCode" value="false" /><option name="processLiterals" value="true" />' +
"</inspection_tool>" +
'<inspection_tool class="PyUnresolvedReferencesInspection" enabled="false" level="WARNING" enabled_by_default="false" />' +
'<inspection_tool class="PyRedundantOverrideInspection" enabled="true" level="MY_SEVERITY" enabled_by_default="true" />' +
"</profile>";
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": "<oops" }, {});
expect(result.writes).toEqual([
[
"inspections.ideProfiles",
{
strict: {
name: "Strict",
overrides: {
"builtin:python-abstract-method": { enabled: true, severity: "error" },
"builtin:python-method-may-be-static": { enabled: false, severity: "weakWarning" },
"lsp:ruff:E501": { enabled: false },
"lsp:pylsp:E501": { enabled: false },
"builtin:spelling": {
enabled: true,
severity: "none",
options: { processCode: false, processLiterals: true },
},
// The custom severity is left out; the inspection still turns on.
"builtin:python-redundant-override": { enabled: true },
},
},
},
],
]);
expect(result.profiles).toEqual([{ name: "Strict", count: 5, id: "ide:strict", replaces: false }]);
expect(result.unmapped).toEqual([
"PyPep8Inspection: W5",
"SpellCheckingInspection (Tests)",
"PyUnresolvedReferencesInspection",
"PyRedundantOverrideInspection (MY_SEVERITY)",
]);
expect(result.invalid).toEqual(["bad.xml"]);
});
it("merges Default into the Default profile and replaces an earlier import by name", () => {
const current = {
default: { "builtin:sql": { enabled: false }, "builtin:spelling": { enabled: true } },
ideProfiles: { strict: { name: "Strict", overrides: { "builtin:sql": { enabled: false } } } },
};
const def =
'<profile version="1.0"><option name="myName" value="Default" />' +
'<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false" /></profile>';
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<string, { overrides: object }>;
expect(Object.keys(customs)).toEqual(["strict"]);
expect(customs.strict!.overrides).not.toHaveProperty("builtin:sql");
});
+9 -1
Переглянути файл
@@ -54,6 +54,11 @@ const webstorm = {
showTipsOnStartup: "false",
confirmExit: "false",
}),
"inspection/Default.xml":
'<profile version="1.0"><option name="myName" value="Default" />' +
'<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false" />' +
'<inspection_tool class="JSUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />' +
"</profile>",
},
};
@@ -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([]);
});
+31
Переглянути файл
@@ -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":
'<profile version="1.0"><option name="myName" value="Strict" />' +
'<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false" />' +
"</profile>",
},
},
});
render(<MessagesHost />);
let done!: Promise<void>;
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 });
});
+149
Переглянути файл
@@ -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<string, string>([
["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<string, InspectionLevel> = {
ERROR: "error",
WARNING: "warning",
"WEAK WARNING": "weakWarning",
"SERVER PROBLEM": "serverProblem",
TYPO: "typo",
INFORMATION: "none",
INFO: "none",
"TEXT ATTRIBUTES": "none",
};
const SPELLING_KEYS = new Set<string>(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:<key>`), 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<string, InspectionOverride>, unmapped: Set<string>): 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<string, string>, 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<string>();
for (const [file, text] of Object.entries(files)) {
const doc = new DOMParser().parseFromString(text, "application/xml");
// App-level files are a bare <profile>; project ones wrap it in a <component>.
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<string, InspectionOverride> = {};
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;
}
+56 -3
Переглянути файл
@@ -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<string, LanguageCodeStyle> };
};
customKeymaps?: Record<string, CustomKeymap>;
inspections?: unknown;
}
const USER_PREFIX = "_@user_";
@@ -148,7 +154,14 @@ export async function planJetBrainsImport(
languages?: readonly LanguageInfo[],
): Promise<JetBrainsImportPlan> {
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 (
<div className={styles.importSummary}>
<div>{tx("These settings will be imported:")}</div>
@@ -397,6 +428,9 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
</div>
)}
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
{unmapped.length > 0 && (
<div>{tx`Inspections without an equivalent in OpenIDEA (${unmapped.length}): ${unmapped.join(", ")}.`}</div>
)}
{unsupported && <div>{tx`Unsupported template expressions (kept as text, not evaluated): ${unsupported}.`}</div>}
</div>
);
@@ -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 });
},
})),
});
}
+5
Переглянути файл
@@ -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}.",
+4
Переглянути файл
@@ -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": "正在加载软件包",