Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions crates/ruff_server/src/format.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ruff_formatter::PrintedRange;
use ruff_python_ast::PySourceType;
use ruff_python_formatter::format_module_source;
use ruff_python_formatter::{format_module_source, FormatModuleError};
use ruff_text_size::TextRange;
use ruff_workspace::FormatterSettings;

Expand All @@ -12,8 +12,16 @@ pub(crate) fn format(
formatter_settings: &FormatterSettings,
) -> crate::Result<String> {
let format_options = formatter_settings.to_format_options(source_type, document.contents());
let formatted = format_module_source(document.contents(), format_options)?;
Ok(formatted.into_code())
match format_module_source(document.contents(), format_options) {
Ok(formatted) => Ok(formatted.into_code()),
// Special case - syntax/parse errors are be handled here instead of
// being propagated as visible server errors.
Err(FormatModuleError::ParseError(error)) => {
tracing::warn!("Unable to format document: {error}");
Ok(document.contents().to_string())
}
Err(err) => Err(err.into()),
}
}

pub(crate) fn format_range(
Expand All @@ -24,9 +32,14 @@ pub(crate) fn format_range(
) -> crate::Result<PrintedRange> {
let format_options = formatter_settings.to_format_options(source_type, document.contents());

Ok(ruff_python_formatter::format_range(
document.contents(),
range,
format_options,
)?)
match ruff_python_formatter::format_range(document.contents(), range, format_options) {
Ok(formatted) => Ok(formatted),
// Special case - syntax/parse errors should be handled here instead of
// being propagated to become visible server errors.
Err(FormatModuleError::ParseError(error)) => {
tracing::warn!("Unable to format document range: {error}");
Ok(PrintedRange::new(document.contents().to_string(), range))
}
Err(err) => Err(err.into()),
}
}