use sephera_core::{
path_utils as paths,
plugins::{ImportPlugin, ResolveContext, ResolverPlugin},
};
#[derive(Debug, Clone, Copy, Default)]
pub struct PythonPlugin;
impl ImportPlugin for PythonPlugin {
fn collect_declarations(
&self,
source: &[u8],
tree: &tree_sitter::Tree,
) -> Option<sephera_core::declarations::DeclaredNames> {
Some(crate::extract::declared_names(source, tree))
}
fn extract_from_node(
&self,
source: &[u8],
node: &tree_sitter::Node<'_>,
) -> Option<Vec<sephera_core::types::ImportStatement>> {
crate::extract::extract_from_node(source, node)
}
}
impl ResolverPlugin for PythonPlugin {
fn resolve(
&self,
import_path: &str,
context: ResolveContext<'_>,
) -> Option<String> {
let levels =
import_path.bytes().take_while(|byte| *byte == b'.').count();
let module_path = paths::replace_separator(&import_path[levels..], '.');
if levels > 0 {
let package =
ascend(&paths::parent(context.source_file), levels - 1);
if module_path.is_empty() {
let package_root = paths::join(&package, &["__init__.py"]);
return context.contains(&package_root).then_some(package_root);
}
let relative = paths::join(&package, &[&module_path]);
return first_existing(context, &relative);
}
first_existing(context, &module_path).or_else(|| {
let rooted = paths::join(&import_root(context), &[&module_path]);
first_existing(context, &rooted)
})
}
fn names_a_known_module(
&self,
name: &str,
context: ResolveContext<'_>,
) -> bool {
if name.is_empty() {
return false;
}
first_existing(context, name).is_some()
|| first_existing(
context,
&paths::join(&import_root(context), &[name]),
)
.is_some()
}
}
fn ascend(base: &str, levels: usize) -> String {
let mut result = base.to_owned();
for _ in 0..levels {
let parent = paths::parent(&result);
if parent == result {
break;
}
result = parent;
}
result
}
fn import_root(context: ResolveContext<'_>) -> String {
let mut directory = paths::parent(context.source_file);
let mut topmost_package: Option<String> = None;
loop {
let parent = paths::parent(&directory);
if parent == directory {
break;
}
if context.contains(&paths::join(&directory, &["__init__.py"])) {
topmost_package = Some(directory.clone());
}
directory = parent;
}
topmost_package.map_or(directory, |package| paths::parent(&package))
}
fn first_existing(context: ResolveContext<'_>, path: &str) -> Option<String> {
if path.is_empty() {
return None;
}
let module = format!("{path}.py");
if context.contains(&module) {
return Some(module);
}
let package = paths::join(path, &["__init__.py"]);
if context.contains(&package) {
return Some(package);
}
let directory = format!("{path}/");
context
.files()
.find(|known| known.starts_with(&directory))
.cloned()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn resolve(
import_path: &str,
source_file: &str,
files: &[&str],
) -> Option<String> {
let known: BTreeSet<String> =
files.iter().map(|f| (*f).to_owned()).collect();
let context = sephera_core::plugins::test_context(source_file, &known);
PythonPlugin.resolve(import_path, context)
}
#[test]
fn resolves_absolute_module() {
let files = ["pkg/util.py", "pkg/__init__.py", "main.py"];
assert_eq!(
resolve("pkg.util", "main.py", &files),
Some("pkg/util.py".to_owned())
);
}
#[test]
fn resolves_package_init() {
let files = ["pkg/__init__.py", "main.py"];
assert_eq!(
resolve("pkg", "main.py", &files),
Some("pkg/__init__.py".to_owned())
);
}
#[test]
fn resolves_single_dot_relative_import() {
let files = ["pkg/util.py", "pkg/main.py"];
assert_eq!(
resolve(".util", "pkg/main.py", &files),
Some("pkg/util.py".to_owned())
);
}
#[test]
fn resolves_double_dot_relative_import() {
let files = ["pkg/util.py", "pkg/sub/deep.py"];
assert_eq!(
resolve("..util", "pkg/sub/deep.py", &files),
Some("pkg/util.py".to_owned())
);
}
#[test]
fn relative_import_falls_back_to_an_absolute_sibling() {
let files = ["util.py", "pkg/main.py"];
assert_eq!(
resolve("..util", "pkg/main.py", &files),
Some("util.py".to_owned())
);
}
#[test]
fn relative_import_that_matches_nothing_stays_unresolved() {
let files = ["pkg/main.py"];
assert_eq!(resolve("..nowhere", "pkg/main.py", &files), None);
}
#[test]
fn external_package_is_not_resolved() {
let files = ["main.py"];
assert_eq!(resolve("os", "main.py", &files), None);
assert_eq!(resolve("os.path", "main.py", &files), None);
}
#[test]
fn ascend_stops_at_the_root() {
assert_eq!(ascend("a/b/c", 0), "a/b/c");
assert_eq!(ascend("a/b/c", 1), "a/b");
assert_eq!(ascend("a/b/c", 2), "a");
assert_eq!(ascend("a", 5), "");
}
#[test]
fn a_dots_only_path_resolves_the_package_it_names() {
let files = ["pkg/sub/__init__.py", "pkg/sub/deep.py"];
assert_eq!(
resolve(".", "pkg/sub/deep.py", &files),
Some("pkg/sub/__init__.py".to_owned())
);
assert_eq!(
resolve("..", "pkg/sub/deep.py", &files),
None,
"`pkg` has no `__init__.py` here, so two dots name no package"
);
}
#[test]
fn a_dots_only_path_does_not_land_on_a_bare_directory() {
let files = [
"python/pkg/__init__.py",
"python/pkg/sub/deep.py",
"python/orphan.py",
];
assert_eq!(
resolve("...", "python/pkg/sub/deep.py", &files),
None,
"a directory is not a package because it has files in it"
);
assert_eq!(
resolve("...outside", "python/pkg/sub/deep.py", &files),
None
);
}
#[test]
fn an_absolute_import_finds_the_directory_python_would_search() {
let files = [
"app/pkg/__init__.py",
"app/pkg/sub/__init__.py",
"app/pkg/sub/deep.py",
"app/pkg/sub/value.py",
];
assert_eq!(
resolve("pkg.sub.value", "app/pkg/sub/deep.py", &files),
Some("app/pkg/sub/value.py".to_owned())
);
assert_eq!(
resolve("pkg", "app/pkg/sub/deep.py", &files),
Some("app/pkg/__init__.py".to_owned())
);
}
#[test]
fn an_absolute_import_works_from_inside_a_namespace_subpackage() {
let files = [
"src/flask/__init__.py",
"src/flask/app.py",
"src/flask/sansio/app.py",
];
assert_eq!(
resolve("flask.app", "src/flask/sansio/app.py", &files),
Some("src/flask/app.py".to_owned()),
"`sansio` has no `__init__.py` and is still inside `flask`"
);
assert_eq!(
resolve("flask", "src/flask/sansio/app.py", &files),
Some("src/flask/__init__.py".to_owned())
);
}
#[test]
fn an_absolute_import_still_tries_the_analysis_base_first() {
let files = ["pkg/util.py", "main.py"];
assert_eq!(
resolve("pkg.util", "main.py", &files),
Some("pkg/util.py".to_owned())
);
assert_eq!(
resolve("util", "pkg/main.py", &["util.py", "pkg/main.py"]),
Some("util.py".to_owned()),
"a file outside any package makes both attempts identical"
);
}
#[test]
fn an_absolute_import_outside_a_package_stays_unresolved() {
let files = [
"tests/test_apps/helloworld/wsgi.py",
"tests/test_apps/helloworld/hello.py",
];
assert_eq!(
resolve("hello", "tests/test_apps/helloworld/wsgi.py", &files),
None,
"a bare module in a directory that is not a package is not \
importable by convention"
);
}
#[test]
fn a_name_the_analysis_holds_is_told_from_the_standard_library() {
let files = ["app/pkg/__init__.py", "app/pkg/sub/deep.py"];
let known: BTreeSet<String> =
files.iter().map(|f| (*f).to_owned()).collect();
let plugin = PythonPlugin;
let inside =
sephera_core::plugins::test_context("app/pkg/sub/deep.py", &known);
assert!(
plugin.names_a_known_module("pkg", inside),
"`pkg` is a package in this analysis"
);
let outside =
sephera_core::plugins::test_context("app/pkg/sub/deep.py", &known);
assert!(
!plugin.names_a_known_module("collections", outside),
"the standard library is not a local gap"
);
assert!(
!plugin.names_a_known_module("", outside),
"an empty name is a malformed path, not a module"
);
}
#[test]
fn resolve_missing_absolute_submodule_is_local_gap() {
let files = ["pkg/__init__.py", "main.py"];
let known: BTreeSet<String> =
files.iter().map(|f| (*f).to_owned()).collect();
let context = sephera_core::plugins::test_context("main.py", &known);
let plugin = PythonPlugin;
let resolved = plugin.resolve("pkg.absent", context);
assert_eq!(resolved, None, "missing submodule should not resolve");
}
#[test]
fn resolve_relative_import_with_too_many_dots_is_local_gap() {
let files = ["pkg/sub/deep.py", "pkg/__init__.py", "main.py"];
let known: BTreeSet<String> =
files.iter().map(|f| (*f).to_owned()).collect();
let context =
sephera_core::plugins::test_context("pkg/sub/deep.py", &known);
let plugin = PythonPlugin;
let resolved = plugin.resolve("...outside", context);
assert_eq!(resolved, None, "climbing past root should not resolve");
}
}