//! A `CottonOp` IS BUILT IN THREE PLACES: `mint` (this file's own write),//! `wire` (a peer's bytes) and `stored` (a row of this file read back). Every//! other `CottonOp { … }` literal is a write path that stamps, folds and//! queues on its own terms — four answers to what a stale skip means, forty//! author constants — and the groundwork's slices 2b and 2c move each of them//! into `mint`. Until they land, the ones left are named below, each with the//! slice that takes it, and a pull may only shorten the list.//!//! Test modules are not scanned: a fixture that builds the op a case needs is//! the test's business. Production source under `crates/*/src` is.use std::path::{Path, PathBuf};/// The three builders.const BUILDERS: [&str; 3] = ["cotton-store/src/mint.rs","cotton-store/src/wire.rs","cotton-store/src/stored.rs",];/// The literals left outside them, each with the slice that moves it.// Every production literal outside the builders has moved (2b, 2c, and the// fixtures file to `mint` in 3a); the list stays so a new stray must be named.const NOT_YET_MOVED: [(&str, &str); 0] = [];fn crates_root() -> PathBuf { cotton_store::manifest_dir() .parent() .expect("cotton-store sits in the crates directory") .to_path_buf()}/// Every production source file under `crates/*/src`, as (path from `crates/`,/// text with any trailing `#[cfg(test)] mod …` cut off and comments blanked).fn sources() -> Vec<(String, String)> {let root = crates_root();letmut found = Vec::new();letmut crates: Vec<PathBuf> = std::fs::read_dir(&root) .expect("the crates directory") .filter_map(Result::ok) .map(|entry| entry.path().join("src")) .filter(|src| src.is_dir()) .collect(); crates.sort();for src in crates { walk(&src, &root, &mut found); } assert!( found.len() > 200,"the scan found only {} files", found.len() ); found}fn walk(dir: &Path, root: &Path, found: &mutVec<(String, String)>) {letOk(entries) = std::fs::read_dir(dir) else {return; };letmut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); paths.sort();for path in paths {if path.is_dir() { walk(&path, root, found);continue; }let name = path .file_name() .and_then(|n| n.to_str()) .unwrap_or_default();if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {continue; }letOk(text) = std::fs::read_to_string(&path) else {continue; };let relative = path .strip_prefix(root) .unwrap_or(&path) .to_string_lossy() .replace('\\', "/"); found.push((relative, production_text(&text))); }}/// The text before an inline `#[cfg(test)] mod … {`, with every `//` comment/// blanked so a sentence about the type is not a literal.fn production_text(text: &str) -> String {let lines: Vec<&str> = text.lines().collect();letmut end = lines.len();for (index, line) in lines.iter().enumerate() {if line.trim() != "#[cfg(test)]" {continue; }let next = lines[index + 1..].iter().find(|l| !l.trim().is_empty());if next.is_some_and(|l| l.trim_start().starts_with("mod ") && l.trim_end().ends_with('{')) { end = index;break; } } lines[..end] .iter() .map(|line| match line.find("//") {Some(at) => &line[..at],None => line, }) .collect::<Vec<_>>() .join("\n")}/// The line of each `CottonOp {` literal in `text`.////// A brace after the name is also how a return type meets its body/// (`-> CottonOp {`) and how the type is declared (`struct CottonOp {`), so/// the word before the name decides: a literal follows an operator, a/// keyword that takes a value, or an open delimiter, never `->`, `struct`,/// `impl`, `enum` or `for`.fn literals(text: &str) -> Vec<usize> {letmut found = Vec::new();letmut from = 0;whileletSome(at) = text[from..].find("CottonOp") {let offset = from + at;let before = text[..offset].trim_end();let glued = text[..offset] .chars() .next_back() .is_some_and(|c| c.is_alphanumeric() || c == '_');let after = text[offset + "CottonOp".len()..].trim_start();let declares = before.ends_with("->") || ["struct", "impl", "enum", "for", "dyn"] .iter() .any(|word| before.ends_with(word));if !glued && !declares && after.starts_with('{') { found.push(text[..offset].matches('\n').count() + 1); } from = offset + "CottonOp".len(); } found}/// RULE: A CottonOp is built only in mint, wire and stored; every other literal is on the slice-named list in this test, and a pull only shortens that list.#[test]fn no_cotton_op_literal_outside_mint_wire_stored() {let files = sources();letmut strays = Vec::new();for (file, text) in &files {let lines = literals(text);if lines.is_empty() || BUILDERS.contains(&file.as_str()) {continue; }if NOT_YET_MOVED.iter().any(|(path, _)| path == file) {continue; } strays.push(format!("{file}:{}", lines[0])); } assert!( strays.is_empty(),"a CottonOp is built outside mint, wire and stored — build it through one of them, \ or hand the write to mint:\n {}", strays.join("\n ") );}/// RULE: Each builder of a CottonOp still builds one, and each file on the not-yet-moved list still holds a literal, so an entry leaves the list with the pull that moves it.#[test]fn the_list_still_names_what_it_names() {let files = sources();let text_of = |path: &str| { files .iter() .find(|(file, _)| file == path) .map(|(_, text)| text.as_str()) .unwrap_or_else(|| panic!("{path} is not where this guard reads it")) };// Since receipts (slice 3a) the literal itself is `wire`'s alone — an op// is the reading of its receipt's bytes — and `mint` and `stored` build// theirs through it: `mint` from the receipt it just made, `stored` from// the bytes a row of this file holds.for builder in BUILDERS {let text = text_of(builder); assert!( !literals(text).is_empty() || text.contains("wire::from_receipt(") || text.contains("wire::from_bytes("),"{builder} no longer builds a CottonOp — it is one of the three places that may" ); } assert!( !literals(text_of("cotton-store/src/wire.rs")).is_empty(),"wire no longer holds the one CottonOp literal the builders share" );for (path, reason) in NOT_YET_MOVED { assert!( !literals(text_of(path)).is_empty(),"{path} no longer builds a CottonOp ({reason}) — take it off NOT_YET_MOVED" ); }}#[test]fn the_scan_refuses_what_it_says_it_refuses() { assert_eq!(literals("fn a() { CottonOp { op_id, .. } }"), vec![1]); assert_eq!( literals("fn a() {\n let op = CottonOp {\n op_id };\n}"), vec![2] ); assert!(literals("fn a(op: &CottonOp) -> CottonOp { op.clone() }").is_empty()); assert!(literals("fn a(\n op: &CottonOp,\n) -> CottonOp {\n op.clone()\n}").is_empty()); assert!(literals("pub struct CottonOp {\n pub op_id: String,\n}").is_empty()); assert!(literals("impl CottonOp {\n fn a() {} }").is_empty()); assert_eq!(literals("fn a() -> X { Ok(CottonOp { op_id }) }"), vec![1]); assert_eq!( literals("fn a() { ops.push(CottonOp {\n op_id }) }"), vec![1] ); assert_eq!(literals("fn a() { return CottonOp { op_id }; }"), vec![1]); assert!(literals("struct MyCottonOp { x: u8 }").is_empty()); assert!(literals(&production_text("// a CottonOp { … } in a comment\nfn a() {}" )) .is_empty()); assert!(literals(&production_text("fn a() {}\n#[cfg(test)]\nmod tests {\n fn b() { CottonOp { x } }\n}" )) .is_empty());}