ruff server now supports the source.organizeImports source action (#10652)

## Summary

This builds on top of the work in
https://github.com/astral-sh/ruff/pull/10597 to support `Ruff: Organize
imports` as an available source action.

To do this, we have to support `Clone`-ing for linter settings, since we
need to modify them in place to select import-related diagnostics
specifically (`I001` and `I002`).

## Test Plan


04282d01-dfda-4ac5-aa8f-6a92d5f85bfd
This commit is contained in:
Jane Lewis 2024-04-04 15:20:50 -07:00 committed by GitHub
parent fd8da66fcb
commit d050d6da2e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 106 additions and 39 deletions

View file

@ -271,7 +271,7 @@ impl SupportedCodeAction {
[
Self::QuickFix,
Self::SourceFixAll,
// Self::SourceOrganizeImports,
Self::SourceOrganizeImports,
]
.into_iter()
}

View file

@ -9,7 +9,7 @@ use lsp_types::{self as types, request as req};
use rustc_hash::FxHashSet;
use types::{CodeActionKind, CodeActionOrCommand};
use super::code_action_resolve::resolve_edit_for_fix_all;
use super::code_action_resolve::{resolve_edit_for_fix_all, resolve_edit_for_organize_imports};
pub(crate) struct CodeActions;
@ -26,11 +26,11 @@ impl super::BackgroundDocumentRequestHandler for CodeActions {
) -> Result<Option<types::CodeActionResponse>> {
let mut response: types::CodeActionResponse = types::CodeActionResponse::default();
let supported_code_actions = supported_code_actions(params.context.only);
let supported_code_actions = supported_code_actions(params.context.only.clone());
if supported_code_actions.contains(&SupportedCodeAction::QuickFix) {
response.extend(
quick_fix(&snapshot, params.context.diagnostics)
quick_fix(&snapshot, params.context.diagnostics.clone())
.with_failure_code(ErrorCode::InternalError)?,
);
}
@ -40,7 +40,7 @@ impl super::BackgroundDocumentRequestHandler for CodeActions {
}
if supported_code_actions.contains(&SupportedCodeAction::SourceOrganizeImports) {
todo!("Implement the `source.organizeImports` code action");
response.push(organize_imports(&snapshot).with_failure_code(ErrorCode::InternalError)?);
}
Ok(Some(response))
@ -109,6 +109,39 @@ fn fix_all(snapshot: &DocumentSnapshot) -> crate::Result<CodeActionOrCommand> {
Ok(types::CodeActionOrCommand::CodeAction(action))
}
fn organize_imports(snapshot: &DocumentSnapshot) -> crate::Result<CodeActionOrCommand> {
let document = snapshot.document();
let (edit, data) = if snapshot
.resolved_client_capabilities()
.code_action_deferred_edit_resolution
{
// The edit will be resolved later in the `CodeActionsResolve` request
(
None,
Some(serde_json::to_value(snapshot.url()).expect("document url to serialize")),
)
} else {
(
Some(resolve_edit_for_organize_imports(
document,
snapshot.url(),
&snapshot.configuration().linter,
snapshot.encoding(),
)?),
None,
)
};
let action = types::CodeAction {
title: format!("{DIAGNOSTIC_NAME}: Organize imports"),
kind: Some(types::CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
edit,
data,
..Default::default()
};
Ok(types::CodeActionOrCommand::CodeAction(action))
}
/// If `action_filter` is `None`, this returns [`SupportedCodeActionKind::all()`]. Otherwise,
/// the list is filtered.
fn supported_code_actions(

View file

@ -7,6 +7,7 @@ use crate::session::DocumentSnapshot;
use crate::PositionEncoding;
use lsp_server::ErrorCode;
use lsp_types::{self as types, request as req};
use ruff_linter::codes::Rule;
use ruff_linter::settings::LinterSettings;
pub(crate) struct CodeActionResolve;
@ -47,9 +48,15 @@ impl super::BackgroundDocumentRequestHandler for CodeActionResolve {
)
.with_failure_code(ErrorCode::InternalError)?,
),
SupportedCodeAction::SourceOrganizeImports => {
todo!("Support `source.organizeImports`")
}
SupportedCodeAction::SourceOrganizeImports => Some(
resolve_edit_for_organize_imports(
document,
snapshot.url(),
&snapshot.configuration().linter,
snapshot.encoding(),
)
.with_failure_code(ErrorCode::InternalError)?,
),
SupportedCodeAction::QuickFix => {
return Err(anyhow::anyhow!(
"Got a code action that should not need additional resolution: {action_kind:?}"
@ -80,3 +87,30 @@ pub(super) fn resolve_edit_for_fix_all(
..Default::default()
})
}
pub(super) fn resolve_edit_for_organize_imports(
document: &crate::edit::Document,
url: &types::Url,
linter_settings: &ruff_linter::settings::LinterSettings,
encoding: PositionEncoding,
) -> crate::Result<types::WorkspaceEdit> {
let mut linter_settings = linter_settings.clone();
linter_settings.rules = [
Rule::UnsortedImports, // I001
Rule::MissingRequiredImport, // I002
]
.into_iter()
.collect();
Ok(types::WorkspaceEdit {
changes: Some(
[(
url.clone(),
crate::fix::fix_all(document, &linter_settings, encoding)?,
)]
.into_iter()
.collect(),
),
..Default::default()
})
}