fix(csharp): apply Roslyn's suppress and severity quick fixes (#7667)

Choosing Roslyn's "Suppress or configure issues" on a C# diagnostic did nothing: Roslyn returns its entries in the client command roslyn.client.nestedCodeAction, which the IDE did not handle. The entries are now listed by group (suppress, severity of the ID, of its category, of all analyzers) and applied like other code actions, so severities are written to .editorconfig. A newly created .editorconfig was ignored until a project reload, so the projects below it are now reported to Roslyn as changed. The real Roslyn test is ignored by default.

Closes #7646

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-03 16:45:44 +08:00
1 джерело 62bac6ec8c
коміт 27164e8919
10 files changed
+535 -3

No files matched your search

+262
Переглянути файл
@@ -0,0 +1,262 @@
//! Severity quick fixes writing `.editorconfig` (#7646), against the real `dotnet` and the Roslyn
//! language server installed as Settings does. It downloads the server, so it runs only on request:
//! `cargo test -p ide-host --test roslyn_editorconfig -- --ignored`; skipped without a .NET SDK.
mod common;
use ide_core::{DocId, IdeEvent, Pos, Range, RequestId, Severity};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::CodeAction;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const WINDOW: &str = "main";
const PROGRAM: &str =
"var c = new C();\nc.M();\n\nclass C\n{\n public string Name { get; set; } public void M() { }\n}\n";
/// `Name` on line 5, and the whole line, which CA1822 (on `M`) shares.
const NAME: Range = Range { start: Pos { line: 5, col: 18 }, end: Pos { line: 5, col: 22 } };
const LINE: Range = Range { start: Pos { line: 5, col: 0 }, end: Pos { line: 5, col: 56 } };
fn has_dotnet() -> bool {
Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success())
}
fn write(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
/// Installs the server as Settings does and puts it on `PATH` as the app does at startup. This
/// binary has one test, so nothing else reads the environment meanwhile.
fn install_roslyn() -> tempfile::TempDir {
let data = tempfile::tempdir().unwrap();
let languages: Vec<_> = ide_language::LanguageRegistry::load(None).unwrap().all();
ide_tools::Tools::new(data.path())
.install("roslyn-language-server", &languages, &Default::default(), &|_| {})
.unwrap();
ide_tools::extend_process_path(data.path());
data
}
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
host: Arc<Host>,
events: Arc<Mutex<Vec<IdeEvent>>>,
doc: DocId,
}
impl Fixture {
/// A console project below `app`, with a solution there or on its own.
async fn new(solution: bool) -> Self {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("app");
if solution {
write(&root.join("App.slnx"), "<Solution><Project Path=\"App/App.csproj\" /></Solution>\n");
}
write(
&root.join("App/App.csproj"),
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><OutputType>Exe</OutputType>\
<TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable>\
<AnalysisMode>All</AnalysisMode></PropertyGroup></Project>\n",
);
write(&root.join("App/Program.cs"), PROGRAM);
let restore = Command::new("dotnet").args(["restore", "App/App.csproj"]).current_dir(&root).output().unwrap();
assert!(restore.status.success(), "{}", String::from_utf8_lossy(&restore.stdout));
let events = Arc::new(Mutex::new(Vec::new()));
let seen = events.clone();
let host = Arc::new(Host::new(HostConfig {
sink_for: Box::new(move |_| {
let seen = seen.clone();
Arc::new(move |event: IdeEvent| seen.lock().unwrap().push(event))
}),
..common::host_config(&base.join("host"))
}));
host.set_project_trust(&root, true, false).await.unwrap();
host.open_project(WINDOW, &root).unwrap();
let doc = ops::doc::doc_open(&host, WINDOW, root.join("App/Program.cs")).await.unwrap().id;
Self { _tmp: tmp, root, host, events, doc }
}
/// Waits until the latest diagnostics give `code` the severity `want` (`None`: not reported).
async fn severity(&self, code: &str, want: Option<Severity>) {
let path = self.root.join("App/Program.cs");
let start = Instant::now();
loop {
let mut latest = std::collections::HashMap::new();
for event in self.events.lock().unwrap().iter() {
if let IdeEvent::Diagnostics { path: p, source, items } = event
&& **p == *path
{
latest.insert(source.clone(), items.clone());
}
}
let found = latest.values().flatten().find(|d| d.code.as_deref() == Some(code)).map(|d| d.severity);
if !latest.is_empty() && found == want {
return;
}
assert!(start.elapsed() < Duration::from_secs(180), "{code}: {found:?}, not {want:?}; {latest:?}");
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
/// The entries of "Suppress or configure issues" over `range`, as the UI builds their actions.
async fn entries(&self, range: Range) -> Vec<(String, CodeAction)> {
let start = Instant::now();
loop {
let actions = ops::lsp::lsp_code_actions(&self.host, WINDOW, self.doc, range, vec![]).await;
let parent = actions.as_ref().ok().and_then(|a| a.iter().find(|a| a.title.starts_with("Suppress or")));
if let Some(parent) = parent {
let command = parent.command.as_ref().unwrap();
assert_eq!(command.command, "roslyn.client.nestedCodeAction");
return command.arguments[0]["NestedCodeActions"]
.as_array()
.unwrap()
.iter()
.map(|entry| {
let path: Vec<&str> = entry["data"]["CodeActionPath"]
.as_array()
.unwrap()
.iter()
.filter_map(|p| p.as_str())
.collect();
let action = CodeAction {
title: entry["title"].as_str().unwrap().into(),
data: Some(entry["data"].clone()),
command: None,
..parent.clone()
};
(path[1..].join(" > "), action)
})
.collect();
}
assert!(start.elapsed() < Duration::from_secs(180), "no severity actions: {actions:?}");
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
async fn resolve(&self, entry: &str) -> ide_core::IdeResult<CodeAction> {
let entries = self.entries(NAME).await;
let (_, action) = entries.into_iter().find(|(path, _)| path == entry).expect(entry);
ops::lsp::lsp_resolve_code_action(&self.host, WINDOW, self.doc, action).await
}
async fn apply(&self, entry: &str) -> ide_core::IdeResult<()> {
let action = self.resolve(entry).await?;
ops::lsp::lsp_execute_code_action(&self.host, WINDOW, RequestId(1), self.doc, action, vec![]).await?;
Ok(())
}
/// Applies `entry` once the server has read the current `.editorconfig`, whose text becomes
/// one holding every line of `expect`.
async fn rewrites(&self, file: &str, entry: &str, expect: &[&str]) {
let path = self.root.join(file);
let start = Instant::now();
loop {
let before = std::fs::read_to_string(&path).unwrap();
let edit = self.resolve(entry).await.ok().and_then(|a| a.edit);
let after = edit.and_then(|edit| {
edit.files.iter().find_map(|f| match f {
ide_core::FileEdit::Edit { path: p, edits, .. } if **p == *path => {
let mut doc = ide_text::Document::new(&before);
doc.apply_edits(edits).ok()?;
Some(doc.text())
}
_ => None,
})
});
if let Some(after) = &after
&& expect.iter().all(|line| after.lines().filter(|l| l.trim() == *line).count() == 1)
{
return;
}
assert!(start.elapsed() < Duration::from_secs(60), "{file}: {after:?} from {before:?}");
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "installs roslyn-language-server and needs the .NET SDK"]
async fn severity_quick_fixes_write_editorconfig() {
if !has_dotnet() {
return;
}
let _tools = install_roslyn();
let f = Fixture::new(true).await;
let config = f.root.join(".editorconfig");
let read = || std::fs::read_to_string(&config).unwrap();
const KEY: &str = "dotnet_diagnostic.CS8618.severity";
f.severity("CS8618", Some(Severity::Warning)).await;
// Two diagnostics on one line each have their own severities.
let paths: Vec<String> = f.entries(LINE).await.into_iter().map(|(path, _)| path).collect();
for id in ["CS8618", "CA1822"] {
assert!(paths.contains(&format!("Configure {id} severity > Silent")), "{paths:?}");
}
// No `.editorconfig`: the server creates one beside the solution, applied without a restart.
f.apply("Configure CS8618 severity > Error").await.unwrap();
assert!(read().contains("[*.cs]") && read().contains(&format!("{KEY} = error")), "{}", read());
f.severity("CS8618", Some(Severity::Error)).await;
// The edit is undoable.
let id = f.events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
});
ops::lsp::undo_workspace_edit(&f.host, WINDOW, id.unwrap()).await.unwrap();
assert!(!config.exists());
f.severity("CS8618", Some(Severity::Warning)).await;
ops::lsp::redo_workspace_edit(&f.host, WINDOW, id.unwrap()).await.unwrap();
f.severity("CS8618", Some(Severity::Error)).await;
// An existing key is replaced, not repeated.
f.apply("Configure CS8618 severity > None").await.unwrap();
assert_eq!(read().matches(KEY).count(), 1, "{}", read());
assert!(read().contains(&format!("{KEY} = none")), "{}", read());
f.severity("CS8618", None).await;
write(&config, &format!("root = true\n[*.cs]\n{KEY} = warning\n"));
f.severity("CS8618", Some(Severity::Warning)).await;
// The server's edits of other existing files.
let line = format!("{KEY} = silent");
for (text, section) in [
("root = true\n", "[*.cs]"),
("root = true\n\n[*.md]\nindent_size = 2\n", "[*.cs]"),
("root = true\n\n[*.{cs,vb}]\nindent_size = 4\n", "[*.{cs,vb}]"),
] {
write(&config, text);
f.rewrites(".editorconfig", "Configure CS8618 severity > Silent", &[section, &line]).await;
}
// A read-only file is left alone, with an error.
let mut permissions = std::fs::metadata(&config).unwrap().permissions();
permissions.set_readonly(true);
std::fs::set_permissions(&config, permissions.clone()).unwrap();
let before = read();
let result = f.apply("Configure CS8618 severity > Error").await;
assert!(result.is_err(), "{}", read());
assert_eq!(read(), before);
#[allow(clippy::permissions_set_readonly_false)]
permissions.set_readonly(false);
std::fs::set_permissions(&config, permissions).unwrap();
// A nearer `.editorconfig` with `root = true` is the one edited.
write(&f.root.join("App/.editorconfig"), "root = true\n\n[*.cs]\nindent_size = 4\n");
f.rewrites("App/.editorconfig", "Configure CS8618 severity > Silent", &["[*.cs]", &line]).await;
f.host.shutdown().await;
// Without a solution it creates one beside the project.
let f = Fixture::new(false).await;
f.severity("CS8618", Some(Severity::Warning)).await;
f.apply("Configure CS8618 severity > Error").await.unwrap();
let created = std::fs::read_to_string(f.root.join("App/.editorconfig")).unwrap();
assert!(created.contains(&format!("{KEY} = error")), "{created}");
f.severity("CS8618", Some(Severity::Error)).await;
f.host.shutdown().await;
}
+10 -1
Переглянути файл
@@ -36,6 +36,7 @@ mod phoxite;
mod plugin_requests;
mod pull;
mod razor;
mod roslyn;
mod scope;
mod server;
mod source_actions;
@@ -3545,6 +3546,11 @@ impl LspManager {
self.configuration_cache.lock().invalidate_paths();
}
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
let reload = if servers.iter().any(|s| s.name == roslyn::NAME) {
roslyn::projects_under_new_editorconfigs(created)
} else {
Vec::new()
};
let open: HashMap<(ide_core::ServerId, u64), HashSet<PathBuf>> = {
let docs = self.docs.lock();
let mut open: HashMap<_, HashSet<_>> = HashMap::new();
@@ -3579,7 +3585,7 @@ impl LspManager {
.flat_map(|(paths, change)| paths.iter().map(move |p| (p, change)));
let watchers = run.watchers.read();
let roots = self.server_workspace_roots(&s);
let changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
let mut changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
// Dart watches the filesystem itself and rejects this unregistered notification.
if s.name == "dart" {
continue;
@@ -3597,6 +3603,9 @@ impl LspManager {
.collect()
};
drop(watchers);
if s.name == roslyn::NAME {
changes.extend(reload.iter().map(|p| (p, Change::Changed)));
}
if changes.is_empty() {
continue;
}
+34
Переглянути файл
@@ -0,0 +1,34 @@
//! Roslyn applies a changed `.editorconfig` at once, but reads a new one (as a severity quick fix
//! creates) only when a project reloads.
use std::path::PathBuf;
pub(crate) const NAME: &str = "roslyn-language-server";
/// The projects to report as changed for the `.editorconfig` files among `created`.
pub(crate) fn projects_under_new_editorconfigs(created: &[PathBuf]) -> Vec<PathBuf> {
created
.iter()
.filter(|p| p.file_name().is_some_and(|n| n == ".editorconfig"))
.filter_map(|p| p.parent())
.flat_map(|dir| ignore::WalkBuilder::new(dir).build().flatten())
.map(ignore::DirEntry::into_path)
.filter(|p| p.extension().is_some_and(|x| x == "csproj" || x == "vbproj"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_new_editorconfig_reloads_the_projects_below_it() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::write(root.join("a/A.csproj"), "").unwrap();
std::fs::write(root.join("a/A.cs"), "").unwrap();
assert_eq!(projects_under_new_editorconfigs(&[root.join(".editorconfig")]), [root.join("a/A.csproj")]);
assert!(projects_under_new_editorconfigs(&[root.join("a/A.cs")]).is_empty());
}
}
+2
Переглянути файл
@@ -18,6 +18,8 @@ With Roslyn, the editor shows inlay hints: parameter names before literals, `new
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
With Roslyn, `⌥↵` / `Alt+Enter` on a diagnostic offers **Suppress or configure issues**. Its entries are grouped: suppress the diagnostic, or set its severity (None, Silent, Suggestion, Warning, Error), that of its category or of all analyzers. A severity is written to the nearest `.editorconfig`; without one, the server creates it beside the solution (or the project, when there is none). The change is undoable and the diagnostics update without restarting the server.
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
+2
Переглянути файл
@@ -18,6 +18,8 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是
语言服务器会加载根据这些标记找到的解决方案或项目。FsAutoComplete 启动时开启了 `AutomaticWorkspaceInit`,无需等待编辑器请求就会自动加载项目。
使用 Roslyn 时,在诊断上按 `⌥↵` / `Alt+Enter` 会出现 **Suppress or configure issues**,条目按组排列:抑制该诊断,或设置它、它所属类别或全部分析器的严重级别(None、Silent、Suggestion、Warning、Error)。级别写入最近的 `.editorconfig`;没有该文件时,服务器在解决方案旁(没有解决方案时在项目旁)创建。修改可以撤销,诊断无需重启服务器即可更新。
跳转到类库类型的定义时,语言服务器返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
`ProjectSettings/ProjectVersion.txt` 这个标记是为 Unity 项目准备的。把 OpenIDEA 设为 Unity 外部编辑器的方法见 [Unity](/zh/languages/unity)。
+70
Переглянути файл
@@ -0,0 +1,70 @@
/**
* Roslyn's "Suppress or configure issues" (#7646). The host is stubbed at the IPC layer (no
* language server runs; `crates/ide-host/tests/roslyn_editorconfig.rs` runs the real one): the
* spec checks that the entries are listed by group and the chosen one is resolved and applied.
*/
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
test("severity entries open from the intention and apply from the keyboard", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(() => {
const entry = (group: string, title: string) => ({
title,
kind: "quickfix",
data: { CodeActionPath: ["Suppress or configure issues", group, title] },
});
const levels = ["None", "Silent", "Suggestion", "Warning", "Error"];
window.__ipc.handlers.lsp_code_actions = () => [
{
title: "Suppress or configure issues",
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: {
title: "Suppress or configure issues",
command: "roslyn.client.nestedCodeAction",
arguments: [
{
NestedCodeActions: [
entry("Suppress CS8618", "in Source"),
...levels.map((level) => entry("Configure CS8618 severity", level)),
],
},
],
},
data: null,
server: 1,
},
];
window.__ipc.handlers.lsp_resolve_code_action = (args) => ({ ...(args.action as object), edit: { files: [] } });
window.__ipc.handlers.lsp_resolve_command = () => null;
window.__ipc.handlers.lsp_execute_code_action = () => [];
});
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("Alt+Enter");
const intentions = page.getByRole("dialog", { name: "Intentions", exact: true });
await intentions.getByRole("option", { name: "Suppress or configure issues" }).click();
const popup = page.getByRole("dialog", { name: "Suppress or configure issues", exact: true });
await expect(popup.getByRole("option")).toHaveText(["in Source", "None", "Silent", "Suggestion", "Warning", "Error"]);
await expect(popup.getByText("Configure CS8618 severity")).toBeVisible();
await expect(popup.getByRole("listbox")).toBeFocused();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/a3-severity-list.png`, animations: "disabled" });
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await expect(popup).toHaveCount(0);
await expect
.poll(() => ipcCalls(page, "lsp_execute_code_action"))
.toMatchObject([
{
action: {
title: "Error",
data: { CodeActionPath: [expect.any(String), "Configure CS8618 severity", "Error"] },
},
},
]);
});
+2
Переглянути файл
@@ -1,4 +1,5 @@
import { MOVE_TO_FILE_COMMAND, moveToFile } from "./typescriptCommands";
import { chooseRoslynAction, ROSLYN_NESTED_COMMAND } from "./roslynActions";
import { serverCodeLenses } from "./serverCodeLens";
/**
* LSP-backed editor features: completion, diagnostics, hover / quick docs,
@@ -141,6 +142,7 @@ export function activate(): () => void {
registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerClientCommand(MOVE_TO_FILE_COMMAND, moveToFile),
registerClientCommand(ROSLYN_NESTED_COMMAND, chooseRoslynAction),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
+2 -2
Переглянути файл
@@ -237,7 +237,7 @@ export async function applyQuickFix(view: EditorView) {
* Commands a server leaves to the client (jdtls' `java.action.applyRefactoringCommand`, which
* opens a dialog or asks for a destination). A handler returns false for arguments it doesn't take.
*/
type ClientCommand = (view: EditorView, args: readonly unknown[]) => Promise<boolean>;
type ClientCommand = (view: EditorView, args: readonly unknown[], action: CodeAction) => Promise<boolean>;
const clientCommands = new Map<string, ClientCommand>();
export function registerClientCommand(name: string, run: ClientCommand): () => void {
@@ -264,7 +264,7 @@ export async function applyCodeAction(view: EditorView, action: EditorQuickFix)
return;
}
const client = !action.edit && action.command ? clientCommands.get(action.command.command) : undefined;
if (client && (await client(view, action.command!.arguments.map(parseArgument)))) return;
if (client && (await client(view, action.command!.arguments.map(parseArgument), action))) return;
const before = view.state.doc;
// The server's edit and its reformatting undo as one step (with the refactoring's own Undo).
const grouped = beginHistoryGroup(view);
+93
Переглянути файл
@@ -0,0 +1,93 @@
import { EditorState } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import type { CodeAction } from "@/bindings";
const edit = { files: [{ kind: "create" as const, path: "/p/.editorconfig", overwrite: false }] };
const lspResolveCodeAction = vi.fn(async (_doc: number, action: CodeAction) => ({
status: "ok" as const,
data: { ...action, edit },
}));
const lspExecuteCodeAction = vi.fn(async (_request: number, _doc: number, _action: CodeAction) => ({
status: "ok" as const,
data: [] as string[],
}));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: { ...actual.commands, lspResolveCodeAction, lspExecuteCodeAction },
};
});
type Item = { label: string; section: { label: string }; run: () => Promise<void> };
const popups: { title: string; items: Item[] }[] = [];
vi.mock("./popupStore", async (orig) => ({
...(await orig<typeof import("./popupStore")>()),
caretAnchor: () => ({ x: 0, y: 0 }),
openPopup: (p: (typeof popups)[number]) => popups.push(p),
}));
vi.mock("@/editor/api", async (orig) => ({
...(await orig<typeof import("@/editor/api")>()),
whenSynced: async () => {},
}));
vi.mock("./lsp", async (orig) => ({
...(await orig<typeof import("./lsp")>()),
docOf: () => ({ doc: 7, path: "/p/Program.cs", language: "csharp" }),
}));
const { chooseRoslynAction } = await import("./roslynActions");
/** The shape `roslyn-language-server` 5.13 answers. */
const entry = (group: string, title: string) => ({
title,
kind: "quickfix",
data: { CodeActionPath: ["Suppress or configure issues", group, title] },
});
const parent = {
title: "Suppress or configure issues",
kind: "quickfix",
diagnostics: [],
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 3,
} as CodeAction;
const view = { state: EditorState.create({ doc: "class C;" }), themeClasses: "" } as never;
describe("Roslyn's nested code actions", () => {
it("lists the entries by group without Fix All, then resolves and applies the chosen one", async () => {
const args = [
{
NestedCodeActions: [
entry("Suppress CS8618", "in Source"),
{
...entry("Suppress CS8618", "Fix All: in Source"),
command: { title: "", command: "roslyn.client.fixAllCodeAction" },
},
entry("Configure CS8618 severity", "None"),
entry("Configure CS8618 severity", "Error"),
],
},
];
expect(await chooseRoslynAction(view, args, parent)).toBe(true);
const { title, items } = popups[0]!;
expect(title).toBe("Suppress or configure issues");
expect(items.map((i) => `${i.section.label} / ${i.label}`)).toEqual([
"Suppress CS8618 / in Source",
"Configure CS8618 severity / None",
"Configure CS8618 severity / Error",
]);
void items[2]!.run();
await vi.waitFor(() => expect(lspExecuteCodeAction).toHaveBeenCalled());
expect(lspResolveCodeAction.mock.calls[0]![1]).toMatchObject({ title: "Error", server: 3, edit: null });
expect(lspExecuteCodeAction.mock.calls[0]![2]).toMatchObject({ data: args[0]!.NestedCodeActions[3]!.data, edit });
});
it("leaves arguments it does not know to the server", async () => {
expect(await chooseRoslynAction(view, ["x"], parent)).toBe(false);
expect(await chooseRoslynAction(view, [], parent)).toBe(false);
});
});
+58
Переглянути файл
@@ -0,0 +1,58 @@
/**
* Roslyn leaves its nested code actions ("Suppress or configure issues": suppressions and
* `.editorconfig` severities) to the client. Their entries are listed under their group's title
* and each is resolved and applied like any code action.
*/
import type { EditorView } from "@codemirror/view";
import type { CodeAction } from "@/platform/ipc";
import { applyCodeAction } from "./intentions";
import { caretAnchor, openPopup } from "./popupStore";
export const ROSLYN_NESTED_COMMAND = "roslyn.client.nestedCodeAction";
/** Fix All needs a scope the IDE has no dialog for. */
const ROSLYN_FIX_ALL_COMMAND = "roslyn.client.fixAllCodeAction";
interface NestedAction {
title: string;
kind?: string;
data?: { CodeActionPath?: string[] };
command?: { title: string; command: string; arguments?: unknown[] };
}
export async function chooseRoslynAction(
view: EditorView,
args: readonly unknown[],
parent: CodeAction,
): Promise<boolean> {
const nested = (args[0] as { NestedCodeActions?: NestedAction[] } | undefined)?.NestedCodeActions;
const entries = nested?.filter((a) => a.command?.command !== ROSLYN_FIX_ALL_COMMAND);
if (!entries?.length) return false;
openPopup({
kind: "list",
anchor: caretAnchor(view, view.state.selection.main.head),
title: parent.title,
themeClasses: view.themeClasses,
items: entries.map((entry, i) => {
// The path is the parent's title, the group's, then the entry's own.
const group = entry.data?.CodeActionPath?.slice(1, -1).join(" › ") ?? "";
return {
id: `roslyn:${i}`,
label: entry.title,
section: { id: group, label: group },
run: () =>
applyCodeAction(view, {
...parent,
title: entry.title,
kind: entry.kind ?? parent.kind,
data: (entry.data ?? null) as CodeAction["data"],
edit: null,
command: entry.command
? { ...entry.command, arguments: (entry.command.arguments ?? []) as string[] }
: null,
}),
};
}),
});
return true;
}