Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[POC] ruff server Expand format action capability #11803

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ benchmark = "bench -p ruff_benchmark --bench linter --bench formatter --"
# that shared/dynamic library.
#
# See: https://github.com/astral-sh/ruff/issues/11503
[target.'cfg(all(target_env="msvc", target_os = "windows"))']
[target.'cfg(all(target_env = "msvc", target_os = "windows"))']
rustflags = ["-C", "target-feature=+crt-static"]
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
"ignore": ["RUF001"],
"run": "onSave"
},
"fixAll": false,
"sourceAction": {
"fixAll": false
},
"logLevel": "warn",
"lineLength": 80,
"exclude": ["third_party"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
"format": {
"args": []
},
"sourceAction": {
"organizeImports": true,
"fixAll": true
},
"enable": true,
"organizeImports": true,
"fixAll": true,
"showNotifications": "off"
},
{
Expand Down Expand Up @@ -62,9 +64,11 @@
"format": {
"args": []
},
"sourceAction": {
"organizeImports": true,
"fixAll": true
},
"enable": true,
"organizeImports": true,
"fixAll": true,
"showNotifications": "off"
}
],
Expand All @@ -87,7 +91,10 @@
"lint": {
"enable": true,
"preview": true,
"select": ["F", "I"],
"select": [
"F",
"I"
],
"run": "onType",
"args": [
"--preview"
Expand All @@ -96,9 +103,11 @@
"format": {
"args": []
},
"sourceAction": {
"organizeImports": true,
"fixAll": false
},
"enable": true,
"organizeImports": true,
"fixAll": false,
"showNotifications": "off"
}
}
}
47 changes: 44 additions & 3 deletions crates/ruff_server/src/fix.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::borrow::Cow;
use std::{borrow::Cow, sync::Arc};

use rustc_hash::FxHashMap;

Expand All @@ -8,13 +8,13 @@ use ruff_linter::{
settings::{flags, types::UnsafeFixes, LinterSettings},
};
use ruff_notebook::SourceValue;
use ruff_source_file::LineIndex;
use ruff_source_file::{LineIndex, OneIndexed};
use ruff_workspace::resolver::match_any_exclusion;

use crate::{
edit::{Replacement, ToRangeExt},
session::DocumentQuery,
PositionEncoding,
PositionEncoding, TextDocument,
};

/// A simultaneous fix made across a single text document or among an arbitrary
Expand Down Expand Up @@ -165,3 +165,44 @@ pub(crate) fn fix_all(
.collect())
}
}

pub(crate) fn parse_all(query: &DocumentQuery, fixes: Fixes) -> DocumentQuery {
match query {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feel free to rewrite this function. I think it could be better implementation at here.

DocumentQuery::Text {
file_url,
document,
settings,
} => {
let mut contents = document.contents().to_owned();
for (url, edits) in fixes {
if url == *file_url {
let text_edit = edits.first().unwrap();
let source_index = LineIndex::from_source_text(&contents);
let start_offset = source_index
.line_start(
OneIndexed::from_zero_indexed(text_edit.range.start.line as usize),
&contents,
)
.to_usize();
let end_offset = source_index
.line_start(
OneIndexed::from_zero_indexed(text_edit.range.end.line as usize),
&contents,
)
.to_usize();
let mut new_contents = String::new();
new_contents.push_str(&contents[..start_offset]);
new_contents.push_str(&text_edit.new_text);
new_contents.push_str(&contents[end_offset..]);
contents = new_contents;
}
}
DocumentQuery::Text {
file_url: file_url.clone(),
document: Arc::new(TextDocument::new(contents, document.version())),
settings: settings.clone(),
}
}
DocumentQuery::Notebook { .. } => query.clone(), // TODO
}
}
46 changes: 40 additions & 6 deletions crates/ruff_server/src/server/api/requests/format.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use lsp_server::ErrorCode;
use lsp_types::{self as types, request as req};
use types::TextEdit;

Expand All @@ -11,6 +12,8 @@ use crate::server::{client::Notifier, Result};
use crate::session::{DocumentQuery, DocumentSnapshot};
use crate::{PositionEncoding, TextDocument};

use super::code_action_resolve::{fix_all_edit, organize_imports_edit};

pub(crate) struct Format;

impl super::RequestHandler for Format {
Expand All @@ -24,7 +27,37 @@ impl super::BackgroundDocumentRequestHandler for Format {
_notifier: Notifier,
_params: types::DocumentFormattingParams,
) -> Result<super::FormatResponse> {
format_document(&snapshot)
match snapshot.query() {
DocumentQuery::Text { .. } => {
let mut query = snapshot.query().to_owned();
let mut response = None;

if snapshot.client_settings().organize_imports()
&& snapshot.client_settings().format_action().isort
{
let fixes = organize_imports_edit(&query, snapshot.encoding())
.with_failure_code(ErrorCode::InternalError)?;
query = crate::fix::parse_all(&query, fixes.clone());
response = fixes.values().next().map(std::borrow::ToOwned::to_owned);
}
if snapshot.client_settings().fix_all()
&& snapshot.client_settings().format_action().fix
{
let fixes = fix_all_edit(&query, snapshot.encoding())
.with_failure_code(ErrorCode::InternalError)?;
query = crate::fix::parse_all(&query, fixes.clone());
response = fixes.values().next().map(std::borrow::ToOwned::to_owned);
}
if snapshot.client_settings().format_action().style {
response = format_document(&query, snapshot.encoding())?;
}
Ok(response)
}
DocumentQuery::Notebook { .. } => {
format_document(snapshot.query(), snapshot.encoding())
} // TODO
}
// if snapshot.client_settings().format_action().style {}
}
}

Expand Down Expand Up @@ -60,16 +93,17 @@ pub(super) fn format_full_document(snapshot: &DocumentSnapshot) -> Result<Fixes>

/// Formats either a full text document or an specific notebook cell. If the query within the snapshot is a notebook document
/// with no selected cell, this will throw an error.
pub(super) fn format_document(snapshot: &DocumentSnapshot) -> Result<super::FormatResponse> {
let text_document = snapshot
.query()
pub(super) fn format_document(
query: &DocumentQuery,
encoding: PositionEncoding,
) -> Result<super::FormatResponse> {
let text_document = query
.as_single_document()
.expect("format should only be called on text documents or notebook cells");
let query = snapshot.query();
format_text_document(
text_document,
query,
snapshot.encoding(),
encoding,
query.as_notebook().is_some(),
)
}
Expand Down
Loading
Loading