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 decision journal: `rust/DECISIONS.md`, where every `waive` and every `attest` leaves a
//! section in the project's format (`## ADR-007: title`, `Status`, `Context`, `Decision`,
//! `Consequences`). The number is the largest `## ADR-NNN` of the file plus one, never
//! renumbering; a decision written by hand counts like any other.
//!
//! A title is a `## ADR-NNN` line outside a code block (``` or ~~~): what an example cites in a
//! block is not a decision. The section of an ADR runs from its title to the next `## ` title,
//! also outside a code block; it is what the check of a decision reads (it must name what it
//! decides).
use std::path::Path;
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Result, bail};
use regex::Regex;
use super::super::evidence::{Opened, open};
/// The decision journal, from the repository root.
pub const ADR_FILE: &str = "rust/DECISIONS.md";
/// A decision title: `## ADR-012: ...` or `## ADR-012`, at the start of a line.
static TITLE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^## (ADR-(\d+))(?:[:\s]|$)").expect("a valid pattern"));
/// The journal text under the repository's file guard: missing gives `None`; a link that leaves
/// the repository, a folder or an unreadable file is an error.
pub(super) fn read(root: &Path) -> Result<Option<String>> {
match open(root, ADR_FILE) {
Opened::Absent => Ok(None),
Opened::Refused(why) => bail!("{ADR_FILE} is not opened: {why}"),
Opened::Text(text) => Ok(Some(text)),
}
}
/// A titled section of the journal.
struct Section {
number: u64,
/// The line of the title, counting from 1.
line: usize,
/// The title and everything after it up to the next `## ` title.
text: String,
}
/// The titled sections of a text, in order. A line in a code block is neither a title nor the end
/// of a section.
pub(super) struct Journal {
sections: Vec<Section>,
/// The text ends inside a code block that nothing closes.
unclosed: bool,
}
/// A code block fence line: its character, its length and what follows. At most three spaces in
/// front, otherwise it is an indented block and not a fence.
fn fence(line: &str) -> Option<(char, usize, &str)> {
let trimmed = line.trim_start_matches(' ');
if line.len() - trimmed.len() > 3 {
return None;
}
let ch = trimmed.chars().next().filter(|c| matches!(c, '`' | '~'))?;
let run = trimmed.chars().take_while(|c| *c == ch).count();
(run >= 3).then(|| (ch, run, &trimmed[run..]))
}
/// Appends `line` to the current section, when there is one.
fn append(sections: &mut [Section], current: bool, line: &str) {
if let Some(last) = sections.last_mut().filter(|_| current) {
last.text.push_str(line);
last.text.push('\n');
}
}
impl Journal {
pub(super) fn parse(text: &str) -> Self {
let mut sections: Vec<Section> = Vec::new();
// The open fence: its character and its length.
let mut open_fence: Option<(char, usize)> = None;
let mut current = false;
for (i, line) in text.lines().enumerate() {
if let Some((ch, len)) = open_fence {
// Only a fence of the same character, at least as long and with nothing after
// it, closes the block.
if fence(line)
.is_some_and(|(c, n, rest)| c == ch && n >= len && rest.trim().is_empty())
{
open_fence = None;
}
append(&mut sections, current, line);
continue;
}
if let Some((ch, len, rest)) = fence(line)
&& !(ch == '`' && rest.contains('`'))
{
open_fence = Some((ch, len));
append(&mut sections, current, line);
continue;
}
// A level 1 title also closes the current section.
if line == "#" || line.starts_with("# ") {
current = false;
continue;
}
if line == "##" || line.starts_with("## ") {
current = false;
if let Some(c) = TITLE.captures(line) {
sections.push(Section {
number: c[2].parse::<u64>().unwrap_or(u64::MAX),
line: i + 1,
text: format!("{line}\n"),
});
current = true;
}
continue;
}
append(&mut sections, current, line);
}
Self {
sections,
unclosed: open_fence.is_some(),
}
}
/// The lines of the titles of `id`: empty if the ADR is not titled, two or more if it is
/// titled twice.
/// Numbers are compared by value: `ADR-007` and `ADR-0007` are the same ADR.
pub(super) fn lines_of(&self, id: &str) -> Vec<usize> {
let Some(number) = number_of(id) else {
return Vec::new();
};
self.sections
.iter()
.filter(|s| s.number == number)
.map(|s| s.line)
.collect()
}
/// The section of `id`, when a single title carries it (numbers compared by value).
pub(super) fn section(&self, id: &str) -> Option<&str> {
let number = number_of(id)?;
let mut found = self.sections.iter().filter(|s| s.number == number);
let first = found.next()?;
found.next().is_none().then_some(first.text.as_str())
}
}
/// The number of an `ADR-NNN` id (as many digits as wanted), or `None` if it is not one. A number
/// too large to fit gives the same fallback as in `Journal::parse`.
fn number_of(id: &str) -> Option<u64> {
let digits = id.strip_prefix("ADR-")?;
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
Some(digits.parse::<u64>().unwrap_or(u64::MAX))
}
/// Before writing: the composed journal, read back with the reader, must show the new ADR once
/// and show it naming every thing its decision cites (the rule the reading of decisions
/// applies). Otherwise the write would produce an ADR that its own reading does not see: an
/// error, and nothing is written.
pub(super) fn verify(
existing: Option<&str>,
composed: &str,
id: &str,
decided: &[&str],
) -> Result<()> {
let before = Journal::parse(existing.unwrap_or_default());
if before.unclosed {
bail!(
"{ADR_FILE} ends inside a code block that is not closed: close the block (a line with ``` or ~~~), then run the command again; nothing was written"
);
}
let journal = Journal::parse(composed);
if journal.unclosed || journal.sections.len() != before.sections.len() + 1 {
bail!(
"{id} would change more of {ADR_FILE} than its own section once written (a name it cites holds a line break, a title or a code fence), so it would not be read back as written: nothing was written"
);
}
let lines = journal.lines_of(id);
let Some(section) = journal.section(id) else {
bail!(
"{id} would be titled {} times in {ADR_FILE} once written, so it would not be read back: fix the journal, then run the command again; nothing was written",
lines.len()
);
};
if let Some(missing) = decided.iter().find(|what| !names(section, what)) {
bail!(
"{id} would not name `{missing}` in {ADR_FILE} once written, so the decision would not hold: fix the journal, then run the command again; nothing was written"
);
}
Ok(())
}
/// The journal of the repository `root` (missing gives an empty journal), under the file guard.
pub(super) fn journal(root: &Path) -> Result<Journal> {
Ok(Journal::parse(&read(root)?.unwrap_or_default()))
}
/// A section names `thing` when it writes it between backticks: that is what `waive` and
/// `attest` write, and the form that is not confused with a longer id.
pub(super) fn names(section: &str, thing: &str) -> bool {
section.contains(&format!("`{thing}`"))
}
/// The next id: the largest title number plus one, on at least three digits. A number titled
/// twice changes nothing: the new one is always beyond the largest.
pub(super) fn next_id(text: Option<&str>) -> String {
let largest = Journal::parse(text.unwrap_or_default())
.sections
.iter()
.map(|s| s.number)
.max()
.unwrap_or(0);
format!("ADR-{:03}", largest.saturating_add(1))
}
/// What a section says; each field is one or more lines.
pub(super) struct Record<'a> {
pub title: &'a str,
pub context: &'a str,
pub decision: &'a str,
pub consequences: &'a str,
}
/// The journal once the section is added. A missing journal starts with a title; the section
/// always follows a blank line, whatever the end of the existing text.
pub(super) fn with_section(existing: Option<&str>, id: &str, date: &str, rec: &Record) -> String {
let mut out = match existing {
Some(text) => text.trim_end_matches('\n').to_string(),
None => "# Decisions".to_string(),
};
out.push_str(&format!(
"\n\n## {id}: {}\nStatus: accepted ({date})\nContext: {}\nDecision: {}\nConsequences: {}\n",
rec.title, rec.context, rec.decision, rec.consequences
));
out
}
/// Today's date, in UTC, in the format `YYYY-MM-DD`.
pub(super) fn today() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
date_of(secs)
}
/// The UTC date `secs` seconds after the Unix epoch.
pub(super) fn date_of(secs: u64) -> String {
crate::audit::utc(secs)[..10].to_string()
}
/// A date written `YYYY-MM-DD` that exists in the calendar (leap years included).
pub(super) fn is_date(text: &str) -> bool {
let parts: Vec<&str> = text.split('-').collect();
let [y, m, d] = parts[..] else {
return false;
};
if y.len() != 4 || m.len() != 2 || d.len() != 2 {
return false;
}
let (Ok(y), Ok(m), Ok(d)) = (y.parse::<i64>(), m.parse::<u32>(), d.parse::<u32>()) else {
return false;
};
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let days = match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return false,
};
(1..=days).contains(&d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_come_from_the_unix_epoch_in_utc() {
assert_eq!(date_of(0), "1970-01-01");
assert_eq!(date_of(86_399), "1970-01-01");
assert_eq!(date_of(86_400), "1970-01-02");
// The leap day, a year end and the first day of the next year.
assert_eq!(date_of(951_782_400), "2000-02-29");
assert_eq!(date_of(1_704_067_199), "2023-12-31");
assert_eq!(date_of(1_704_067_200), "2024-01-01");
assert_eq!(date_of(1_709_164_800), "2024-02-29");
assert_eq!(date_of(1_709_251_200), "2024-03-01");
// The day this module was written.
assert_eq!(date_of(1_795_651_200), "2026-11-26");
}
#[test]
fn a_date_is_valid_only_when_the_calendar_has_it() {
for ok in ["2026-11-26", "2024-02-29", "2000-02-29", "1999-12-31"] {
assert!(is_date(ok), "{ok}");
}
for bad in [
"2026-02-29",
"1900-02-29",
"2026-13-01",
"2026-00-10",
"2026-04-31",
"2026-4-1",
"26-04-01",
"2026/04/01",
"2026-04-01 ",
"",
] {
assert!(!is_date(bad), "{bad}");
}
}
#[test]
fn the_next_number_follows_the_largest_one_and_never_renumbers() {
assert_eq!(next_id(None), "ADR-001");
assert_eq!(next_id(Some("# Decisions\n")), "ADR-001");
let text = "# D\n\n## ADR-002: b\n\n## ADR-009: a\n\n## ADR-004: c\n";
assert_eq!(next_id(Some(text)), "ADR-010");
// Four digits and a title without a colon count; a deeper title or a mention does not.
let wide = "## ADR-0999: x\n## ADR-1000\n### ADR-5000: nested\ntext ## ADR-7000: inline\n";
assert_eq!(next_id(Some(wide)), "ADR-1001");
}
#[test]
fn a_number_titled_twice_still_gives_the_largest_plus_one() {
let text = "## ADR-003: a\n\n## ADR-007: b\n\n## ADR-007: c\n";
assert_eq!(next_id(Some(text)), "ADR-008");
assert_eq!(Journal::parse(text).lines_of("ADR-007"), [3, 5]);
assert!(Journal::parse(text).section("ADR-007").is_none());
assert!(Journal::parse(text).section("ADR-003").is_some());
}
#[test]
fn titles_are_read_at_the_start_of_a_line_only() {
let text =
"## ADR-001: a\nsee ## ADR-002: b\n### ADR-003: c\n## ADR-004: d\n## ADR-0050x\n";
let journal = Journal::parse(text);
let found: Vec<&str> = ["ADR-001", "ADR-002", "ADR-003", "ADR-004", "ADR-0050x"]
.into_iter()
.filter(|id| !journal.lines_of(id).is_empty())
.collect();
assert_eq!(found, ["ADR-001", "ADR-004"]);
}
#[test]
fn a_title_inside_a_code_block_is_not_a_title() {
let text = "# D\n\n## ADR-001: real\nbody\n\n```md\n## ADR-009: example\n```\n\n~~~\n## ADR-010: tilde example\n~~~\n\n## ADR-002: second\n";
let journal = Journal::parse(text);
assert!(journal.lines_of("ADR-009").is_empty());
assert!(journal.lines_of("ADR-010").is_empty());
assert_eq!(next_id(Some(text)), "ADR-003");
// The block is part of the section it is in, and does not close it.
let first = journal.section("ADR-001").unwrap();
assert!(first.contains("ADR-009: example"), "{first}");
assert!(first.contains("ADR-010: tilde example"), "{first}");
assert!(!first.contains("second"), "{first}");
}
#[test]
fn a_fence_closes_only_with_the_same_character_and_enough_of_it() {
// ```` opens; ``` does not close; ~~~ does not close; ```` closes.
let text = "````\n```\n## ADR-005: still code\n~~~\n````\n## ADR-006: real\n";
let journal = Journal::parse(text);
assert!(journal.lines_of("ADR-005").is_empty());
assert_eq!(journal.lines_of("ADR-006"), [6]);
// An unclosed fence covers the end of the text.
let open = "## ADR-001: a\n```\n## ADR-002: b\n";
assert!(Journal::parse(open).lines_of("ADR-002").is_empty());
// A block indented by four spaces is not a fence.
let indented = " ```\n## ADR-003: c\n";
assert_eq!(Journal::parse(indented).lines_of("ADR-003"), [2]);
// A backtick fence whose info line holds a backtick is not a fence.
let inline = "```a`b\n## ADR-004: d\n";
assert_eq!(Journal::parse(inline).lines_of("ADR-004"), [2]);
}
#[test]
fn a_section_runs_to_the_next_level_two_heading() {
let text =
"## ADR-001: a\none `x`\n### sub\nstill `y`\n## Notes\nnot part\n## ADR-002: b\n";
let journal = Journal::parse(text);
let a = journal.section("ADR-001").unwrap();
assert!(names(a, "x") && names(a, "y"), "{a}");
assert!(!a.contains("not part"), "{a}");
// A name is named only in full and between backticks.
assert!(!names("`export:a#fg`", "export:a#f"));
assert!(!names("export:a#f", "export:a#f"));
}
#[test]
fn a_section_is_appended_after_a_blank_line_in_the_project_format() {
let rec = Record {
title: "Waive 2 obligations",
context: "two things",
decision: "waived",
consequences: "nothing proves them",
};
let first = with_section(None, "ADR-001", "2026-11-26", &rec);
assert_eq!(
first,
"# Decisions\n\n## ADR-001: Waive 2 obligations\nStatus: accepted (2026-11-26)\nContext: two things\nDecision: waived\nConsequences: nothing proves them\n"
);
let second = with_section(Some(&first), "ADR-002", "2026-11-27", &rec);
assert!(second.starts_with(&first));
assert!(
second.contains("\n\n## ADR-002: Waive 2 obligations\nStatus: accepted (2026-11-27)\n")
);
// A text with no final newline, or with several, still gets a blank line.
let loose = with_section(Some("# Mine\n\nnotes"), "ADR-001", "2026-11-26", &rec);
assert!(loose.starts_with("# Mine\n\nnotes\n\n## ADR-001:"));
let many = with_section(Some("# Mine\n\n\n\n"), "ADR-001", "2026-11-26", &rec);
assert!(many.starts_with("# Mine\n\n## ADR-001:"));
}
#[test]
fn adr_numbers_are_compared_by_value_not_by_text() {
let text = "## ADR-007: a\n`x`\n\n## ADR-0007: b\n`y`\n";
let journal = Journal::parse(text);
// The same number, titled twice, however the one citing it writes it.
for cited in ["ADR-007", "ADR-0007", "ADR-7"] {
assert_eq!(journal.lines_of(cited), [1, 4], "{cited}");
assert!(journal.section(cited).is_none(), "{cited}");
}
// A single title: `ADR-7` and `ADR-007` both designate it.
let one = Journal::parse("## ADR-007: a\n`x`\n");
assert_eq!(one.lines_of("ADR-7"), [1]);
assert!(one.section("ADR-0007").is_some());
assert!(one.lines_of("ADR-8").is_empty());
// What is not an ADR id designates nothing.
for odd in ["", "ADR-", "ADR-x", "adr-7", "ADR-7a", " ADR-7"] {
assert!(one.lines_of(odd).is_empty(), "{odd:?}");
}
}
#[test]
fn a_level_one_heading_closes_a_section_but_not_inside_a_code_block() {
let text = "## ADR-001: a\n`x`\n# Other\n`y`\n";
let a = Journal::parse(text).section("ADR-001").unwrap().to_string();
assert!(names(&a, "x") && !names(&a, "y"), "{a}");
let fenced = "## ADR-001: a\n`x`\n```\n# not a heading\n```\n`y`\n";
let a = Journal::parse(fenced)
.section("ADR-001")
.unwrap()
.to_string();
assert!(names(&a, "x") && names(&a, "y"), "{a}");
}
#[test]
fn verify_refuses_a_journal_the_reader_would_not_show_the_new_adr_in() {
let rec = Record {
title: "Waive 1 obligation",
context: "c",
decision: "d",
consequences: "e",
};
let compose = |existing: Option<&str>| {
let id = next_id(existing);
let composed = with_section(existing, &id, "2026-11-26", &rec);
(id, composed)
};
// An unclosed block: the ADR would fall inside it.
let open = "# D\n\n```md\n## ADR-001: example\n";
let (id, composed) = compose(Some(open));
let err = verify(Some(open), &composed, &id, &[])
.unwrap_err()
.to_string();
assert!(
err.contains("not closed") && err.contains("nothing was written"),
"{err}"
);
// A sound journal: the ADR is seen, once.
let (id, composed) = compose(Some("# D\n"));
verify(Some("# D\n"), &composed, &id, &[]).unwrap();
// A thing the decision cites and the section does not name: refused.
let err = verify(Some("# D\n"), &composed, &id, &["absent"])
.unwrap_err()
.to_string();
assert!(err.contains("would not name"), "{err}");
// A missing journal: it starts with its title, and the ADR is seen in it.
let (id, composed) = compose(None);
verify(None, &composed, &id, &[]).unwrap();
}
}