refactor(use-from-import): build fixed variant via AST (#3132)

This commit is contained in:
Florian Best 2023-02-22 19:17:37 +01:00 committed by GitHub
parent 7d55b417f7
commit 6ced5122e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 2 deletions

View File

@ -1,6 +1,7 @@
use ruff_macros::{define_violation, derive_message_formats}; use ruff_macros::{define_violation, derive_message_formats};
use rustpython_parser::ast::{Alias, Stmt}; use rustpython_parser::ast::{Alias, AliasData, Located, Stmt, StmtKind};
use crate::ast::helpers::{create_stmt, unparse_stmt};
use crate::ast::types::Range; use crate::ast::types::Range;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::fix::Fix; use crate::fix::Fix;
@ -58,7 +59,21 @@ pub fn use_from_import(checker: &mut Checker, stmt: &Stmt, alias: &Alias, names:
); );
if fixable && checker.patch(diagnostic.kind.rule()) { if fixable && checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("from {module} import {asname}"), unparse_stmt(
&create_stmt(StmtKind::ImportFrom {
module: Some(module.to_string()),
names: vec![Located::new(
stmt.location,
stmt.end_location.unwrap(),
AliasData {
name: asname.into(),
asname: None,
},
)],
level: Some(0),
}),
checker.stylist,
),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));