use tree_sitter::Node;
use sephera_core::types::{ImportKind, ImportStatement};
use sephera_core::plugins::{line_of, node_text};
pub fn extract_from_node(
source: &[u8],
node: &Node<'_>,
) -> Option<Vec<ImportStatement>> {
if node.kind() != "import_declaration" {
return None;
}
let line = line_of(node)?;
let text = node_text(source, node);
let body = text.strip_prefix("import ").unwrap_or(&text).trim();
let is_static = body.starts_with("static ");
let path = body
.strip_prefix("static ")
.unwrap_or(body)
.trim_end_matches(';')
.trim();
if path.is_empty() {
return None;
}
let kind = if is_static {
ImportKind::TypeAlias
} else if path.ends_with(".*") {
ImportKind::Namespace
} else {
ImportKind::Dependency
};
Some(vec![ImportStatement::new(path, line).with_kind(kind)])
}
#[cfg(test)]
mod tests {
use super::*;
use sephera_compression::SupportedLanguage;
use sephera_compression::with_parser;
use sephera_core::plugins::imports_found_by;
fn imports(source: &[u8]) -> Vec<ImportStatement> {
with_parser(SupportedLanguage::Java, source.len(), |parser| {
Ok(imports_found_by(source, parser, &crate::JavaPlugin))
})
.expect("a parser exists")
}
#[test]
fn an_ordinary_import_is_a_plain_dependency() {
let found = imports(b"import java.util.List;\n");
assert_eq!(found.len(), 1);
assert_eq!(found[0].raw_path, "java.util.List");
assert_eq!(found[0].kind, ImportKind::Dependency);
}
#[test]
fn a_static_import_is_tagged_so_resolution_can_drop_a_segment() {
let found = imports(b"import static com.example.Foo.VALUE;\n");
assert_eq!(found.len(), 1);
assert_eq!(found[0].raw_path, "com.example.Foo.VALUE");
assert_eq!(
found[0].kind,
ImportKind::TypeAlias,
"the keyword is literal in the source, not inferred from the path"
);
}
#[test]
fn a_wildcard_import_is_tagged_as_a_package() {
let found = imports(b"import com.example.*;\n");
assert_eq!(found[0].raw_path, "com.example.*");
assert_eq!(
found[0].kind,
ImportKind::Namespace,
"a package reference is not a dependency on one file"
);
}
#[test]
fn each_import_keeps_its_own_line() {
let found = imports(
b"import java.util.List;\nimport java.io.File;\n\nclass Main {}\n",
);
assert_eq!(
found.iter().map(|s| s.line).collect::<Vec<_>>(),
vec![1, 2]
);
}
#[test]
fn an_empty_import_is_not_reported() {
assert_eq!(
imports(b"import ;\n").len(),
0,
"a statement with no path in it names nothing"
);
}
}