From 5fbe05e05470ea996a3ba59a2c0baa0c847323f8 Mon Sep 17 00:00:00 2001 From: PLR <51248199+plredmond@users.noreply.github.com> Date: Thu, 25 Apr 2024 16:57:56 -0700 Subject: [PATCH] [ruff F401 #10390 #10391] edit to make imports explicit --- crates/ruff_linter/src/fix/edits.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/ruff_linter/src/fix/edits.rs b/crates/ruff_linter/src/fix/edits.rs index 0a70cc4e2327c6..8b67bd3bda49c3 100644 --- a/crates/ruff_linter/src/fix/edits.rs +++ b/crates/ruff_linter/src/fix/edits.rs @@ -1,6 +1,6 @@ //! Interface for generating fix edits from higher-level actions (e.g., "remove an argument"). -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use ruff_diagnostics::Edit; use ruff_python_ast::parenthesize::parenthesized_range; @@ -122,6 +122,30 @@ pub(crate) fn remove_unused_imports<'a>( } } +/// Edits to make the specified imports explicit, e.g. change `import x` to `import x as x`. +pub(crate) fn make_imports_explicit<'a>( + member_names: impl Iterator, + stmt: &Stmt, + locator: &Locator, +) -> Vec { + let aliases = match stmt { + Stmt::Import(ast::StmtImport { names, .. }) => names, + Stmt::ImportFrom(ast::StmtImportFrom { names, .. }) => names, + _ => { + return Vec::new(); + } + }; + // FIXME: what if the import is already `a as b` or `a as a`? + member_names + .filter_map(|name| { + aliases + .iter() + .find(|alias| name == alias.name.id) + .map(|alias| Edit::range_replacement(format!("{name} as {name}"), alias.range)) + }) + .collect() +} + #[derive(Debug, Copy, Clone)] pub(crate) enum Parentheses { /// Remove parentheses, if the removed argument is the only argument left.