#![forbid(unsafe_code)]
use std::fs;
use std::path::{Path, PathBuf};
fn workspace_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
const HARD_BUDGET: usize = 600;
const DECLARED_EXCEPTIONS: &[(&str, usize, &str)] = &[
(
"ssh/sftp_session.rs",
810,
"one cohesive SFTP protocol implementation; splitting moves the wire \
sequence across files without reducing real coupling",
),
(
"errors.rs",
754,
"single error taxonomy; the enum and its exit-code/class/retryable/\
suggestion tables must stay exhaustive in one place",
),
(
"secrets.rs",
748,
"at-rest encryption; splitting the key lifecycle widens the surface that \
touches key material",
),
(
"cli/mod.rs",
712,
"clap derive definition; the argument surface is one declarative unit",
),
(
"vps/model.rs",
699,
"record model plus serde migration; wire schema v3 dual-read belongs with \
the fields it reads",
),
(
"cli/dispatch.rs",
620,
"dispatch table; one match over the whole verb surface",
),
];
const TEST_MODULE_BUDGET: usize = 600;
const DECLARED_TEST_EXCEPTIONS: &[(&str, usize, &str)] = &[(
"tunnel/tests.rs",
729,
"mirrors the tunnel surface it exercises; forward, reverse and socks cases \
share one fixture harness that splitting would have to duplicate",
)];
const MAX_TOO_MANY_ARGS_ALLOWS: usize = 2;
fn walk_rs(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = fs::read_dir(dir) else {
return;
};
for ent in rd.flatten() {
let p = ent.path();
if p.is_dir() {
walk_rs(&p, out);
} else if p.extension().and_then(|s| s.to_str()) == Some("rs") {
out.push(p);
}
}
}
fn all_sources() -> Vec<(String, String)> {
let root = workspace_root().join("src");
let mut files = Vec::new();
walk_rs(&root, &mut files);
files
.into_iter()
.filter_map(|p| {
let rel = p
.strip_prefix(&root)
.ok()?
.to_string_lossy()
.replace('\\', "/");
Some((rel, fs::read_to_string(&p).ok()?))
})
.collect()
}
fn is_test_module(rel: &str) -> bool {
rel.ends_with("tests.rs")
}
fn product_sources() -> Vec<(String, String)> {
all_sources()
.into_iter()
.filter(|(rel, _)| !is_test_module(rel))
.collect()
}
fn test_module_sources() -> Vec<(String, String)> {
all_sources()
.into_iter()
.filter(|(rel, _)| is_test_module(rel))
.collect()
}
fn declared_cap(ledger: &[(&str, usize, &str)], rel: &str) -> Option<usize> {
ledger
.iter()
.find(|(p, _, _)| *p == rel)
.map(|(_, cap, _)| *cap)
}
fn inline_test_module_start(lines: &[&str]) -> Option<usize> {
lines.iter().enumerate().find_map(|(i, l)| {
if !l.trim().starts_with("#[cfg(test)]") {
return None;
}
let declares_mod = lines[i + 1..]
.iter()
.map(|next| next.trim())
.find(|next| !next.is_empty() && !next.starts_with("#[") && !next.starts_with("//"))
.is_some_and(|next| next.starts_with("mod ") || next.starts_with("pub mod "));
declares_mod.then_some(i)
})
}
fn item_is_cfg_test(lines: &[&str], idx: usize) -> bool {
let mut i = idx;
while i > 0 {
i -= 1;
let t = lines[i].trim();
if t.starts_with("#[cfg(test)]") {
return true;
}
if t.starts_with("#[") || t.starts_with("//") {
continue;
}
return false;
}
false
}
#[test]
fn no_product_file_exceeds_its_budget() {
let mut undeclared = Vec::new();
let mut grown = Vec::new();
for (rel, text) in product_sources() {
let lines = text.lines().count();
match declared_cap(DECLARED_EXCEPTIONS, &rel) {
Some(cap) if lines > cap => {
grown.push(format!("{rel}: {lines} lines, frozen at {cap}"));
}
Some(_) => {}
None if lines > HARD_BUDGET => {
undeclared.push(format!("{rel}: {lines} lines"));
}
None => {}
}
}
assert!(
undeclared.is_empty(),
"these files cross the {HARD_BUDGET}-line budget and are not declared \
exceptions:\n {}\n\
Split them by responsibility (see `src/vps/exec_ops/` and `src/sftp/` \
for the pattern). Adding an entry to DECLARED_EXCEPTIONS instead is a \
decision that must be argued in the reason field, not a formality.",
undeclared.join("\n ")
);
assert!(
grown.is_empty(),
"these declared exceptions grew past their frozen cap:\n {}\n\
The ledger ratchets down only. Reduce the file, or split it.",
grown.join("\n ")
);
}
#[test]
fn no_test_module_exceeds_its_budget() {
let mut undeclared = Vec::new();
let mut grown = Vec::new();
for (rel, text) in test_module_sources() {
let lines = text.lines().count();
match declared_cap(DECLARED_TEST_EXCEPTIONS, &rel) {
Some(cap) if lines > cap => {
grown.push(format!("{rel}: {lines} lines, frozen at {cap}"));
}
Some(_) => {}
None if lines > TEST_MODULE_BUDGET => {
undeclared.push(format!("{rel}: {lines} lines"));
}
None => {}
}
}
assert!(
undeclared.is_empty(),
"these test modules cross the {TEST_MODULE_BUDGET}-line budget and are \
not declared exceptions:\n {}\n\
Split them by the behaviour they cover. A test module gets the same \
budget as product code because it is read the same way.",
undeclared.join("\n ")
);
assert!(
grown.is_empty(),
"these declared test-module exceptions grew past their frozen cap:\n {}\n\
The ledger ratchets down only. Reduce the module, or split it.",
grown.join("\n ")
);
}
fn assert_ledger_is_current(
label: &str,
ledger: &[(&str, usize, &str)],
budget: usize,
sources: &[(String, String)],
) {
let mut missing = Vec::new();
let mut no_longer_needed = Vec::new();
let mut slack = Vec::new();
for (path, cap, reason) in ledger {
assert!(
!reason.trim().is_empty(),
"{path} is declared without a reason"
);
assert!(
*cap > budget,
"{path} is capped at {cap}, at or below the {budget}-line \
budget — it does not need an exception at all"
);
match sources.iter().find(|(rel, _)| rel == path) {
None => missing.push((*path).to_string()),
Some((_, text)) => {
let lines = text.lines().count();
if lines <= budget {
no_longer_needed.push(format!("{path}: now {lines} lines"));
} else if cap.saturating_sub(lines) > MAX_LEDGER_SLACK {
slack.push(format!(
"{path}: capped at {cap} but measures {lines} \
({} lines of unused credit)",
cap - lines
));
}
}
}
}
assert!(
missing.is_empty(),
"these entries in {label} name files that are not in the population it \
measures (deleted, renamed, or charged to the other ledger):\n {}",
missing.join("\n ")
);
assert!(
no_longer_needed.is_empty(),
"these files now fit the {budget}-line budget — delete their entries \
from {label}:\n {}",
no_longer_needed.join("\n ")
);
assert!(
slack.is_empty(),
"these entries in {label} carry more than {MAX_LEDGER_SLACK} lines of unused \
credit — lower each cap to the measured size:\n {}\n\
A frozen cap that outruns its file is the same permit this ledger exists to \
refuse, only granted in advance instead of in arrears.",
slack.join("\n ")
);
}
const MAX_LEDGER_SLACK: usize = 8;
#[test]
fn the_exception_ledger_contains_no_stale_entries() {
assert_ledger_is_current(
"DECLARED_EXCEPTIONS",
DECLARED_EXCEPTIONS,
HARD_BUDGET,
&product_sources(),
);
}
#[test]
fn the_test_module_ledger_contains_no_stale_entries() {
assert_ledger_is_current(
"DECLARED_TEST_EXCEPTIONS",
DECLARED_TEST_EXCEPTIONS,
TEST_MODULE_BUDGET,
&test_module_sources(),
);
}
#[test]
fn coupling_lint_suppressions_stay_within_budget_and_are_justified() {
let mut sites = Vec::new();
let mut unjustified = Vec::new();
for (rel, text) in product_sources() {
let lines: Vec<&str> = text.lines().collect();
let inline_tests = inline_test_module_start(&lines);
for (i, line) in lines.iter().enumerate() {
if !line.contains("allow(clippy::too_many_arguments)") {
continue;
}
if inline_tests.is_some_and(|start| i >= start) || item_is_cfg_test(&lines, i) {
continue;
}
sites.push(format!("{rel}:{}", i + 1));
let inline = line.contains("//");
let above = i
.checked_sub(1)
.and_then(|j| lines.get(j))
.is_some_and(|prev| prev.trim_start().starts_with("//"));
if !inline && !above {
unjustified.push(format!("{rel}:{}", i + 1));
}
}
}
assert!(
sites.len() <= MAX_TOO_MANY_ARGS_ALLOWS,
"{} suppressions of `too_many_arguments` (budget {MAX_TOO_MANY_ARGS_ALLOWS}):\n {}\n\
Group the parameters into a named context struct instead — see \
`crate::vps::AuthOverrides` and `crate::tunnel::ServeContext`.",
sites.len(),
sites.join("\n ")
);
assert!(
unjustified.is_empty(),
"these suppressions carry no comment explaining why the flat shape is \
correct:\n {}",
unjustified.join("\n ")
);
}
#[test]
fn no_deferred_constant_markers_remain() {
let offenders: Vec<String> = all_sources()
.into_iter()
.flat_map(|(rel, text)| {
text.lines()
.enumerate()
.filter(|(_, l)| l.contains("TODO(constants)"))
.map(|(i, l)| format!("{rel}:{}: {}", i + 1, l.trim()))
.collect::<Vec<_>>()
})
.collect();
assert!(
offenders.is_empty(),
"deferred constant markers found — move the value into \
`src/constants.rs`:\n {}",
offenders.join("\n ")
);
}
#[test]
fn scp_constants_are_centralized_and_used() {
let constants =
fs::read_to_string(workspace_root().join("src/constants.rs")).expect("read constants.rs");
assert!(
constants.contains("SCP_IO_CHUNK") && constants.contains("SCP_HEADER_MAX_BYTES"),
"both SCP constants must be declared in crate::constants"
);
for rel in ["src/ssh/client_real_scp.rs", "src/ssh/scp_wire.rs"] {
let text = fs::read_to_string(workspace_root().join(rel)).expect("read scp source");
assert!(
!text.contains("const SCP_IO_CHUNK") && !text.contains("const SCP_HEADER_MAX_BYTES"),
"{rel} must not redeclare an SCP constant locally"
);
}
}