Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions crates/fensu-native/src/rules/_helpers/layers/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,12 @@ fn current_ownership_position(
) -> (usize, Option<String>) {
context.ownership_offset.map_or_else(
|| (parts.len(), None),
|offset| (1 + offset, context.ownership_root.clone()),
|offset| {
(
context.package_parts().len().max(1) + offset,
context.ownership_root.clone(),
)
},
)
}

Expand All @@ -248,18 +253,15 @@ fn ownership_position(context: &NativeRuleContext, parts: &[String]) -> (usize,
} else {
Path::new(&context.repo_root).join(configured_source)
};
let Some(package) = source.file_name().and_then(|value| value.to_str()) else {
let Some(package) = source_package(context, &source, parts) else {
continue;
};
if parts.first().map(String::as_str) != Some(package) {
continue;
}
for ownership_root in &context.ownership_roots {
let ownership = Path::new(ownership_root);
let Ok(relative) = ownership.strip_prefix(&source) else {
continue;
};
let mut prefix = vec![package.to_owned()];
let mut prefix = package.clone();
prefix.extend(
relative
.components()
Expand Down Expand Up @@ -356,7 +358,7 @@ pub(crate) fn normalized_targets(
}

fn current_module_parts(context: &NativeRuleContext) -> Vec<String> {
let mut parts = vec![context.package_name.clone()];
let mut parts = context.package_parts();
parts.extend(context.relative_parts.iter().cloned());
if let Some(last) = parts.last_mut() {
*last = last.strip_suffix(".py").unwrap_or(last).to_owned();
Expand All @@ -371,21 +373,31 @@ fn file_name(context: &NativeRuleContext) -> &str {
context.relative_parts.last().map_or("", String::as_str)
}

fn runtime_root<'a>(context: &'a NativeRuleContext, package: &str) -> Option<&'a str> {
context.scope_roots.iter().find_map(|(scope, root)| {
(scope == ROOT_SCOPE && root.rsplit('/').next() == Some(package)).then_some(root.as_str())
})
/// The package segments `source` holds when `parts` start with them.
fn source_package(
context: &NativeRuleContext,
source: &Path,
parts: &[String],
) -> Option<Vec<String>> {
let package: Vec<String> = context.package_parts();
let folders: Vec<String> = source
.components()
.map(|part| part.as_os_str().to_string_lossy().into_owned())
.collect();
if !package.is_empty() && folders.ends_with(&package) && parts.starts_with(&package) {
return Some(package);
}
let name: String = folders.last()?.clone();
(parts.first() == Some(&name)).then(|| vec![name])
}

fn module_init_path(context: &NativeRuleContext, parts: &[String]) -> Option<String> {
let root = runtime_root(context, parts.first()?)?;
let parent = root.rsplit_once('/').map_or("", |item| item.0);
let parent = context.package_root_parent(ROOT_SCOPE, parts)?;
Some(format!("{parent}/{}/{INIT_FILE_NAME}", parts.join("/")))
}

fn module_file_path(context: &NativeRuleContext, parts: &[String]) -> Option<String> {
let root = runtime_root(context, parts.first()?)?;
let parent = root.rsplit_once('/').map_or("", |item| item.0);
let parent = context.package_root_parent(ROOT_SCOPE, parts)?;
Some(format!("{parent}/{}.py", parts.join("/")))
}

Expand Down
8 changes: 4 additions & 4 deletions crates/fensu-native/src/rules/_helpers/layers/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn internal_public_surface_faults(
}
imports
.iter()
.filter(|row| imports_public_surface(row, &context.package_name))
.filter(|row| imports_public_surface(row, context))
.map(|row| location_fault(code, row.line, row.column))
.collect()
}
Expand Down Expand Up @@ -148,13 +148,13 @@ fn collect_import_faults(
(helper_module_aliases, faults)
}

fn imports_public_surface(row: &ImportRow, package_name: &str) -> bool {
fn imports_public_surface(row: &ImportRow, context: &NativeRuleContext) -> bool {
if row.from_import {
row.relative_level == 0 && row.module_parts.as_slice() == [package_name]
row.relative_level == 0 && row.module_parts == context.package_parts()
} else {
row.aliases
.iter()
.any(|alias| alias.imported_name == package_name)
.any(|alias| alias.imported_name == context.package_name)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,13 @@ pub(crate) fn plan_project_queries(
}
}
if selected.contains(PUBLIC_FACADE_IMPORT_DIRECTION_CODE) && context.scope == ROOT_SCOPE {
let package: Vec<String> = context.package_parts();
for target in module_targets(program, context) {
if target.len() == PUBLIC_FACADE_MODULE_PARTS
&& target.first() == Some(&context.package_name)
if target.len() == package.len() + PUBLIC_FACADE_MODULE_PARTS - 1
&& target.starts_with(&package)
{
let mut path = scope_root(context);
path.push(format!("{}.py", target[1]));
path.push(format!("{}.py", target[package.len()]));
queries.push(query(
"public_facade",
&path.join("/"),
Expand Down Expand Up @@ -210,14 +211,6 @@ fn scope_root(context: &NativeRuleContext) -> Vec<String> {
.collect()
}

fn configured_roots<'a>(context: &'a NativeRuleContext, scope: &str) -> Vec<&'a str> {
context
.scope_roots
.iter()
.filter_map(|(kind, path)| (kind == scope).then_some(path.as_str()))
.collect()
}

fn test_layout_area_path(context: &NativeRuleContext) -> Option<String> {
if context.scope != TEST_SCOPE
|| matches!(file_name(context), INIT_FILE | "conftest.py")
Expand Down Expand Up @@ -309,7 +302,7 @@ fn normalized_import_targets(row: &ImportRow, context: &NativeRuleContext) -> Ve
}

fn module_parts(context: &NativeRuleContext) -> Vec<String> {
let mut parts = vec![context.package_name.clone()];
let mut parts = context.package_parts();
parts.extend(context.relative_parts.iter().cloned());
if let Some(last) = parts.last_mut() {
*last = last.strip_suffix(".py").unwrap_or(last).to_owned();
Expand All @@ -323,23 +316,13 @@ fn module_parts(context: &NativeRuleContext) -> Vec<String> {
parts
}

fn runtime_root<'a>(context: &'a NativeRuleContext, package: &str) -> Option<&'a str> {
configured_roots(context, "root")
.into_iter()
.find(|root| root.rsplit('/').next() == Some(package))
}

fn module_init_path(context: &NativeRuleContext, parts: &[String]) -> Option<String> {
let package = parts.first()?;
let root = runtime_root(context, package)?;
let parent = root.rsplit_once('/').map_or("", |item| item.0);
let parent = context.package_root_parent(ROOT_SCOPE, parts)?;
Some(format!("{parent}/{}/{INIT_FILE}", parts.join("/")))
}

fn module_file_path(context: &NativeRuleContext, parts: &[String]) -> Option<String> {
let package = parts.first()?;
let root = runtime_root(context, package)?;
let parent = root.rsplit_once('/').map_or("", |item| item.0);
let parent = context.package_root_parent(ROOT_SCOPE, parts)?;
Some(format!("{parent}/{}.py", parts.join("/")))
}

Expand Down
9 changes: 6 additions & 3 deletions crates/fensu-native/src/rules/_helpers/roles/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,16 +133,19 @@ fn import_targets(
}

fn public_facade_path(target: &[String], context: &NativeRuleContext) -> Option<String> {
if target.len() != PUBLIC_FACADE_MODULE_PARTS || target.first()? != &context.package_name {
let package: Vec<String> = context.package_parts();
if target.len() != package.len() + PUBLIC_FACADE_MODULE_PARTS - 1
|| !target.starts_with(&package)
{
return None;
}
let mut path = scope_root_parts(context);
path.push(format!("{}.py", target[1]));
path.push(format!("{}.py", target[package.len()]));
Some(path.join("/"))
}

fn current_module_parts(context: &NativeRuleContext) -> Vec<String> {
let mut parts = vec![context.package_name.clone()];
let mut parts = context.package_parts();
parts.extend(context.relative_parts.iter().cloned());
if let Some(last) = parts.last_mut() {
*last = last.strip_suffix(PYTHON_SUFFIX).unwrap_or(last).to_owned();
Expand Down
28 changes: 28 additions & 0 deletions crates/fensu-native/src/rules/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,34 @@ impl NativeRuleContext {
self.ownership_offset
}

/// The dotted package name's segments: `python.nodes` is `["python", "nodes"]`.
pub fn package_parts(&self) -> Vec<String> {
self.package_name
.split('.')
.filter(|part| !part.is_empty())
.map(str::to_owned)
.collect()
}

/// The folder above the `scope` root whose last folders spell the start of `parts`.
pub fn package_root_parent(&self, scope: &str, parts: &[String]) -> Option<String> {
let package: Vec<String> = self.package_parts();
let depth: usize = if !package.is_empty() && parts.starts_with(&package) {
package.len()
} else {
1
};
let suffix: String = parts.get(..depth)?.join("/");
self.scope_roots.iter().find_map(|(kind, root)| {
let parent: &str = if *root == suffix {
""
} else {
root.strip_suffix(&suffix)?.strip_suffix('/')?
};
(kind == scope).then(|| parent.to_owned())
})
}

pub fn observation(&self, query: &NativeProjectQuery) -> &[String] {
self.observations
.get(&query.key())
Expand Down
2 changes: 2 additions & 0 deletions crates/fensu-native/tests/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
mod helpers;
#[path = "rules/test_contracts.rs"]
mod test_contracts;
#[path = "rules/test_dotted_package.rs"]
mod test_dotted_package;
#[path = "rules/test_types.rs"]
mod test_types;
85 changes: 85 additions & 0 deletions crates/fensu-native/tests/rules/test_dotted_package.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! A dotted package name resolves imports by its leading module segments.

use std::collections::HashMap;

use fensu_facts::extension::models::ProgramHandle;
use fensu_native::{
evaluate_core_rules, plan_core_rule_queries, NativeProjectPlane, NativeRuleContext,
};
use ruff_python_ast::PythonVersion;

use crate::test_types::DottedPackageTestCase;

const CODE: &str = "FFL104";

#[test]
fn given_dotted_package_when_importing_private_main_then_domains_are_read_below_the_package() {
let test_cases = [
DottedPackageTestCase {
description: "another domain's private main entry is rejected",
relative_parts: &["inventory", "_helpers", "use.py"],
source: "from app.nodes.orders.billing.main._calculate import calculate\n",
expected_query_path: "src/app/nodes/orders/billing/main/_calculate.py",
expected_messages: &[
"import 'app.nodes.orders.billing.main._calculate' reaches a domain-private main \
entry",
],
},
DottedPackageTestCase {
description: "the same domain's private main entry is allowed",
relative_parts: &["orders", "shipping", "_helpers", "use.py"],
source: "from app.nodes.orders.billing.main._calculate import calculate\n",
expected_query_path: "src/app/nodes/orders/billing/main/_calculate.py",
expected_messages: &[],
},
];
let version = PythonVersion {
major: 3,
minor: 12,
};
for test_case in &test_cases {
let program = ProgramHandle::parse_many(vec![test_case.source.to_owned()], version)
.pop()
.flatten()
.expect("fixture source parses");
let codes = vec![CODE.to_owned()];
let mut context = NativeRuleContext {
scope: "root".to_owned(),
package_name: "app.nodes".to_owned(),
relative_parts: test_case
.relative_parts
.iter()
.map(|part| (*part).to_owned())
.collect(),
repository_path: format!("src/app/nodes/{}", test_case.relative_parts.join("/")),
scope_roots: vec![("root".to_owned(), "src/app/nodes".to_owned())],
ownership_root: Some("/repo/src/app/nodes".to_owned()),
ownership_roots: vec!["/repo/src/app/nodes".to_owned()],
repo_root: "/repo".to_owned(),
..NativeRuleContext::default()
};
let queries = plan_core_rule_queries(&program, &codes, &context);
let paths: Vec<&str> = queries.iter().map(|query| query.path.as_str()).collect();
assert_eq!(
paths,
vec![test_case.expected_query_path],
"{}",
test_case.description
);
context.observations = queries
.iter()
.map(|query| (query.key(), vec!["true".to_owned()]))
.collect::<HashMap<_, _>>();
let project = NativeProjectPlane::new(Vec::new(), Vec::new());
let messages: Vec<String> = evaluate_core_rules(&program, &codes, &context, &project)
.expect("rules evaluate")
.into_iter()
.filter_map(|fault| fault.message)
.collect();
assert_eq!(
messages, test_case.expected_messages,
"{}",
test_case.description
);
}
}
8 changes: 8 additions & 0 deletions crates/fensu-native/tests/rules/test_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,11 @@ pub(crate) fn default_test_scopes() -> Vec<String> {
.map(str::to_owned)
.collect()
}

pub(crate) struct DottedPackageTestCase {
pub(crate) description: &'static str,
pub(crate) relative_parts: &'static [&'static str],
pub(crate) source: &'static str,
pub(crate) expected_query_path: &'static str,
pub(crate) expected_messages: &'static [&'static str],
}
Loading