Add import insertion support to autofix capabilities (#3787)

This commit is contained in:
Charlie Marsh 2023-03-30 11:33:46 -04:00 committed by GitHub
parent d7113d3995
commit 01357f62e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 820 additions and 265 deletions

View file

@ -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}"),
));
}
}
}

View file

@ -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 {