mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-03 18:28:24 +00:00
Add import insertion support to autofix capabilities (#3787)
This commit is contained in:
parent
d7113d3995
commit
01357f62e5
20 changed files with 820 additions and 265 deletions
|
@ -219,10 +219,15 @@ impl<'a> Context<'a> {
|
|||
///
|
||||
/// ...then `resolve_qualified_import_name("sys", "version_info")` will return
|
||||
/// `Some("python_version")`.
|
||||
pub fn resolve_qualified_import_name(&self, module: &str, member: &str) -> Option<String> {
|
||||
pub fn resolve_qualified_import_name(
|
||||
&self,
|
||||
module: &str,
|
||||
member: &str,
|
||||
) -> Option<(&Stmt, String)> {
|
||||
self.scopes().enumerate().find_map(|(scope_index, scope)| {
|
||||
scope.binding_ids().find_map(|binding_index| {
|
||||
match &self.bindings[*binding_index].kind {
|
||||
let binding = &self.bindings[*binding_index];
|
||||
match &binding.kind {
|
||||
// Ex) Given `module="sys"` and `object="exit"`:
|
||||
// `import sys` -> `sys.exit`
|
||||
// `import sys as sys2` -> `sys2.exit`
|
||||
|
@ -234,7 +239,10 @@ impl<'a> Context<'a> {
|
|||
.take(scope_index)
|
||||
.all(|scope| scope.get(name).is_none())
|
||||
{
|
||||
return Some(format!("{name}.{member}"));
|
||||
return Some((
|
||||
binding.source.as_ref().unwrap().into(),
|
||||
format!("{name}.{member}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -250,7 +258,10 @@ impl<'a> Context<'a> {
|
|||
.take(scope_index)
|
||||
.all(|scope| scope.get(name).is_none())
|
||||
{
|
||||
return Some((*name).to_string());
|
||||
return Some((
|
||||
binding.source.as_ref().unwrap().into(),
|
||||
(*name).to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -265,7 +276,10 @@ impl<'a> Context<'a> {
|
|||
.take(scope_index)
|
||||
.all(|scope| scope.get(name).is_none())
|
||||
{
|
||||
return Some(format!("{name}.{member}"));
|
||||
return Some((
|
||||
binding.source.as_ref().unwrap().into(),
|
||||
format!("{name}.{member}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,6 +27,17 @@ pub struct Alias<'a> {
|
|||
pub as_name: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> Import<'a> {
|
||||
pub fn module(name: &'a str) -> Self {
|
||||
Self {
|
||||
name: Alias {
|
||||
name,
|
||||
as_name: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AnyImport<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue