Skip to content
Merged
61 changes: 61 additions & 0 deletions crates/cli/tests/integration/orphan_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,67 @@ fn diff_main_json(dir: &Path, cache: &Path, expected_code: i32) -> Value {
)
}

#[test]
fn python_from_namespace_imports_reach_local_children_without_external_findings() {
let repo = init_git_repo(&[
("codeint.yaml", "entry_points:\n - main.py\n"),
("pyproject.toml", "[project]\nname = 'demo-app'\n"),
(
"main.py",
"from demo import (worker as job, extra)\nfrom demo.ns import child\nfrom service.ns import task\nfrom service.__init__ import service_value\nfrom __init__ import root_value\nfrom cgi import local\nfrom requests import Session\nprint(job.value + extra.value + child.value + task.value + local.value + service_value + root_value)\n",
),
("demo/worker.py", "value = 42\n"),
("demo.worker.py", "value = -1\n"),
("demo.ns.py", "value = -1\n"),
("demo/ns/child.py", "value = 0\n"),
("requests.Session.py", "value = -1\n"),
("src/demo/extra.py", "value = 0\n"),
("demo/unused.py", "value = 1\n"),
("service/ns/task.py", "value = -1\n"),
("service/ns.py", "value = -1\n"),
("__init__.py", "root_value = 0\n"),
("src/service/__init__.py", "service_value = 0\n"),
("src/service/ns/task.py", "value = 0\n"),
("cgi/local.py", "value = 0\n"),
]);

for target in [
"demo/worker.py",
"src/demo/extra.py",
"demo/ns/child.py",
"src/service/ns/task.py",
"src/service/__init__.py",
"__init__.py",
"cgi/local.py",
] {
let trace = run_json(
repo.path(),
None,
&["trace", "main.py", target, "--format", "json"],
0,
);
assert_eq!(trace["paths"], json!([["main.py", target]]), "{target}");
}

let report = run_json(
repo.path(),
None,
&["check", "--all", "--format", "json"],
0,
);
let orphans = orphan_finding_paths(production_orphans(&report));
assert!(orphans.contains(&"demo/unused.py"));
assert!(orphans.contains(&"demo.worker.py"));
assert!(orphans.contains(&"demo.ns.py"));
assert!(orphans.contains(&"requests.Session.py"));
assert!(orphans.contains(&"service/ns/task.py"));
assert!(orphans.contains(&"service/ns.py"));
assert!(!orphans.contains(&"src/service/ns/task.py"));
let unlisted = &report["dependencies"]["unlisted_dependencies"]["findings"];
assert_eq!(unlisted.as_array().unwrap().len(), 1);
assert_eq!(unlisted[0]["dependency"], "requests");
}

#[test]
fn ts_check_reports_orphan_files_across_toon_json_sarif_and_markdown_excluding_generated_and_vendored()
{
Expand Down
2 changes: 2 additions & 0 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1875,6 +1875,8 @@ Marked files in the Test, Generated, or Vendored Source sets stay out of entry p
Production files unreachable from any Production entry point are reported as `unreferenced`, or as `test-only` when still imported by Test files.
In Python, `from demo import worker` reaches `demo/worker.py` when `worker` is a child module of `demo`.
The child module counts as a possible target even when the package exports a symbol with the same name.
For a namespace package without `__init__.py`, a matching child module on a supported import root counts as a local import.
When a namespace spans several import roots, codeint retains each possible child target within that namespace.
Generated and Vendored Source sets and Tooling files (files inside universal repository tooling folders `.github/`, `scripts/`, `docs/`, `examples/`, `tools/`, and `benches/` at the repository root or a package root, plus language-specific Tooling files marked `is-tooling-file` by their owning Language plugin) are excluded from discovered entry-point roots and evaluated Production files.
A Tooling file stays in the Production Source set for all other Production Metrics and Hazards, and listing a Tooling file under `entry_points` overrides its exclusion from Orphan files so it acts as a live entry point.
When no runtime entry points exist for a language or isolated Workspace package, Orphan files reporting stays silently inactive.
Expand Down
1 change: 1 addition & 0 deletions plugins/languages/python/HOW-TO.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
- `src/imports.rs` and `src/resolution.rs` extract runtime imports while ignoring imports inside `if TYPE_CHECKING:` (or `if typing.TYPE_CHECKING:`) guard blocks and `from __future__ import` directives.
- Relative imports (`.foo`, `..bar`, and `from . import Symbol`) and repository-root or `src/`-layout package imports resolve to repository `.py` files, standard-library top-level modules are classified as `Builtin`, and third-party modules are classified as `External` with PEP 503 normalized package names.
- A named import such as `from demo import worker` keeps the package import and adds an edge to a matching child module.
- Namespace child lookup checks path components on each import root. See [Orphan files](../../../docs/reference.md#orphan-files).
- The resolver groups original names by source module and omits aliases.
- If a package exports a symbol with the same name as a child module, the resolver retains the child module as a possible target.
- `src/entry_points.rs` discovers top-level package `__init__.py` and `__main__.py` entry points (excluding non-package tooling/test/docs folders) plus `[project.scripts]`, `[project.gui-scripts]`, `[project.entry-points]`, and Poetry script entry points from `pyproject.toml`.
Expand Down
179 changes: 149 additions & 30 deletions plugins/languages/python/src/resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ use crate::stdlib::is_stdlib_module;
#[cfg(test)]
mod tests;

#[derive(Default)]
struct ModuleIndex {
modules: HashMap<String, String>,
roots: Vec<String>,
}

pub(crate) fn find_python_manifests<P: AsRef<str>>(repository_paths: &[P]) -> Vec<String> {
repository_paths
.iter()
Expand Down Expand Up @@ -54,51 +60,48 @@ pub(crate) fn resolve_with_profiles(
.filter(|path| path.ends_with(".py"))
.map(str::to_owned)
.collect();
let module_map = build_module_map(&py_files, manifests);
let empty_fallback = HashMap::new();
let mut fallback_cache: HashMap<&[String], HashMap<String, String>> = HashMap::new();
let module_index = build_module_index(&py_files, manifests);
let empty_fallback = ModuleIndex::default();
let mut fallback_cache: HashMap<&[String], ModuleIndex> = HashMap::new();
requests
.iter()
.map(|req| {
let active = codeint_model::active_profiles_for_path(package_profiles, &req.importer);
let fallback_map = if active.is_empty() {
let fallback_index = if active.is_empty() {
&empty_fallback
} else {
fallback_cache.entry(active).or_insert_with(|| {
let extra_roots = fallback_import_roots(active, repository_paths, manifests);
build_module_map_for_roots(&py_files, &extra_roots)
build_module_index_for_roots(&py_files, extra_roots)
})
};
resolve_one(
&py_files,
&module_map,
fallback_map,
&module_index,
fallback_index,
&req.importer,
&req.specifier,
)
})
.collect()
}

fn build_module_map(py_files: &HashSet<String>, manifests: &[Manifest]) -> HashMap<String, String> {
fn build_module_index(py_files: &HashSet<String>, manifests: &[Manifest]) -> ModuleIndex {
let mut roots = vec![String::new(), "src".to_owned()];
for manifest in manifests {
if let Some(dir) = manifest.path.strip_suffix("/pyproject.toml") {
roots.push(dir.to_owned());
roots.push(format!("{dir}/src"));
}
}
build_module_map_for_roots(py_files, &roots)
build_module_index_for_roots(py_files, roots)
}

fn build_module_map_for_roots(
py_files: &HashSet<String>,
roots: &[String],
) -> HashMap<String, String> {
fn build_module_index_for_roots(py_files: &HashSet<String>, roots: Vec<String>) -> ModuleIndex {
let mut sorted_files: Vec<&String> = py_files.iter().collect();
sorted_files.sort();
let mut map = HashMap::new();
for root in roots {
let mut modules = HashMap::new();
for root in &roots {
let prefix = if root.is_empty() {
String::new()
} else {
Expand All @@ -109,11 +112,11 @@ fn build_module_map_for_roots(
continue;
};
if let Some(module) = path_to_module(rel) {
map.entry(module).or_insert_with(|| (*file).clone());
modules.entry(module).or_insert_with(|| (*file).clone());
}
}
}
map
ModuleIndex { modules, roots }
}

fn path_to_module(rel: &str) -> Option<String> {
Expand All @@ -128,8 +131,8 @@ fn path_to_module(rel: &str) -> Option<String> {

fn resolve_one(
py_files: &HashSet<String>,
module_map: &HashMap<String, String>,
fallback_map: &HashMap<String, String>,
module_index: &ModuleIndex,
fallback_index: &ModuleIndex,
importer: &str,
specifier: &str,
) -> Resolution {
Expand All @@ -138,20 +141,136 @@ fn resolve_one(
if module.starts_with('.') {
return resolve_relative(py_files, importer, module, names);
}
if let Some(target) = module_map.get(module).or_else(|| fallback_map.get(module)) {
if let Some(names) = names
&& let Some(package) = target
.strip_suffix("/__init__.py")
.or_else(|| target.strip_suffix(".py"))
{
let package_init = init_path_for(package);
if py_files.contains(&package_init) {
let resolution = resolve_target(package_init, importer);
return add_child_targets(py_files, importer, resolution, package, names);
if let Some(names) = names {
return resolve_absolute_from(
py_files,
module_index
.roots
.iter()
.chain(&fallback_index.roots)
.cloned()
.collect(),
importer,
module,
names,
classify_external(module, specifier),
);
}
if let Some(target) = module_index
.modules
.get(module)
.or_else(|| fallback_index.modules.get(module))
{
return resolve_target(target.clone(), importer);
}
classify_external(module, specifier)
}

fn resolve_absolute_from(
py_files: &HashSet<String>,
mut roots: Vec<String>,
importer: &str,
module: &str,
names: &str,
fallback: Resolution,
) -> Resolution {
let (parents, name) = module.rsplit_once('.').unwrap_or(("", module));
for parent in parents.split('.').filter(|p| !p.is_empty()) {
if !descend_into_package(py_files, &mut roots, parent) {
return fallback;
}
}
if let Some(target) = first_concrete_module(py_files, &roots, name) {
return match target {
ConcreteModule::Package(directory) => {
let resolution = resolve_target(init_path_for(&directory), importer);
add_child_targets(py_files, importer, resolution, &directory, names)
}
ConcreteModule::File(path) => resolve_target(path, importer),
};
}
let directories = roots
.into_iter()
.map(|root| module_path(&root, name))
.collect();
resolve_namespace_children(py_files, directories, importer, names, fallback)
}

fn descend_into_package(py_files: &HashSet<String>, roots: &mut Vec<String>, name: &str) -> bool {
match first_concrete_module(py_files, roots, name) {
Some(ConcreteModule::Package(directory)) => {
*roots = vec![directory];
true
}
Some(ConcreteModule::File(_)) => false,
None => {
for root in roots {
*root = module_path(root, name);
}
true
}
return resolve_target(target.clone(), importer);
}
}

enum ConcreteModule {
Package(String),
File(String),
}

fn first_concrete_module(
py_files: &HashSet<String>,
roots: &[String],
name: &str,
) -> Option<ConcreteModule> {
roots.iter().find_map(|root| {
let directory = module_path(root, name);
if py_files.contains(&init_path_for(&directory)) {
return Some(ConcreteModule::Package(directory));
}
let file = format!("{directory}.py");
py_files
.contains(&file)
.then_some(ConcreteModule::File(file))
})
}

fn module_path(root: &str, name: &str) -> String {
if root.is_empty() {
name.to_owned()
} else {
format!("{root}/{name}")
}
}

fn resolve_namespace_children(
py_files: &HashSet<String>,
directories: Vec<String>,
importer: &str,
names: &str,
fallback: Resolution,
) -> Resolution {
let mut children: Vec<_> = names
.split(',')
.flat_map(|name| {
directories
.iter()
.filter_map(move |directory| find_child_module(py_files, directory, name))
})
.collect();
if children.is_empty() {
return fallback;
}
children.sort_unstable();
children.dedup();
children.retain(|target| target != importer);
if children.is_empty() {
Resolution::Builtin
} else {
Resolution::Resolved(children)
}
}

fn classify_external(module: &str, specifier: &str) -> Resolution {
let top = module.split('.').next().unwrap_or("");
if top.is_empty() {
return Resolution::Unresolved(format!("empty Python import specifier {specifier:?}"));
Expand Down
Loading