diff options
| -rw-r--r-- | src/db/candidates.rs | 14 | ||||
| -rw-r--r-- | src/db/invariants.rs | 1 | ||||
| -rw-r--r-- | src/db/migrations.rs | 1 | ||||
| -rw-r--r-- | src/db/model/build_state.rs | 4 | ||||
| -rw-r--r-- | src/db/model/state.rs | 28 | ||||
| -rw-r--r-- | src/db/packages.rs | 1 | ||||
| -rw-r--r-- | src/db/subscriptions.rs | 1 | ||||
| -rw-r--r-- | src/fetch.rs | 2 | ||||
| -rw-r--r-- | src/http/mod.rs | 4 | ||||
| -rw-r--r-- | src/http/render.rs | 2 | ||||
| -rw-r--r-- | src/ops.rs | 4 | ||||
| -rw-r--r-- | src/pkginfo.rs | 2 | ||||
| -rw-r--r-- | src/review/approve.rs | 1 | ||||
| -rw-r--r-- | src/sandbox/kata.rs | 2 | ||||
| -rw-r--r-- | src/shims/mod.rs | 13 | ||||
| -rw-r--r-- | src/time.rs | 3 | ||||
| -rw-r--r-- | src/usecase/detect.rs | 1 | ||||
| -rw-r--r-- | src/usecase/maintenance.rs | 1 | ||||
| -rw-r--r-- | src/usecase/reviews.rs | 1 | ||||
| -rw-r--r-- | src/watch/detect.rs | 2 | ||||
| -rw-r--r-- | src/watch/mirror.rs | 2 | ||||
| -rw-r--r-- | src/watch/upstream.rs | 10 | ||||
| -rw-r--r-- | tests/architecture-budget.json | 150 | ||||
| -rw-r--r-- | tests/architecture.rs | 28 | ||||
| -rwxr-xr-x | tools/arch-census.py | 67 |
25 files changed, 212 insertions, 133 deletions
diff --git a/src/db/candidates.rs b/src/db/candidates.rs index e2f011c..411d60b 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -53,7 +53,7 @@ impl NewCandidate { } #[derive(Debug, Clone)] -pub struct OpenReview { +pub(crate) struct OpenReview { pub id: i64, pub identity_hash: String, pub viewed_at: Option<String>, @@ -69,7 +69,7 @@ impl OpenReview { // ------------------------------------------------------------------ in-tx -- #[derive(Debug, Clone)] -pub struct ReviewSubject { +pub(crate) struct ReviewSubject { pub id: i64, pub pkgbase_id: i64, pub state: CandidateState, @@ -78,14 +78,13 @@ pub struct ReviewSubject { pub base_release_id: Option<i64>, pub current_base_release_id: Option<i64>, pub risk_level: String, - pub pkgbase: String, } -pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Option<ReviewSubject>> { +pub(crate) fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Option<ReviewSubject>> { Ok(tx .query_row( "SELECT c.id, c.pkgbase_id, c.state, c.identity_hash, c.diff_digest, c.base_release_id, - p.current_accepted_release_id, c.risk_level, p.name + p.current_accepted_release_id, c.risk_level FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id WHERE c.id = ?1", params![candidate_id], @@ -99,7 +98,6 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti base_release_id: r.get(5)?, current_base_release_id: r.get(6)?, risk_level: r.get(7)?, - pkgbase: r.get(8)?, }) }, ) @@ -151,7 +149,7 @@ pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> { }) } -pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenReview>> { +pub(crate) fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenReview>> { Ok(tx .query_row( "SELECT id, identity_hash, viewed_at, revision FROM candidate @@ -169,7 +167,7 @@ pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenRevie .optional()?) } -pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result<i64> { +pub(crate) fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result<i64> { let revision = open.revision + 1; tx.execute( "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4, diff --git a/src/db/invariants.rs b/src/db/invariants.rs index e2648fa..e9e133f 100644 --- a/src/db/invariants.rs +++ b/src/db/invariants.rs @@ -31,6 +31,7 @@ pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { #[derive(Debug, Clone)] +// Unbuilt stays `pub`: the attention row `approved_but_unbuilt` returns to the web UI and to tests/crash.rs. pub struct Unbuilt { pub pkgbase: String, pub approved: String, diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 015610a..7adc69c 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -1,3 +1,4 @@ +// Migration stays `pub`: the row type of `MIGRATIONS`, which is `pub` only under `test-support`; production walks the table through `db::migrate` without naming it. pub struct Migration { pub version: u32, pub name: &'static str, diff --git a/src/db/model/build_state.rs b/src/db/model/build_state.rs index d081bca..37eee79 100644 --- a/src/db/model/build_state.rs +++ b/src/db/model/build_state.rs @@ -66,7 +66,7 @@ impl BuildState { } } - pub fn predecessors(to: BuildState) -> Vec<&'static str> { + pub(crate) fn predecessors(to: BuildState) -> Vec<&'static str> { BuildState::ALL .iter() .filter(|from| from.can_transition(to)) @@ -143,7 +143,7 @@ impl StepState { } } - pub fn predecessors(to: StepState) -> Vec<&'static str> { + pub(crate) fn predecessors(to: StepState) -> Vec<&'static str> { StepState::ALL .iter() .filter(|from| from.can_transition(to)) diff --git a/src/db/model/state.rs b/src/db/model/state.rs index dcc9b84..18860ff 100644 --- a/src/db/model/state.rs +++ b/src/db/model/state.rs @@ -118,20 +118,6 @@ impl ReleaseState { pub fn parse(s: &str) -> Option<ReleaseState> { ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) } - - /// NOTE: nothing consults this table today — release transitions are - /// enforced elsewhere. Left `pub` and dead rather than quietly deleted - /// or quietly wired up; it is a disposition-table decision. - pub fn can_transition(&self, to: ReleaseState) -> bool { - use ReleaseState::*; - if *self == to { - return true; - } - match self { - Published => matches!(to, Withdrawn | FailedUnbuilt), - Withdrawn | FailedUnbuilt => false, - } - } } impl std::fmt::Display for ReleaseState { @@ -199,20 +185,6 @@ impl SubscriptionState { pub fn parse(text: &str) -> Option<SubscriptionState> { SubscriptionState::ALL.iter().copied().find(|st| st.as_str() == text) } - - /// NOTE: dead in the same way as `ReleaseState::can_transition`. - pub fn can_transition(&self, to: SubscriptionState) -> bool { - use SubscriptionState::*; - if *self == to { - return true; - } - match self { - Active => matches!(to, Paused | Orphaned | Removed), - Paused => matches!(to, Active | Orphaned | Removed), - Orphaned => matches!(to, Active | Removed), - Removed => false, - } - } } impl std::fmt::Display for SubscriptionState { diff --git a/src/db/packages.rs b/src/db/packages.rs index 0a302b0..247c328 100644 --- a/src/db/packages.rs +++ b/src/db/packages.rs @@ -6,6 +6,7 @@ use crate::error::Result; // ---------------------------------------------------------------- package -- #[derive(Debug, Clone)] +// PackageRow stays `pub`: what `index_packages` hands back to `http`, the publish step and the `aur-build` binary, which bind it without naming it. pub struct PackageRow { pub id: i64, pub release_id: i64, diff --git a/src/db/subscriptions.rs b/src/db/subscriptions.rs index 947a205..fc17de3 100644 --- a/src/db/subscriptions.rs +++ b/src/db/subscriptions.rs @@ -7,6 +7,7 @@ use crate::time; // ------------------------------------------------------------- subscriptions -- #[derive(Debug, Clone)] +// Subscription stays `pub`: what `get_subscription` and `list_subscriptions` hand back to `watch`, `usecase`, the binary and tests/detect.rs. pub struct Subscription { pub id: i64, pub pkgbase: String, diff --git a/src/fetch.rs b/src/fetch.rs index bcbdbda..fd9a661 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use crate::error::{Error, Result}; -pub enum Body { +pub(crate) enum Body { File(std::fs::File), Http(Box<dyn Read + Send>), } diff --git a/src/http/mod.rs b/src/http/mod.rs index 60a1f2e..8a00745 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -28,10 +28,10 @@ impl Req { pub(crate) fn form(&self) -> &[(String, String)] { &self.form_pairs } - pub fn form_get(&self, key: &str) -> Option<String> { + pub(crate) fn form_get(&self, key: &str) -> Option<String> { self.form_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) } - pub fn query_get(&self, key: &str) -> Option<String> { + pub(crate) fn query_get(&self, key: &str) -> Option<String> { self.query_pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) } /// Reading a cookie off a request is internal plumbing; the auth tests need it in order to forge one. diff --git a/src/http/render.rs b/src/http/render.rs index d513c2a..6e1083b 100644 --- a/src/http/render.rs +++ b/src/http/render.rs @@ -60,7 +60,7 @@ impl Page { gated: false, } } - pub fn flash(mut self, msg: String, err: bool) -> Self { + pub(crate) fn flash(mut self, msg: String, err: bool) -> Self { self.flash = msg; self.has_flash = true; self.flash_err = err; @@ -230,7 +230,7 @@ fn dir_bytes(path: &Path) -> u64 { total } -pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> { +pub(crate) fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> { let keep = keep.max(1); let pkgbases = db::pkgbase_release_pointers(db)?; @@ -259,7 +259,7 @@ pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>) } #[derive(Debug, Clone)] -pub struct EvictPlan { +pub(crate) struct EvictPlan { pub release_id: i64, } diff --git a/src/pkginfo.rs b/src/pkginfo.rs index 2cf449e..470ccf7 100644 --- a/src/pkginfo.rs +++ b/src/pkginfo.rs @@ -1,6 +1,7 @@ use std::io::Read; #[derive(Debug, Clone, Default, PartialEq, Eq)] +// PkgInfo stays `pub`: what `parse_pkginfo` answers with; `pipeline`, `shims` and tests/world.rs read its fields, never its name. pub struct PkgInfo { pub name: String, pub version: String, @@ -19,6 +20,7 @@ pub struct PkgInfo { } #[derive(Debug, Clone, PartialEq, Eq)] +// Installed stays `pub`: what `parse_installed` answers with, read line by line by `pipeline` and tests/world.rs. pub struct Installed { pub name: String, pub version: String, diff --git a/src/review/approve.rs b/src/review/approve.rs index e1150b3..c5b2f07 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -133,6 +133,7 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> } #[derive(Debug)] +// BulkItem stays `pub`: one outcome of `approve::bulk`, which tests/approve.rs drives directly. pub struct BulkItem { pub candidate: Option<CandidateRow>, pub outcome: BulkOutcome, diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 1f24ce7..84a79e4 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -18,6 +18,7 @@ use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; #[derive(Debug, Clone)] +// ProvisionRequest stays `pub`: the argument of `Provisioner::provision`, the trait the public `LocalAgentProvisioner` implements. pub struct ProvisionRequest { pub sandbox_id: String, pub profile: String, @@ -27,6 +28,7 @@ pub struct ProvisionRequest { pub image: String, } +// Provisioner stays `pub`: implemented by the test-gated public `LocalAgentProvisioner`; a private trait on a public impl is E0445. pub trait Provisioner: Send + Sync { fn provision(&self, req: &ProvisionRequest) -> Result<()>; fn reclaim(&self, sandbox_id: &str) -> Result<()>; diff --git a/src/shims/mod.rs b/src/shims/mod.rs index a877739..8e6e231 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -6,6 +6,7 @@ use crate::hash; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] +// FakePackage stays `pub`: the whole `shims` module is `test-support`-gated, so a release build never compiles it. pub struct FakePackage { pub name: String, pub version: String, @@ -41,7 +42,7 @@ impl Default for FakePackage { } impl FakePackage { - pub fn split_version(&self) -> (String, String) { + pub(crate) fn split_version(&self) -> (String, String) { match self.version.rsplit_once('-') { Some((v, r)) => (v.to_string(), r.to_string()), None => (self.version.clone(), "1".into()), @@ -51,6 +52,7 @@ impl FakePackage { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] +// FakeInstalled stays `pub`: the whole `shims` module is `test-support`-gated, so a release build never compiles it. pub struct FakeInstalled { pub name: String, pub version: String, @@ -59,6 +61,7 @@ pub struct FakeInstalled { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] +// Manifest stays `pub`: returned by `manifest()`, which the shim tests read; the module is `test-support`-gated. pub struct Manifest { pub name: String, pub build: String, @@ -240,7 +243,7 @@ pub(crate) fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String emit_packages(m, "makechrootpkg", wants_sig) } -pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, String> { +pub(crate) fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, String> { for l in &m.log_lines { println!("{l}"); } @@ -320,7 +323,7 @@ fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec<FakePackage> { } } -pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, String> { +pub(crate) fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, String> { let (pkgver, pkgrel) = p.split_version(); let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); let path = dir.join(&filename); @@ -502,7 +505,7 @@ fn installed_db() -> Option<std::path::PathBuf> { std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } -pub const DB_SUFFIXES: [&str; 5] = [ +pub(crate) const DB_SUFFIXES: [&str; 5] = [ ".db.tar", ".db.tar.gz", ".db.tar.zst", @@ -535,7 +538,7 @@ fn valid_db_arg_impl(p: &Path) -> bool { .any(|sfx| name.ends_with(sfx)) } -pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { +pub(crate) fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { let mut positional: Vec<&String> = Vec::new(); let mut skip = false; for a in args { diff --git a/src/time.rs b/src/time.rs index 9917f54..4f5ab7f 100644 --- a/src/time.rs +++ b/src/time.rs @@ -143,6 +143,7 @@ mod clock { static AT: Mutex<Option<DateTime<Utc>>> = Mutex::new(None); static OWNER: Mutex<()> = Mutex::new(()); +// VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it. pub struct VirtualClock { _owner: MutexGuard<'static, ()>, } @@ -205,7 +206,7 @@ mod clock { } #[inline(always)] - pub fn wrap<F, T>(f: F) -> F + pub(super) fn wrap<F, T>(f: F) -> F where F: FnOnce() -> T + Send + 'static, T: Send + 'static, diff --git a/src/usecase/detect.rs b/src/usecase/detect.rs index 67cc83c..81042f7 100644 --- a/src/usecase/detect.rs +++ b/src/usecase/detect.rs @@ -11,6 +11,7 @@ use crate::watch::detect::{self, Outcome}; /// subscription should not stop at the first pkgbase whose mirror is /// unreachable, and the caller decides whether a failure is a line on stderr /// or a row in a table. +// Checked stays `pub`: what `usecase::detect` returns to the `aur-build` binary, which is a separate crate. pub struct Checked { pub pkgbase: String, pub outcome: Result<Outcome>, diff --git a/src/usecase/maintenance.rs b/src/usecase/maintenance.rs index 4276016..8c66ee2 100644 --- a/src/usecase/maintenance.rs +++ b/src/usecase/maintenance.rs @@ -8,6 +8,7 @@ use crate::error::Result; use crate::ops; /// What a garbage collection would do, before anything is deleted. +// GcPlan stays `pub`: what `usecase::plan_gc` returns to the `aur-build` binary, which is a separate crate. pub struct GcPlan { pub keep: usize, /// Releases whose files survive. diff --git a/src/usecase/reviews.rs b/src/usecase/reviews.rs index 8cbb534..c58e39b 100644 --- a/src/usecase/reviews.rs +++ b/src/usecase/reviews.rs @@ -7,6 +7,7 @@ use crate::pipeline; use crate::review::{approve as ap, candidates, diff}; /// The diff a reviewer is being asked to look at, already recorded. +// Prepared stays `pub`: what `prepare_review` and `view_review` return to the `aur-build` binary, which is a separate crate. pub struct Prepared { pub candidate: CandidateRow, pub text: String, diff --git a/src/watch/detect.rs b/src/watch/detect.rs index 3d2c955..1c72131 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -23,6 +23,7 @@ pub enum Outcome { } #[derive(Debug, Clone)] +// CheckReport stays `pub`: what `detect::check_pkgbase` returns; the test tier drives it and binds the value without naming it. pub struct CheckReport { pub pkgbase: String, pub head: String, @@ -106,7 +107,6 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor pkgver: a.pkgver.clone(), pkgrel: a.pkgrel.clone(), pins: accepted_pins.clone(), - cached: true, }) }; let (epoch, pkgver, pkgrel, pins) = match &resolved { diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs index d7c793b..5b7e2b1 100644 --- a/src/watch/mirror.rs +++ b/src/watch/mirror.rs @@ -69,7 +69,7 @@ impl Tree { pub fn recipe_hash(&self) -> String { crate::hash::recipe_hash(&self.blobs) } - pub fn json_list(&self) -> String { + pub(crate) fn json_list(&self) -> String { serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into()) } } diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs index 0845440..7987178 100644 --- a/src/watch/upstream.rs +++ b/src/watch/upstream.rs @@ -10,6 +10,7 @@ use crate::error::{Error, Result, TransientCause}; use crate::git; #[derive(Debug, Clone)] +// StageA stays `pub`: what `upstream::probe` returns; tests/ops.rs and tests/vcs.rs call `probe` directly. pub struct StageA { pub pins: Vec<UpstreamPin>, pub unprobed: Vec<String>, @@ -106,26 +107,20 @@ fn probe_impl(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> { } #[derive(Debug, Clone)] -pub struct StageB { +pub(crate) struct StageB { pub epoch: String, pub pkgver: String, pub pkgrel: String, pub pins: Vec<UpstreamPin>, - pub cached: bool, } impl StageB { - pub fn version(&self) -> String { - crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) - } - fn from_cache(row: StageBCacheRow) -> Self { StageB { epoch: row.epoch, pkgver: row.pkgver, pkgrel: row.pkgrel, pins: row.pins, - cached: true, } } @@ -274,7 +269,6 @@ fn run( pkgver, pkgrel, pins, - cached: false, }) } diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json index f451680..7a95341 100644 --- a/tests/architecture-budget.json +++ b/tests/architecture-budget.json @@ -1,5 +1,25 @@ { "dead_code": { + "allowlist": { + "db.Migration": "the row type of `MIGRATIONS`, which is `pub` only under `test-support`; production walks the table through `db::migrate` without naming it", + "db.PackageRow": "what `index_packages` hands back to `http`, the publish step and the `aur-build` binary, which bind it without naming it", + "db.Subscription": "what `get_subscription` and `list_subscriptions` hand back to `watch`, `usecase`, the binary and tests/detect.rs", + "db.Unbuilt": "the attention row `approved_but_unbuilt` returns to the web UI and to tests/crash.rs", + "pkginfo.Installed": "what `parse_installed` answers with, read line by line by `pipeline` and tests/world.rs", + "pkginfo.PkgInfo": "what `parse_pkginfo` answers with; `pipeline`, `shims` and tests/world.rs read its fields, never its name", + "review.BulkItem": "one outcome of `approve::bulk`, which tests/approve.rs drives directly", + "sandbox.ProvisionRequest": "the argument of `Provisioner::provision`, the trait the public `LocalAgentProvisioner` implements", + "sandbox.Provisioner": "implemented by the test-gated public `LocalAgentProvisioner`; a private trait on a public impl is E0445", + "shims.FakeInstalled": "the whole `shims` module is `test-support`-gated, so a release build never compiles it", + "shims.FakePackage": "the whole `shims` module is `test-support`-gated, so a release build never compiles it", + "shims.Manifest": "returned by `manifest()`, which the shim tests read; the module is `test-support`-gated", + "time.VirtualClock": "lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it", + "usecase.Checked": "what `usecase::detect` returns to the `aur-build` binary, which is a separate crate", + "usecase.GcPlan": "what `usecase::plan_gc` returns to the `aur-build` binary, which is a separate crate", + "usecase.Prepared": "what `prepare_review` and `view_review` return to the `aur-build` binary, which is a separate crate", + "watch.CheckReport": "what `detect::check_pkgbase` returns; the test tier drives it and binds the value without naming it", + "watch.StageA": "what `upstream::probe` returns; tests/ops.rs and tests/vcs.rs call `probe` directly" + }, "deadonly": { "bin/gpg": 0, "bin/makechrootpkg": 0, @@ -9,26 +29,26 @@ "bin/repo-add": 0, "bin/sandbox-agent": 0, "config": 0, - "db": 8, + "db": 0, "error": 0, - "fetch": 1, + "fetch": 0, "git": 0, "hash": 0, - "http": 3, + "http": 0, "lib": 0, "main": 0, - "ops": 1, + "ops": 0, "pipeline": 0, - "pkginfo": 2, + "pkginfo": 0, "pkgver": 0, "recipe": 0, - "review": 1, - "sandbox": 2, - "shims": 8, - "time": 2, + "review": 0, + "sandbox": 0, + "shims": 0, + "time": 0, "urlutil": 0, - "usecase": 3, - "watch": 4 + "usecase": 0, + "watch": 0 } }, "modules": { @@ -121,14 +141,14 @@ "test": 2 }, "db": { - "dead": 19, - "deadonly": 8, + "dead": 11, + "deadonly": 0, "glob": 0, "largest": 368, "largest_file": "src/db/mod.rs", - "lines": 3923, - "priv": 12, - "pub": 196, + "lines": 3897, + "priv": 19, + "pub": 189, "test": 11 }, "error": { @@ -143,14 +163,14 @@ "test": 0 }, "fetch": { - "dead": 1, - "deadonly": 1, + "dead": 0, + "deadonly": 0, "glob": 0, "largest": 57, "largest_file": "src/fetch.rs", "lines": 57, - "priv": 1, - "pub": 2, + "priv": 2, + "pub": 1, "test": 0 }, "git": { @@ -176,14 +196,14 @@ "test": 0 }, "http": { - "dead": 8, - "deadonly": 3, + "dead": 5, + "deadonly": 0, "glob": 0, "largest": 565, "largest_file": "src/http/routes/pages.rs", "lines": 2034, - "priv": 78, - "pub": 20, + "priv": 81, + "pub": 17, "test": 5 }, "lib": { @@ -209,14 +229,14 @@ "test": 0 }, "ops": { - "dead": 4, - "deadonly": 1, + "dead": 3, + "deadonly": 0, "glob": 0, "largest": 455, "largest_file": "src/ops.rs", "lines": 455, - "priv": 3, - "pub": 13, + "priv": 5, + "pub": 11, "test": 3 }, "pipeline": { @@ -231,12 +251,12 @@ "test": 6 }, "pkginfo": { - "dead": 2, - "deadonly": 2, + "dead": 0, + "deadonly": 0, "glob": 0, - "largest": 115, + "largest": 117, "largest_file": "src/pkginfo.rs", - "lines": 115, + "lines": 117, "priv": 0, "pub": 6, "test": 0 @@ -264,47 +284,47 @@ "test": 0 }, "review": { - "dead": 5, - "deadonly": 1, + "dead": 4, + "deadonly": 0, "glob": 0, "largest": 301, "largest_file": "src/review/diff.rs", - "lines": 914, + "lines": 915, "priv": 4, "pub": 24, "test": 4 }, "sandbox": { - "dead": 9, - "deadonly": 2, + "dead": 7, + "deadonly": 0, "glob": 0, - "largest": 506, + "largest": 508, "largest_file": "src/sandbox/kata.rs", - "lines": 1411, + "lines": 1413, "priv": 16, "pub": 21, "test": 7 }, "shims": { - "dead": 12, - "deadonly": 8, + "dead": 4, + "deadonly": 0, "glob": 0, - "largest": 652, + "largest": 655, "largest_file": "src/shims/mod.rs", - "lines": 652, - "priv": 8, - "pub": 13, + "lines": 655, + "priv": 13, + "pub": 8, "test": 4 }, "time": { - "dead": 5, - "deadonly": 2, + "dead": 3, + "deadonly": 0, "glob": 0, - "largest": 242, + "largest": 243, "largest_file": "src/time.rs", - "lines": 242, + "lines": 243, "priv": 0, - "pub": 14, + "pub": 13, "test": 3 }, "urlutil": { @@ -319,25 +339,25 @@ "test": 0 }, "usecase": { - "dead": 3, - "deadonly": 3, + "dead": 0, + "deadonly": 0, "glob": 0, - "largest": 123, + "largest": 124, "largest_file": "src/usecase/reviews.rs", - "lines": 402, + "lines": 405, "priv": 0, "pub": 30, "test": 0 }, "watch": { - "dead": 8, - "deadonly": 4, + "dead": 4, + "deadonly": 0, "glob": 0, - "largest": 302, + "largest": 296, "largest_file": "src/watch/upstream.rs", - "lines": 1121, - "priv": 10, - "pub": 24, + "lines": 1115, + "priv": 12, + "pub": 21, "test": 4 } }, @@ -348,15 +368,15 @@ "total": 36 }, "totals": { - "dead": 84, - "deadonly": 35, + "dead": 49, + "deadonly": 0, "edges": 87, "glob": 0, "largest": 701, "largest_file": "src/config.rs", - "lines": 15704, - "priv": 150, - "pub": 470, + "lines": 15684, + "priv": 170, + "pub": 448, "test": 49 } } diff --git a/tests/architecture.rs b/tests/architecture.rs index 12de924..6f68f2b 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -241,6 +241,7 @@ impl Census { .collect(); let mut modules: BTreeMap<String, Module> = BTreeMap::new(); + let allowlist = allowed_pub_items(); for (path, text) in &texts { let module = modules.entry(module_of(path)).or_default(); module.lines += text.lines().count(); @@ -278,6 +279,12 @@ impl Census { } let used_by_tests = test_texts.iter().any(|t| mentions(t, name)); for module in declaring { + // An item the budget file argues for is a decision, not a hole, + // so it leaves the dead columns entirely. `deadonly` then means + // *dead and unargued* — the one number that can stay at zero. + if allowlist.contains(&format!("{module}.{name}")) { + continue; + } let module = modules.get_mut(module).unwrap(); module.dead += 1; if used_by_tests { @@ -340,6 +347,27 @@ impl Census { } } +/// The `dead_code.allowlist` keys — `module.item` for every item that stays +/// `pub` by decision, with its reason next to it in the same file. +fn allowed_pub_items() -> BTreeSet<String> { + let path = root().join("tests/architecture-budget.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e)); + let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json"); + value + .get("dead_code") + .and_then(|d| d.get("allowlist")) + .and_then(|a| a.as_object()) + .map(|a| { + a.keys() + .map(|k| { + assert!(!k.trim().is_empty(), "an allowlist key cannot be blank"); + k.clone() + }) + .collect() + }) + .unwrap_or_default() +} + /// A top-level section of the budget file, as `key -> allowed`. fn budget_section(section: &str) -> BTreeMap<String, usize> { let path = root().join("tests/architecture-budget.json"); diff --git a/tools/arch-census.py b/tools/arch-census.py index a0f436f..b734061 100755 --- a/tools/arch-census.py +++ b/tools/arch-census.py @@ -18,6 +18,12 @@ real is to privatize them and let the compiler answer: it rejects the ones that are load-bearing and says nothing about the rest. Whatever survives that is budgeted rather than zeroed, and the budget is where the reason lives. +An item whose reason has been written is no longer a hole, so it is not counted +as one: the `dead_code.allowlist` in `tests/architecture-budget.json` names +every item that stays `pub` by decision, and those items leave the `dead`, +`test` and `deadonly` columns. `deadonly` therefore means *dead and unargued*, +which is the one number that can honestly be held at zero forever. + The metric errs the other way too. Mentions are matched as words over the raw file, so a name that appears only inside someone else's error *string* counts as used: `watch::upstream::resolve` looked live for as long as some unrelated @@ -72,12 +78,27 @@ TESTS = os.path.join(ROOT, "tests") # A declaration, not a re-export: `pub use` is counted separately as a glob. PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)") PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+") +PUB_CRATE_NAME_RE = re.compile( + r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)" +) GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*") EDGE_RE = re.compile(r"\bcrate::([a-z_][a-z0-9_]*)") # The binaries are separate crates, so they name the library through its own # name rather than through `crate::`. Those edges are part of the graph too. LIB_EDGE_RE = re.compile(r"\baur_build::([a-z_][a-z0-9_]*)") COMMENT = re.compile(r"^\s*(?://|//!|///)") +BUDGET = os.path.join(ROOT, "tests", "architecture-budget.json") + + +def load_allowlist(path=None): + """The `module.item` names that stay `pub` by decision, with their reasons.""" + try: + with open(path or BUDGET) as handle: + section = json.load(handle).get("dead_code", {}) + except (ValueError, OSError): + return {} + allow = section.get("allowlist", {}) + return allow if isinstance(allow, dict) else {} def rust_files(*dirs): @@ -133,7 +154,8 @@ def declarations(texts): return names -def census(): +def census(allow=None): + allow = set(load_allowlist() if allow is None else allow) src_files = rust_files(SRC) test_files = rust_files(TESTS) src_texts = read_all(src_files) @@ -142,6 +164,9 @@ def census(): mods = sorted({module_of(p) for p in src_files}) rows = {} + # Every name a module declares, `pub` or `pub(crate)`. The allowlist is + # checked against this, so a permission cannot outlive the item it names. + declared = collections.defaultdict(set) for mod in mods: rows[mod] = { "pub": 0, @@ -163,6 +188,9 @@ def census(): continue if PUB_CRATE_RE.match(line): row["priv"] += 1 + m = PUB_CRATE_NAME_RE.match(line) + if m: + declared[module_of(path)].add(m.group(1)) if GLOB_RE.match(line): row["glob"] += 1 size = text.count("\n") + 1 @@ -176,6 +204,8 @@ def census(): for name, paths in names.items(): declaring = {module_of(p) for p, _ in paths} for mod in declaring: + declared[mod].add(name) + for mod in declaring: rows[mod]["pub"] += 1 outside = any( module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t) @@ -185,6 +215,17 @@ def census(): continue used_by_tests = any(re.search(r"\b%s\b" % re.escape(name), t) for t in test_texts.values()) for mod in declaring: + if f"{mod}.{name}" in allow: + # Argued, so not a hole: it stays `pub` on purpose and the reason + # is in the budget file next to its name. + dead_items.append({ + "module": mod, + "name": name, + "kind": "allowlisted", + "file": os.path.relpath(next(p for p, _ in paths if module_of(p) == mod), ROOT), + "line": next(ln for p, ln in paths if module_of(p) == mod), + }) + continue rows[mod]["dead"] += 1 if used_by_tests: rows[mod]["test"] += 1 @@ -214,6 +255,7 @@ def census(): return { "modules": rows, "dead_items": dead_items, + "declared": {mod: sorted(v) for mod, v in sorted(declared.items())}, "edges": {k: sorted(v) for k, v in sorted(edges.items())}, "totals": { "pub": sum(r["pub"] for r in rows.values()), @@ -266,6 +308,12 @@ def check_dead_code(data, budget): accepted count. An item can appear that no one argued for. And an allowlist entry can outlive the item it excused, which is how a deleted item comes back: the permission is still on the books, so nobody notices the new one. + + An entry stays valid while the item it names is still declared in that module, + even once the item has been narrowed to `pub(crate)` — the reason a caller + outside the module does not name it is worth keeping. Re-widening a narrowed + item is not caught here; it raises the module's `deadonly` over its accepted + count, which is what the count is for. """ accepted, allowlist = dead_code_section(budget) problems = [] @@ -274,32 +322,34 @@ def check_dead_code(data, budget): have, allowed = actual.get(mod, 0), accepted.get(mod, 0) if have > allowed: problems.append(f"{mod}.deadonly: {have} > {allowed} accepted") - named = set() for item in data["dead_items"]: if item["kind"] != "deadonly": continue key = f"{item['module']}.{item['name']}" - named.add(key) if key not in allowlist: problems.append(f"{key} at {item['file']}:{item['line']} is dead and unargued") elif not str(allowlist[key]).strip(): problems.append(f"{key} is allowlisted with no reason") - for key in sorted(set(allowlist) - named): - problems.append(f"allowlist names {key}, which is not dead; delete the permission") + declared = data["declared"] + for key in sorted(allowlist): + mod, _, name = key.partition(".") + if name not in declared.get(mod, []): + problems.append(f"allowlist names {key}, which no module member is; delete the permission") return problems def list_dead(data): """Name every dead item. A count tells a module is wide; this says which items.""" width = max(len(d["module"]) for d in data["dead_items"]) if data["dead_items"] else 0 - for kind, label in (("deadonly", "named by nobody"), ("test", "named only by tests")): + for kind, label in (("deadonly", "named by nobody"), ("test", "named only by tests"), + ("allowlisted", "kept `pub` by decision, reason in the budget file")): rows = [d for d in data["dead_items"] if d["kind"] == kind] print(f"\n{label} — {len(rows)} items") for d in rows: print(f" {d['module'].ljust(width)} {d['name'].ljust(34)} {d['file']}:{d['line']}") totals = data["totals"] print(f"\n{totals['dead']} dead of {totals['pub']} pub; " - f"{totals['deadonly']} of them named by nobody") + f"{totals['deadonly']} of them unargued") def print_census(data): @@ -355,9 +405,10 @@ def main(): ap.add_argument("--budget", metavar="FILE", help="fail if a number is over the committed budget") ap.add_argument("--write-budget", metavar="FILE", help="write the current numbers as the budget") ap.add_argument("--list-dead", action="store_true", help="name every dead item with its file:line") + ap.add_argument("--allowlist", metavar="FILE", help="read the kept-item allowlist from FILE") args = ap.parse_args() - data = census() + data = census(allow=load_allowlist(args.allowlist) if args.allowlist else None) if args.write_budget: # Preserve any section another tool owns (for example `test_surface`, |
