Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! The human decisions: `rust/obligations-decisions.toml`, outside the regenerated registry. The
//! tool writes it (`obligations waive`, `obligations attest`) and a person can read and fix it.
//!
//! ```toml
//! [[waive]]
//! adr = "ADR-012"
//! date = "2026-11-26"
//! reason = "internal helpers of a CLI, reached through the commands"
//! pattern = "export:*" # optional: what was typed
//! items = ["export:src/a.ts#f", "export:src/b.ts#g"]
//!
//! [[attest]]
//! adr = "ADR-013"
//! date = "2026-11-26"
//! family = "command"
//! reason = "the six commands of the usage text are the listed ones"
//! state = "enumerated"
//! obligations = 6
//! unlisted = 0
//! fingerprint = "9f3a0c1d2b4e5f60"
//!
//! [[size]]
//! adr = "ADR-014"
//! date = "2026-12-02"
//! reason = "re-implements html.parser and the bs4 tree builder, which no crate reproduces"
//! unit = "src/scrape.py"
//! max = 6
//! ```
//!
//! The file is read strictly, all faults at once, like the bindings: a wrong decision would make
//! what blocks pass for waived. Nothing is applied if there is a fault. Each entry names an ADR
//! that must be titled in `rust/DECISIONS.md`: a waiver only holds with its written decision.
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use anyhow::{Result, bail};
use toml_edit::{DocumentMut, Item, Table};
use super::super::evidence::{Opened, open};
use super::super::{Completeness, Family};
use super::adr;
/// The decisions file, from the repository root.
pub const DECISIONS_FILE: &str = "rust/obligations-decisions.toml";
const WAIVE_KEYS: [&str; 5] = ["adr", "date", "reason", "pattern", "items"];
const SIZE_KEYS: [&str; 5] = ["adr", "date", "reason", "unit", "max"];
const ATTEST_KEYS: [&str; 8] = [
"adr",
"date",
"family",
"reason",
"state",
"obligations",
"unlisted",
"fingerprint",
];
/// Obligations that a person waives, with its ADR.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Waive {
pub adr: String,
pub date: String,
pub reason: String,
/// What was typed, when it was a pattern.
pub pattern: Option<String>,
pub items: Vec<String>,
}
/// The state of a family that a person attests, with its ADR.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Attest {
pub adr: String,
pub date: String,
pub family: Family,
pub reason: String,
pub state: Completeness,
pub obligations: usize,
pub unlisted: usize,
pub fingerprint: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Size {
pub adr: String,
pub date: String,
pub reason: String,
pub unit: String,
pub max: f64,
}
/// All the decisions of the file, in its order.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Decisions {
pub waives: Vec<Waive>,
pub attests: Vec<Attest>,
pub sizes: Vec<Size>,
}
impl Decisions {
/// Each waived id, with the ADR of the decision.
pub fn waived(&self) -> BTreeMap<&str, &Waive> {
let mut out = BTreeMap::new();
for w in &self.waives {
for item in &w.items {
out.entry(item.as_str()).or_insert(w);
}
}
out
}
/// The attestation that counts for a family: the last one written. A newer one replaces a
/// stale one without deleting it, so the file keeps the history.
pub fn attestation(&self, family: Family) -> Option<&Attest> {
self.attests.iter().rev().find(|a| a.family == family)
}
pub fn size(&self, unit: &str) -> Option<&Size> {
self.sizes.iter().rev().find(|s| s.unit == unit)
}
}
/// The decisions of the repository `root` (already canonical). A missing file decides nothing; a
/// file that does not open or that is wrong is an error that lists its faults.
pub(super) fn read(root: &Path) -> Result<Decisions> {
let text = match open(root, DECISIONS_FILE) {
Opened::Absent => return Ok(Decisions::default()),
Opened::Refused(why) => bail!("{DECISIONS_FILE} is not opened: {why}"),
Opened::Text(text) => text,
};
let journal = adr::journal(root)?;
parse(&text, &journal)
}
/// A reason: one sentence, on one line. The command line's refusals and the file's faults go
/// through here.
pub(super) fn reason_fault(reason: &str) -> Option<&'static str> {
if reason.trim().is_empty() {
Some("the reason is empty: say why")
} else if reason.contains('\n') || reason.contains('\r') {
Some("the reason must be on one line")
} else if reason.chars().any(|c| c.is_control() && c != '\t') {
Some("the reason must be printable text: it holds a control character")
} else {
None
}
}
fn parse(text: &str, journal: &adr::Journal) -> Result<Decisions> {
let doc: DocumentMut = match text.parse() {
Ok(doc) => doc,
Err(e) => bail!("invalid {DECISIONS_FILE}: {e}"),
};
let mut faults: Vec<String> = Vec::new();
for (key, _) in doc.iter() {
if !matches!(key, "waive" | "attest" | "size") {
faults.push(format!(
"unknown key `{key}` (the tables are `[[waive]]`, `[[attest]]` and `[[size]]`)"
));
}
}
let mut decisions = Decisions::default();
for (key, what) in [
("waive", "waiver"),
("attest", "attestation"),
("size", "size allowance"),
] {
let Some(item) = doc.get(key) else { continue };
let Some(tables) = item.as_array_of_tables() else {
faults.push(format!("`{key}` must be written as `[[{key}]]` tables"));
continue;
};
for (i, table) in tables.iter().enumerate() {
let mut fault = |why: String| faults.push(format!("[[{key}]] #{}: {why}", i + 1));
let head = head(table, journal, what, &mut fault);
if key == "waive" {
if let Some(w) = waive(table, head, &mut fault) {
// The cited section must name what the waiver decides: the first id,
// which is the first one `waive` writes.
if let Some(first) = w.items.first() {
names_what(journal, &w.adr, first, &mut fault);
}
decisions.waives.push(w);
}
} else if key == "size" {
if let Some(s) = size(table, head, &mut fault) {
names_what(journal, &s.adr, &s.unit, &mut fault);
decisions.sizes.push(s);
}
} else if let Some(a) = attest(table, head, &mut fault) {
names_what(journal, &a.adr, a.family.label(), &mut fault);
decisions.attests.push(a);
}
}
}
duplicates(&decisions, &mut faults);
if faults.is_empty() {
return Ok(decisions);
}
let list: String = faults.iter().map(|f| format!("\n - {f}")).collect();
bail!("invalid {DECISIONS_FILE}:{list}")
}
/// The fields both kinds of entries have in common: the ADR, the date and the reason.
struct Head {
adr: String,
date: String,
reason: String,
}
fn text_of<'a>(table: &'a Table, key: &str) -> Option<&'a str> {
table
.get(key)
.and_then(Item::as_str)
.filter(|s| !s.trim().is_empty())
}
/// The section of the cited ADR must write `what` between backticks: without that, an unrelated
/// ADR (or one emptied afterwards) would make a decision hold that it does not carry. A missing
/// ADR or one titled twice already has its fault: no second one here.
fn names_what(journal: &adr::Journal, adr_id: &str, what: &str, fault: &mut impl FnMut(String)) {
if let Some(section) = journal.section(adr_id)
&& !adr::names(section, what)
{
fault(format!(
"{adr_id} does not mention `{what}`: the section must name what the decision decides"
));
}
}
fn head(
table: &Table,
journal: &adr::Journal,
what: &str,
fault: &mut impl FnMut(String),
) -> Option<Head> {
let mut ok = true;
let adr = match text_of(table, "adr") {
None => {
fault("`adr` is missing or empty: name the decision record".to_string());
ok = false;
String::new()
}
Some(adr) => {
let lines = journal.lines_of(adr);
if lines.is_empty() {
fault(format!(
"{adr} is not in {}: a {what} only holds with its decision record",
adr::ADR_FILE
));
ok = false;
} else if lines.len() > 1 {
let at: Vec<String> = lines.iter().map(ToString::to_string).collect();
fault(format!(
"{adr} is titled {} times in {} (lines {}): a {what} needs one record, not an ambiguous one",
lines.len(),
adr::ADR_FILE,
at.join(", ")
));
ok = false;
}
adr.to_string()
}
};
let date = match text_of(table, "date") {
Some(date) if adr::is_date(date) => date.to_string(),
Some(date) => {
fault(format!("`date` `{date}` is not a date written YYYY-MM-DD"));
ok = false;
String::new()
}
None => {
fault("`date` is missing or empty".to_string());
ok = false;
String::new()
}
};
let reason = match table.get("reason").and_then(Item::as_str) {
None => {
fault("`reason` is missing: say why".to_string());
ok = false;
String::new()
}
Some(reason) => {
if let Some(why) = reason_fault(reason) {
fault(format!("`reason`: {why}"));
ok = false;
}
reason.to_string()
}
};
ok.then_some(Head { adr, date, reason })
}
fn unknown_keys(table: &Table, keys: &[&str], fault: &mut impl FnMut(String)) {
for (key, _) in table.iter() {
if !keys.contains(&key) {
fault(format!("unknown key `{key}`"));
}
}
}
fn waive(table: &Table, head: Option<Head>, fault: &mut impl FnMut(String)) -> Option<Waive> {
unknown_keys(table, &WAIVE_KEYS, fault);
let mut items = Vec::new();
let mut ok = true;
match table.get("items").and_then(Item::as_array) {
None => {
fault("`items` must be a non-empty array of obligation ids".to_string());
ok = false;
}
Some(list) if list.is_empty() => {
fault("`items` is empty".to_string());
ok = false;
}
Some(list) => {
for value in list {
match value.as_str().filter(|s| !s.trim().is_empty()) {
None => {
fault("`items` holds something that is not a non-empty string".to_string());
ok = false;
}
Some(id) if items.iter().any(|i| i == id) => {
fault(format!("`{id}` is listed twice in `items`"));
ok = false;
}
Some(id) => items.push(id.to_string()),
}
}
}
}
let pattern = match table.get("pattern") {
None => None,
Some(item) => match item.as_str().filter(|s| !s.trim().is_empty()) {
Some(p) => Some(p.to_string()),
None => {
fault("`pattern` must be a non-empty string when it is there".to_string());
ok = false;
None
}
},
};
let head = head?;
ok.then_some(Waive {
adr: head.adr,
date: head.date,
reason: head.reason,
pattern,
items,
})
}
fn size(table: &Table, head: Option<Head>, fault: &mut impl FnMut(String)) -> Option<Size> {
unknown_keys(table, &SIZE_KEYS, fault);
let unit = text_of(table, "unit").map(str::to_string);
if unit.is_none() {
fault("`unit` is missing or empty: name the unit as its `rust-anything.json` does".into());
}
let cap = crate::gate::MAX_GROWTH;
let max = table
.get("max")
.and_then(|i| i.as_float().or_else(|| i.as_integer().map(|n| n as f64)))
.filter(|m| m.is_finite() && *m > cap);
if max.is_none() {
fault(format!(
"`max` must be a number greater than {cap}, the times the original's lines a port \
may take without a decision"
));
}
let head = head?;
Some(Size {
adr: head.adr,
date: head.date,
reason: head.reason,
unit: unit?,
max: max?,
})
}
fn count(table: &Table, key: &str, fault: &mut impl FnMut(String)) -> Option<usize> {
let found = table
.get(key)
.and_then(Item::as_integer)
.and_then(|n| usize::try_from(n).ok());
if found.is_none() {
fault(format!("`{key}` must be a whole number, zero or more"));
}
found
}
fn attest(table: &Table, head: Option<Head>, fault: &mut impl FnMut(String)) -> Option<Attest> {
unknown_keys(table, &ATTEST_KEYS, fault);
let family = match text_of(table, "family") {
None => {
fault("`family` is missing or empty".to_string());
None
}
Some(name) => match name.parse::<Family>() {
Ok(family) => Some(family),
Err(e) => {
fault(e);
None
}
},
};
let state = match text_of(table, "state") {
None => {
fault("`state` is missing or empty".to_string());
None
}
Some(name) => match name.parse::<Completeness>() {
Ok(Completeness::Complete) => {
fault("`state` is `complete`: a complete family needs no attestation".to_string());
None
}
Ok(state) => Some(state),
Err(e) => {
fault(e);
None
}
},
};
let obligations = count(table, "obligations", fault);
let unlisted = count(table, "unlisted", fault);
let fingerprint = match text_of(table, "fingerprint") {
Some(f) if f.len() == 16 && f.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) => {
Some(f.to_string())
}
Some(f) => {
fault(format!(
"`fingerprint` `{f}` is not 16 lowercase hexadecimal digits"
));
None
}
None => {
fault("`fingerprint` is missing or empty".to_string());
None
}
};
let head = head?;
Some(Attest {
adr: head.adr,
date: head.date,
family: family?,
reason: head.reason,
state: state?,
obligations: obligations?,
unlisted: unlisted?,
fingerprint: fingerprint?,
})
}
/// An id waived twice, or a family attested twice with the same fingerprint: the second entry
/// would say nothing more, and a file with two voices hides an error.
fn duplicates(decisions: &Decisions, faults: &mut Vec<String>) {
let mut first: BTreeMap<&str, &str> = BTreeMap::new();
for w in &decisions.waives {
for item in &w.items {
match first.get(item.as_str()) {
Some(adr) if *adr != w.adr => {
faults.push(format!("`{item}` is waived twice ({adr} and {})", w.adr));
}
Some(_) => faults.push(format!("`{item}` is waived twice (both under {})", w.adr)),
None => {
first.insert(item, &w.adr);
}
}
}
}
let mut seen: BTreeSet<(Family, &str)> = BTreeSet::new();
for a in &decisions.attests {
if !seen.insert((a.family, a.fingerprint.as_str())) {
faults.push(format!(
"family `{}` is attested twice with the same fingerprint",
a.family.label()
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A journal where each ADR is titled and cites what it is given between backticks.
fn journal_of(entries: &[(&str, &[&str])]) -> adr::Journal {
let mut text = String::from("# Decisions\n");
for (id, names) in entries {
text.push_str(&format!("\n## {id}: a decision\nStatus: accepted\n"));
for name in *names {
text.push_str(&format!("Decision: `{name}`\n"));
}
}
adr::Journal::parse(&text)
}
/// The journal that `GOOD` assumes: each ADR names what its entry decides.
fn titled(ids: &[&str]) -> adr::Journal {
let all: [&str; 4] = ["export:a#f", "command", "export:b#g", "flag"];
let entries: Vec<(&str, &[&str])> = ids.iter().map(|id| (*id, &all[..])).collect();
journal_of(&entries)
}
fn faults(text: &str, ids: &[&str]) -> Vec<String> {
let err = parse(text, &titled(ids)).expect_err("the file is wrong");
let message = format!("{err}");
assert!(
message.starts_with(&format!("invalid {DECISIONS_FILE}:")),
"{message}"
);
message
.lines()
.skip(1)
.map(|l| l.trim().trim_start_matches("- ").to_string())
.collect()
}
const GOOD: &str = r#"
[[waive]]
adr = "ADR-001"
date = "2026-11-26"
reason = "helpers reached through the commands"
pattern = "export:*"
items = ["export:a#f", "export:b#g"]
[[attest]]
adr = "ADR-002"
date = "2026-11-26"
family = "command"
reason = "the usage text lists them"
state = "enumerated"
obligations = 6
unlisted = 0
fingerprint = "9f3a0c1d2b4e5f60"
"#;
#[test]
fn a_good_file_is_read_in_full() {
let d = parse(GOOD, &titled(&["ADR-001", "ADR-002"])).unwrap();
assert_eq!(d.waives.len(), 1);
assert_eq!(d.waives[0].items, ["export:a#f", "export:b#g"]);
assert_eq!(d.waives[0].pattern.as_deref(), Some("export:*"));
assert_eq!(d.attests[0].family, Family::Command);
assert_eq!(d.attests[0].state, Completeness::Enumerated);
assert_eq!(d.attests[0].obligations, 6);
assert_eq!(
d.waived().get("export:b#g").map(|w| w.adr.as_str()),
Some("ADR-001")
);
assert!(d.attestation(Family::Flag).is_none());
}
#[test]
fn every_fault_is_listed_and_nothing_is_applied() {
let text = r#"
colour = "red"
[[waive]]
adr = "ADR-009"
date = "2026-02-30"
reason = ""
items = []
extra = 1
[[waive]]
adr = ""
date = "2026-11-26"
reason = "two\nlines"
items = ["a", "a", 3]
pattern = ""
[[attest]]
adr = "ADR-001"
date = "yesterday"
family = "colour"
reason = "ok"
state = "complete"
obligations = -1
fingerprint = "XYZ"
"#;
let list = faults(text, &["ADR-001"]);
let has = |needle: &str| list.iter().any(|f| f.contains(needle));
assert!(has("unknown key `colour`"), "{list:?}");
assert!(
has(
"[[waive]] #1: ADR-009 is not in rust/DECISIONS.md: a waiver only holds with its decision record"
),
"{list:?}"
);
assert!(
has("[[waive]] #1: `date` `2026-02-30` is not a date"),
"{list:?}"
);
assert!(
has("[[waive]] #1: `reason`: the reason is empty"),
"{list:?}"
);
assert!(has("[[waive]] #1: `items` is empty"), "{list:?}");
assert!(has("[[waive]] #1: unknown key `extra`"), "{list:?}");
assert!(has("[[waive]] #2: `adr` is missing or empty"), "{list:?}");
assert!(
has("[[waive]] #2: `reason`: the reason must be on one line"),
"{list:?}"
);
assert!(
has("[[waive]] #2: `a` is listed twice in `items`"),
"{list:?}"
);
assert!(
has("[[waive]] #2: `items` holds something that is not a non-empty string"),
"{list:?}"
);
assert!(
has("[[waive]] #2: `pattern` must be a non-empty string"),
"{list:?}"
);
assert!(has("[[attest]] #1: `date` `yesterday`"), "{list:?}");
assert!(has("[[attest]] #1: unknown family `colour`"), "{list:?}");
assert!(has("[[attest]] #1: `state` is `complete`"), "{list:?}");
assert!(
has("[[attest]] #1: `obligations` must be a whole number"),
"{list:?}"
);
assert!(
has("[[attest]] #1: `unlisted` must be a whole number"),
"{list:?}"
);
assert!(
has("[[attest]] #1: `fingerprint` `XYZ` is not 16 lowercase hexadecimal digits"),
"{list:?}"
);
}
#[test]
fn a_waiver_named_twice_and_an_attestation_repeated_are_faults() {
let text = format!(
"{GOOD}\n[[waive]]\nadr = \"ADR-003\"\ndate = \"2026-11-27\"\nreason = \"again\"\nitems = [\"export:a#f\"]\n\n[[attest]]\nadr = \"ADR-004\"\ndate = \"2026-11-27\"\nfamily = \"command\"\nreason = \"again\"\nstate = \"enumerated\"\nobligations = 6\nunlisted = 0\nfingerprint = \"9f3a0c1d2b4e5f60\"\n"
);
let list = faults(&text, &["ADR-001", "ADR-002", "ADR-003", "ADR-004"]);
assert!(
list.iter()
.any(|f| f == "`export:a#f` is waived twice (ADR-001 and ADR-003)"),
"{list:?}"
);
assert!(
list.iter()
.any(|f| f.contains("`command` is attested twice with the same fingerprint")),
"{list:?}"
);
}
#[test]
fn a_new_attestation_of_a_family_replaces_the_old_one_without_deleting_it() {
let text = format!(
"{GOOD}\n[[attest]]\nadr = \"ADR-003\"\ndate = \"2026-11-27\"\nfamily = \"command\"\nreason = \"after the change\"\nstate = \"enumerated\"\nobligations = 7\nunlisted = 0\nfingerprint = \"0000000000000001\"\n"
);
let d = parse(&text, &titled(&["ADR-001", "ADR-002", "ADR-003"])).unwrap();
assert_eq!(d.attests.len(), 2);
assert_eq!(d.attestation(Family::Command).unwrap().adr, "ADR-003");
}
#[test]
fn the_tables_must_be_arrays_of_tables_and_the_text_must_parse() {
let list = faults("waive = 3\nattest = \"x\"\n", &[]);
assert!(
list.iter()
.any(|f| f.contains("`waive` must be written as `[[waive]]` tables"))
);
assert!(
list.iter()
.any(|f| f.contains("`attest` must be written as `[[attest]]` tables"))
);
let err = parse("this is = = not toml", &titled(&[])).unwrap_err();
assert!(format!("{err}").starts_with("invalid rust/obligations-decisions.toml: "));
}
#[test]
fn an_adr_titled_twice_is_a_fault_for_every_decision_that_cites_it() {
let text = "\
[[waive]]
adr = \"ADR-007\"
date = \"2026-11-26\"
reason = \"r\"
items = [\"export:a#f\"]
[[attest]]
adr = \"ADR-007\"
date = \"2026-11-26\"
family = \"command\"
reason = \"r\"
state = \"enumerated\"
obligations = 1
unlisted = 0
fingerprint = \"9f3a0c1d2b4e5f60\"
";
let journal = adr::Journal::parse(
"## ADR-007: a\n`export:a#f` `command`\n\n## ADR-007: b\n`export:a#f` `command`\n",
);
let err = parse(text, &journal).expect_err("ambiguous record");
let message = format!("{err}");
for entry in ["[[waive]] #1", "[[attest]] #1"] {
assert!(
message.contains(&format!(
"{entry}: ADR-007 is titled 2 times in rust/DECISIONS.md (lines 1, 4)"
)),
"{message}"
);
}
}
#[test]
fn the_section_must_name_what_the_decision_decides() {
let waive = |first: &str| {
format!(
"[[waive]]\nadr = \"ADR-012\"\ndate = \"2026-11-26\"\nreason = \"r\"\nitems = [\"{first}\", \"export:b#g\"]\n"
)
};
// A section that cites only the second id does not decide the first.
let second_only = journal_of(&[("ADR-012", &["export:b#g"])]);
let message = format!("{}", parse(&waive("export:a#f"), &second_only).unwrap_err());
assert!(
message.contains("[[waive]] #1: ADR-012 does not mention `export:a#f`: "),
"{message}"
);
// A longer name that contains the first does not name it either.
let longer = journal_of(&[("ADR-012", &["export:a#fg"])]);
assert!(parse(&waive("export:a#f"), &longer).is_err());
// The first id cited is enough.
let first = journal_of(&[("ADR-012", &["export:a#f"])]);
assert!(parse(&waive("export:a#f"), &first).is_ok());
// An attestation must name its family.
let attest = "[[attest]]\nadr = \"ADR-013\"\ndate = \"2026-11-26\"\nfamily = \"flag\"\nreason = \"r\"\nstate = \"enumerated\"\nobligations = 1\nunlisted = 0\nfingerprint = \"9f3a0c1d2b4e5f60\"\n";
let wrong = journal_of(&[("ADR-013", &["command"])]);
let message = format!("{}", parse(attest, &wrong).unwrap_err());
assert!(
message.contains("[[attest]] #1: ADR-013 does not mention `flag`: "),
"{message}"
);
let right = journal_of(&[("ADR-013", &["flag"])]);
assert!(parse(attest, &right).is_ok());
}
#[test]
fn an_adr_named_only_inside_a_code_block_does_not_hold_a_decision() {
let text = "[[waive]]\nadr = \"ADR-020\"\ndate = \"2026-11-26\"\nreason = \"r\"\nitems = [\"export:a#f\"]\n";
let journal = adr::Journal::parse("## ADR-001: a\n```\n## ADR-020: x\n`export:a#f`\n```\n");
let message = format!("{}", parse(text, &journal).unwrap_err());
assert!(
message.contains("ADR-020 is not in rust/DECISIONS.md"),
"{message}"
);
}
#[test]
fn a_size_allowance_is_read_and_the_last_one_for_a_unit_counts() {
let entry = |adr: &str, max: &str| {
format!(
"[[size]]\nadr = \"{adr}\"\ndate = \"2026-12-02\"\nreason = \"r\"\nunit = \"src/scrape.py\"\nmax = {max}\n"
)
};
let journal = journal_of(&[
("ADR-001", &["src/scrape.py"]),
("ADR-002", &["src/scrape.py"]),
]);
let text = format!("{}\n{}", entry("ADR-001", "6"), entry("ADR-002", "4.5"));
let d = parse(&text, &journal).unwrap();
assert_eq!(d.sizes.len(), 2);
let size = d.size("src/scrape.py").unwrap();
assert_eq!((size.adr.as_str(), size.max), ("ADR-002", 4.5));
assert!(d.size("src/other.py").is_none());
}
#[test]
fn a_size_allowance_needs_a_unit_its_adr_names_and_a_max_over_the_cap() {
let text = "[[size]]\nadr = \"ADR-001\"\ndate = \"2026-12-02\"\nreason = \"r\"\nmax = 3\nlines = 9\n\n\
[[size]]\nadr = \"ADR-001\"\ndate = \"2026-12-02\"\nreason = \"r\"\nunit = \"src/b.py\"\nmax = \"6\"\n\n\
[[size]]\nadr = \"ADR-001\"\ndate = \"2026-12-02\"\nreason = \"r\"\nunit = \"src/c.py\"\nmax = 6\n";
let journal = journal_of(&[("ADR-001", &["src/b.py"])]);
let message = format!("{}", parse(text, &journal).unwrap_err());
for fault in [
"[[size]] #1: unknown key `lines`",
"[[size]] #1: `unit` is missing or empty",
"[[size]] #1: `max` must be a number greater than 3",
"[[size]] #2: `max` must be a number greater than 3",
"[[size]] #3: ADR-001 does not mention `src/c.py`",
] {
assert!(message.contains(fault), "{fault}\n{message}");
}
}
#[test]
fn a_reason_is_one_non_empty_line() {
assert!(reason_fault("because").is_none());
assert!(reason_fault("").is_some());
assert!(reason_fault(" ").is_some());
assert!(reason_fault("a\nb").is_some());
assert!(reason_fault("a\rb").is_some());
}
}