mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-29 13:25:17 +00:00

## Summary Fixes https://github.com/astral-sh/ruff-vscode/issues/482. I've made adjustments to `format` and `format_range` that handle parsing errors before they become server errors. We'll still log this as a problem, but there will no longer be a visible popup. ## Test Plan Instead of seeing a visible error when formatting a document with syntax issues, you should see this warning in the LSP logs: <img width="991" alt="Screenshot 2024-06-04 at 3 38 23 PM" src="9d68947d
-6462-4ca6-ab5a-65e573c91db6"> Similarly, if you try to format a range with syntax issues, you should see this warning in the LSP logs instead of a visible error popup: <img width="1010" alt="Screenshot 2024-06-04 at 3 39 10 PM" src="99fff098
-798d-406a-976e-81ead0da0352"> --------- Co-authored-by: Zanie Blue <contact@zanie.dev>
58 lines
2 KiB
Rust
58 lines
2 KiB
Rust
use ruff_formatter::PrintedRange;
|
|
use ruff_python_ast::PySourceType;
|
|
use ruff_python_formatter::{format_module_source, FormatModuleError};
|
|
use ruff_text_size::TextRange;
|
|
use ruff_workspace::FormatterSettings;
|
|
|
|
use crate::edit::TextDocument;
|
|
|
|
pub(crate) fn format(
|
|
document: &TextDocument,
|
|
source_type: PySourceType,
|
|
formatter_settings: &FormatterSettings,
|
|
) -> crate::Result<Option<String>> {
|
|
let format_options = formatter_settings.to_format_options(source_type, document.contents());
|
|
match format_module_source(document.contents(), format_options) {
|
|
Ok(formatted) => {
|
|
let formatted = formatted.into_code();
|
|
if formatted == document.contents() {
|
|
Ok(None)
|
|
} else {
|
|
Ok(Some(formatted))
|
|
}
|
|
}
|
|
// Special case - syntax/parse errors are handled here instead of
|
|
// being propagated as visible server errors.
|
|
Err(FormatModuleError::ParseError(error)) => {
|
|
tracing::warn!("Unable to format document: {error}");
|
|
Ok(None)
|
|
}
|
|
Err(err) => Err(err.into()),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn format_range(
|
|
document: &TextDocument,
|
|
source_type: PySourceType,
|
|
formatter_settings: &FormatterSettings,
|
|
range: TextRange,
|
|
) -> crate::Result<Option<PrintedRange>> {
|
|
let format_options = formatter_settings.to_format_options(source_type, document.contents());
|
|
|
|
match ruff_python_formatter::format_range(document.contents(), range, format_options) {
|
|
Ok(formatted) => {
|
|
if formatted.as_code() == document.contents() {
|
|
Ok(None)
|
|
} else {
|
|
Ok(Some(formatted))
|
|
}
|
|
}
|
|
// Special case - syntax/parse errors are handled here instead of
|
|
// being propagated as visible server errors.
|
|
Err(FormatModuleError::ParseError(error)) => {
|
|
tracing::warn!("Unable to format document range: {error}");
|
|
Ok(None)
|
|
}
|
|
Err(err) => Err(err.into()),
|
|
}
|
|
}
|