дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
In a project that uses CSharpier (a dotnet tool manifest entry, or a .csharpierrc* / .csharpierignore with CSharpier installed), Reformat Code and format on save of a whole .cs file run CSharpier; selections and other projects keep the language server. CSharpier 0.x uses its pipe protocol. Solutions and projects get Run dotnet format and Verify dotnet format (No Changes) in the Project view and Find Action, with output in the Build window. The real SDK tests are ignored by default. Closes #7626 Co-authored-by: wildcatDownstairs <[email protected]>
229 рядки
9.7 KiB
Rust
229 рядки
9.7 KiB
Rust
//! Reformat Code with CSharpier (#7626), against the real `dotnet` and CSharpier from NuGet.
|
|
//! It downloads CSharpier, so it runs only on request:
|
|
//! `cargo test -p ide-host --test csharpier -- --ignored`; skipped without a .NET SDK.
|
|
|
|
mod common;
|
|
|
|
use ide_core::error::ErrorKind;
|
|
use ide_core::{IdeEvent, IdeResult, Pos, Range, TextEdit};
|
|
use ide_host::{Host, HostConfig, ops};
|
|
use ide_lsp::types::FormatOptions;
|
|
use ide_workspace::SettingsScope;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
const MESSY: &str = "class A{void M( ){var x=1;}}\n";
|
|
const TIDY: &str = "class A\n{\n void M()\n {\n var x = 1;\n }\n}\n";
|
|
|
|
fn dotnet(dir: &Path, args: &[&str]) {
|
|
let out = Command::new("dotnet").args(args).current_dir(dir).output().expect("dotnet");
|
|
assert!(
|
|
out.status.success(),
|
|
"dotnet {args:?}: {}{}",
|
|
String::from_utf8_lossy(&out.stdout),
|
|
String::from_utf8_lossy(&out.stderr)
|
|
);
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
/// A tool manifest in `dir` with CSharpier `version`, restored.
|
|
fn local_tool(dir: &Path, manifest: &str, version: &str, command: &str) {
|
|
write(
|
|
&dir.join(manifest),
|
|
&format!(
|
|
r#"{{"version":1,"isRoot":true,"tools":{{"csharpier":{{"version":"{version}","commands":["{command}"]}}}}}}"#
|
|
),
|
|
);
|
|
dotnet(dir, &["tool", "restore"]);
|
|
}
|
|
|
|
struct Fixture {
|
|
_tmp: tempfile::TempDir,
|
|
root: PathBuf,
|
|
host: Arc<Host>,
|
|
notices: Arc<Mutex<Vec<String>>>,
|
|
}
|
|
|
|
impl Fixture {
|
|
async fn new(trusted: bool) -> Self {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let base = dunce::canonicalize(tmp.path()).unwrap();
|
|
let root = base.join("app");
|
|
std::fs::create_dir_all(&root).unwrap();
|
|
let notices = Arc::new(Mutex::new(Vec::new()));
|
|
let seen = notices.clone();
|
|
let host = Arc::new(Host::new(HostConfig {
|
|
sink_for: Box::new(move |_| {
|
|
let seen = seen.clone();
|
|
Arc::new(move |event: IdeEvent| {
|
|
if let IdeEvent::Notify { body: Some(body), .. } = event {
|
|
seen.lock().unwrap().push(body);
|
|
}
|
|
})
|
|
}),
|
|
..common::host_config(&base.join("host"))
|
|
}));
|
|
host.set_project_trust(&root, trusted, false).await.unwrap();
|
|
host.open_project("main", &root).unwrap();
|
|
Self { _tmp: tmp, root, host, notices }
|
|
}
|
|
|
|
/// Reformat Code on the open document of `name` holding `text`; the result applied to it.
|
|
async fn format(&self, name: &str, text: &str, range: Option<Range>, on_save: bool) -> IdeResult<String> {
|
|
let path = self.root.join(name);
|
|
write(&path, text);
|
|
let doc = ops::doc::doc_open(&self.host, "main", path.clone()).await?;
|
|
let options = FormatOptions { tab_size: 4, insert_spaces: true, on_save, tool: None };
|
|
let edits: Vec<TextEdit> = ops::lsp::lsp_format(&self.host, "main", doc.id, range, options).await?;
|
|
assert_eq!(std::fs::read_to_string(&path).unwrap(), text, "formatting must not write the file");
|
|
// The open buffer holds no byte order mark (saving writes it back).
|
|
let mut formatted = ide_text::Document::new(text.trim_start_matches('\u{feff}'));
|
|
formatted.apply_edits(&edits).unwrap();
|
|
ops::doc::doc_close(&self.host, "main", doc.id).await?;
|
|
Ok(formatted.text())
|
|
}
|
|
|
|
fn notices(&self) -> Vec<String> {
|
|
std::mem::take(&mut self.notices.lock().unwrap())
|
|
}
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
|
async fn a_local_csharpier_formats_the_unsaved_document() {
|
|
if !has_dotnet() {
|
|
return;
|
|
}
|
|
let f = Fixture::new(true).await;
|
|
local_tool(&f.root, "dotnet-tools.json", "1.4.2", "csharpier");
|
|
|
|
// The manifest alone makes the project a CSharpier one.
|
|
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
|
|
|
// A configuration in a subfolder applies there only.
|
|
write(&f.root.join("sub/.csharpierrc"), "indentSize: 2\n");
|
|
assert_eq!(f.format("sub/A.cs", MESSY, None, false).await.unwrap(), TIDY.replace(" ", " "));
|
|
assert_eq!(f.format("B.cs", MESSY, None, false).await.unwrap(), TIDY);
|
|
assert!(f.notices().is_empty());
|
|
|
|
// `.csharpierignore`d and generated files stay as they are, with a notice.
|
|
write(&f.root.join(".csharpierignore"), "Ignored.cs\n");
|
|
assert_eq!(f.format("Ignored.cs", MESSY, None, false).await.unwrap(), MESSY);
|
|
assert_eq!(f.notices(), ["CSharpier left the file unchanged: its configuration excludes it"]);
|
|
assert_eq!(f.format("Form.g.cs", MESSY, None, false).await.unwrap(), MESSY);
|
|
f.notices();
|
|
|
|
// A syntax error is the tool's message and no edits.
|
|
let error = f.format("Broken.cs", "class B{ void M( { \n", None, false).await.unwrap_err();
|
|
assert!(error.message.contains("syntax errors"), "{}", error.message);
|
|
|
|
// CRLF, a byte order mark and non-ASCII text survive; the document keeps its line endings.
|
|
let crlf = "\u{feff}class 中{void M( ){var s=\"日本語 é 😀\";}}\r\n";
|
|
let formatted = f.format("Unicode.cs", crlf, None, false).await.unwrap();
|
|
assert!(formatted.contains("class 中\n{") && formatted.contains("var s = \"日本語 é 😀\";"), "{formatted:?}");
|
|
|
|
// A selection is the language server's (none runs here), never a whole-file rewrite.
|
|
let selection = Some(Range::new(Pos::new(0, 0), Pos::new(0, 7)));
|
|
if let Ok(text) = f.format("Selected.cs", MESSY, selection, false).await {
|
|
assert_eq!(text, MESSY);
|
|
}
|
|
assert!(f.notices().is_empty());
|
|
|
|
// Saving formats only with format on save.
|
|
let on_save = |enabled: bool| {
|
|
let value = enabled.to_string();
|
|
ops::project::set_settings(&f.host, "main", SettingsScope::Global, "editor.formatOnSave", &value).unwrap();
|
|
};
|
|
on_save(false);
|
|
assert_eq!(f.format("Save.cs", MESSY, None, true).await.unwrap(), MESSY);
|
|
on_save(true);
|
|
assert_eq!(f.format("Save.cs", MESSY, None, true).await.unwrap(), TIDY);
|
|
|
|
// A large file is within the formatter's time limit.
|
|
let methods: String = (0..4000).map(|i| format!("void M{i}( ){{var x={i};}}\n")).collect();
|
|
let large = f.format("Large.cs", &format!("class L{{\n{methods}}}\n"), None, false).await.unwrap();
|
|
assert!(large.contains(" void M3999()\n"));
|
|
|
|
// `format_text` (a document that is not open, as the commit dialog's) uses it too.
|
|
let options = FormatOptions { tab_size: 4, insert_spaces: true, on_save: false, tool: None };
|
|
let edits = ops::lsp::lsp_format_text(&f.host, "main", f.root.join("A.cs"), MESSY.into(), options).await.unwrap();
|
|
assert!(!edits.is_empty());
|
|
f.host.shutdown().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
|
async fn an_unrestored_local_tool_reports_dotnets_message() {
|
|
if !has_dotnet() {
|
|
return;
|
|
}
|
|
let f = Fixture::new(true).await;
|
|
write(
|
|
&f.root.join(".config/dotnet-tools.json"),
|
|
r#"{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"9.9.9","commands":["csharpier"]}}}"#,
|
|
);
|
|
let error = f.format("A.cs", MESSY, None, false).await.unwrap_err();
|
|
assert!(error.message.contains("dotnet tool restore"), "{}", error.message);
|
|
f.host.shutdown().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
|
async fn csharpier_before_1_0_formats_through_its_pipe() {
|
|
if !has_dotnet() {
|
|
return;
|
|
}
|
|
let f = Fixture::new(true).await;
|
|
local_tool(&f.root, ".config/dotnet-tools.json", "0.30.6", "dotnet-csharpier");
|
|
write(&f.root.join(".csharpierignore"), "Ignored.cs\n");
|
|
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
|
assert_eq!(f.format("Ignored.cs", MESSY, None, false).await.unwrap(), MESSY);
|
|
let error = f.format("Broken.cs", "class B{ \n", None, false).await.unwrap_err();
|
|
assert!(error.message.contains("Broken.cs") || error.message.contains("compile"), "{}", error.message);
|
|
f.host.shutdown().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
|
async fn an_installed_global_tool_formats_a_configured_project() {
|
|
if !has_dotnet() {
|
|
return;
|
|
}
|
|
let f = Fixture::new(true).await;
|
|
write(&f.root.join(".csharpierrc.json"), "{}");
|
|
// The install Settings runs, into the host's own data folder.
|
|
let data = f.root.parent().unwrap().join("host").join("data");
|
|
let languages: Vec<_> = ide_language::LanguageRegistry::load(None).unwrap().all();
|
|
ide_tools::Tools::new(&data).install("csharpier", &languages, &Default::default(), &|_| {}).unwrap();
|
|
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
|
f.host.shutdown().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
|
async fn restricted_mode_runs_no_csharpier() {
|
|
if !has_dotnet() {
|
|
return;
|
|
}
|
|
let f = Fixture::new(false).await;
|
|
write(
|
|
&f.root.join("dotnet-tools.json"),
|
|
r#"{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"1.4.2","commands":["csharpier"]}}}"#,
|
|
);
|
|
// The language server's path: nothing runs, so nothing changes.
|
|
match f.format("A.cs", MESSY, None, false).await {
|
|
Ok(text) => assert_eq!(text, MESSY),
|
|
Err(e) => assert_ne!(e.kind, ErrorKind::Internal, "{}", e.message),
|
|
}
|
|
f.host.shutdown().await;
|
|
}
|