Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

project: Report formatter failures in the status bar again (#60839)

Apoorva Verma56ab1c482570
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs
index 969e1fd1573..df2d411181f 100644
--- a/crates/editor/src/editor_tests.rs
+++ b/crates/editor/src/editor_tests.rs
@@ -55,12 +55,12 @@ use settings::{
InlayHintSettingsContent, ProjectSettingsContent, ScrollBeyondLastLine, SearchSettingsContent,
SettingsContent, SettingsStore,
};
-use std::{borrow::Cow, sync::Arc};
-use std::{cell::RefCell, future::Future, rc::Rc, sync::atomic::AtomicBool, time::Instant};
use std::{
- iter,
- sync::atomic::{self, AtomicUsize},
+ borrow::Cow,
+ sync::{Arc, atomic},
};
+use std::{cell::RefCell, future::Future, rc::Rc, sync::atomic::AtomicBool, time::Instant};
+use std::{iter, sync::atomic::AtomicUsize};
use task::TaskVariables;
use test::build_editor_with_project;
use unindent::Unindent;
@@ -17612,6 +17612,178 @@ async fn test_formatter_failure_does_not_abort_subsequent_formatters(cx: &mut Te
});
}
+#[gpui::test]
+async fn test_explicit_formatter_failure_is_recorded(cx: &mut TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.formatter = Some(FormatterList::Vec(vec![Formatter::LanguageServer(
+ settings::LanguageServerFormatterSpecifier::Current,
+ )]))
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_file(path!("/file.rs"), "fn main() {}\n".into())
+ .await;
+
+ let project = Project::test(fs, [path!("/").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+
+ let format_should_fail = Arc::new(AtomicBool::new(true));
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let format_should_fail = format_should_fail.clone();
+ move |fake_server| {
+ let format_should_fail = format_should_fail.clone();
+ fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
+ move |_params, _| {
+ let format_should_fail = format_should_fail.clone();
+ async move {
+ if format_should_fail.load(atomic::Ordering::Acquire) {
+ Err(anyhow::anyhow!("Simulated formatter failure"))
+ } else {
+ Ok(Some(Vec::new()))
+ }
+ }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/file.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, cx) = cx.add_window_view(|window, cx| {
+ build_editor_with_project(project.clone(), buffer, window, cx)
+ });
+
+ fake_servers.next().await.unwrap();
+
+ let format = |editor: &Entity<Editor>, cx: &mut VisualTestContext| {
+ editor
+ .update_in(cx, |editor, window, cx| {
+ editor.perform_format(
+ project.clone(),
+ FormatTrigger::Manual,
+ FormatTarget::Buffers(editor.buffer().read(cx).all_buffers()),
+ window,
+ cx,
+ )
+ })
+ .unwrap()
+ };
+ let last_failure = |cx: &mut VisualTestContext| {
+ project.read_with(cx, |project, cx| {
+ project
+ .lsp_store()
+ .read(cx)
+ .last_formatting_failure()
+ .map(str::to_string)
+ })
+ };
+
+ format(&editor, cx).await;
+ assert!(
+ last_failure(cx).is_some(),
+ "a failing explicitly configured formatter should be recorded"
+ );
+
+ format_should_fail.store(false, atomic::Ordering::Release);
+ format(&editor, cx).await;
+ assert_eq!(
+ last_failure(cx),
+ None,
+ "A later successful format clears the recorded failure"
+ );
+}
+
+#[gpui::test]
+async fn test_auto_formatter_failure_is_silent(cx: &mut TestAppContext) {
+ init_test(cx, |settings| {
+ // `formatter: "auto"` with prettier disallowed resolves to the primary language server.
+ settings.defaults.formatter = Some(FormatterList::Single(Formatter::Auto));
+ settings.defaults.prettier.get_or_insert_default().allowed = Some(false);
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_file(path!("/file.rs"), "fn main() {}\n".into())
+ .await;
+
+ let project = Project::test(fs, [path!("/").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new(|fake_server| {
+ fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
+ move |_params, _| async move {
+ Err(anyhow::anyhow!("Simulated formatter failure"))
+ },
+ );
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/file.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, cx) = cx.add_window_view(|window, cx| {
+ build_editor_with_project(project.clone(), buffer, window, cx)
+ });
+
+ fake_servers.next().await.unwrap();
+
+ editor
+ .update_in(cx, |editor, window, cx| {
+ editor.perform_format(
+ project.clone(),
+ FormatTrigger::Manual,
+ FormatTarget::Buffers(editor.buffer().read(cx).all_buffers()),
+ window,
+ cx,
+ )
+ })
+ .unwrap()
+ .await;
+
+ let last_failure = project.read_with(cx, |project, cx| {
+ project
+ .lsp_store()
+ .read(cx)
+ .last_formatting_failure()
+ .map(str::to_string)
+ });
+ assert_eq!(
+ last_failure, None,
+ "an auto-resolved formatter failure should not be surfaced"
+ );
+}
+
#[gpui::test]
async fn test_concurrent_format_requests(cx: &mut TestAppContext) {
init_test(cx, |_| {});
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index f9e563ccdb3..0500d15c33e 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -1548,6 +1548,7 @@ impl LocalLspStore {
});
let mut project_transaction = ProjectTransaction::default();
+ let mut format_error = None;
for buffer in &buffers {
zlog::debug!(
@@ -1601,10 +1602,16 @@ impl LocalLspStore {
.insert(cx.entity(), formatting_transaction);
});
- result?;
+ // Keep formatting the remaining buffers on failure, surfacing the first error.
+ if let Err(error) = result {
+ format_error.get_or_insert(error);
+ }
}
- Ok(project_transaction)
+ match format_error {
+ Some(error) => Err(error),
+ None => Ok(project_transaction),
+ }
}
async fn format_buffer_locally(
@@ -1747,8 +1754,13 @@ impl LocalLspStore {
.flatten()
.chain(formatters);
+ // Only explicitly configured formatters surface their failures;
+ // auto-resolved ones stay silent so a missing optional tool
+ // (e.g. prettier) does not warn on every save.
+ let mut format_error = None;
for formatter in formatters {
- let formatter = if formatter == &Formatter::Auto {
+ let is_auto = formatter == &Formatter::Auto;
+ let formatter = if is_auto {
if settings.prettier.allowed {
zlog::trace!(logger => "Formatter set to auto: defaulting to prettier");
&Formatter::Prettier
@@ -1774,10 +1786,16 @@ impl LocalLspStore {
.await
{
zlog::error!(logger => "Formatter failed, skipping: {err:#}");
+ if !is_auto {
+ format_error.get_or_insert(err);
+ }
}
}
- Ok(())
+ match format_error {
+ Some(err) => Err(err),
+ None => Ok(()),
+ }
}
async fn apply_formatter(