Skip to main content

xtask/
stamp.rs

1//! The merge-time stamp (increment-allocation track, Slice 1).
2//!
3//! On merge, [`plan`] reads the pending files, assigns the next version(s) in
4//! merge order and the next ADR number(s), and [`apply`] materialises them:
5//! it runs `scripts/bump-version.sh`, inserts the changelog row(s), writes each
6//! `design/decisions/NNNN-<slug>.md` and its index row, and deletes the consumed
7//! pending files. Deleting what it consumes is what makes a re-run a no-op —
8//! which is why version assignment and ADR materialisation are one atomic pass
9//! (the entangled-by-delete finding, proposal #689 DECISION A).
10//!
11//! The version bump is injected (see [`apply`]) so the whole flow is testable on
12//! a fixture tree without running the real, side-effect-heavy bump script.
13
14use crate::{Adr, Level, validated_pending_in};
15use std::fmt;
16use std::fs;
17use std::io;
18use std::path::{Path, PathBuf};
19
20/// A semantic version `MAJOR.MINOR.PATCH`.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct Version {
23    pub major: u64,
24    pub minor: u64,
25    pub patch: u64,
26}
27
28impl Version {
29    /// The next version for `level`: `minor` bumps MINOR and resets PATCH,
30    /// `patch` bumps PATCH. (MAJOR is 0 pre-1.0 and never moved here.)
31    pub fn next(self, level: &Level) -> Version {
32        match level {
33            Level::Minor => Version {
34                minor: self.minor + 1,
35                patch: 0,
36                ..self
37            },
38            Level::Patch => Version {
39                patch: self.patch + 1,
40                ..self
41            },
42        }
43    }
44
45    /// Parse an `X.Y.Z` string.
46    pub fn parse(s: &str) -> Option<Version> {
47        let mut it = s.trim().split('.');
48        let major = it.next()?.parse().ok()?;
49        let minor = it.next()?.parse().ok()?;
50        let patch = it.next()?.parse().ok()?;
51        if it.next().is_some() {
52            return None;
53        }
54        Some(Version {
55            major,
56            minor,
57            patch,
58        })
59    }
60}
61
62impl fmt::Display for Version {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
65    }
66}
67
68impl Version {
69    /// The ADR/index version string, following the corpus convention: a MINOR
70    /// increment is `MAJOR.MINOR` (`0.186`), a PATCH increment keeps its patch
71    /// (`0.185.1`, like the existing `v0.29.1`). Since [`next`](Version::next)
72    /// resets PATCH to 0 for a minor bump, `patch == 0` is exactly the minor case.
73    pub fn short(self) -> String {
74        if self.patch == 0 {
75            format!("{}.{}", self.major, self.minor)
76        } else {
77            self.to_string()
78        }
79    }
80}
81
82/// One pending increment stamped with the version it will ship as.
83#[derive(Debug)]
84pub struct Stamped {
85    /// The pending file that produced this (relative name under `design/pending/`).
86    pub file: String,
87    pub version: Version,
88    pub changelog: String,
89    pub adrs: Vec<Adr>,
90    /// Greenfield reference rule ids this increment closes (#1001) — already
91    /// validated (syntax and existence) by `validated_pending_in`.
92    pub closes_rule: Vec<String>,
93    /// Gated greenfield-status probes this increment acknowledges moving — the
94    /// stamp rewrites only these rows of the table.
95    pub probes: Vec<String>,
96    /// Growth probes this increment raises, with reasons (#3679); the stamp
97    /// records each actual rise in `design/greenfield-status-raises.md`.
98    pub raises: Vec<crate::Raise>,
99    /// The increment's breaking-change note (#3178), if it declared one; the
100    /// stamp writes it, under this increment's version, into the Book's
101    /// `reference/upgrading.md`.
102    pub breaking: Option<String>,
103}
104
105/// The full stamp plan for the pending files present.
106#[derive(Debug)]
107pub struct Plan {
108    pub base_version: Version,
109    pub increments: Vec<Stamped>,
110    /// The next free ADR number, for materialisation.
111    pub first_adr_number: u32,
112    /// Growth-probe rises measured at stamp time (committed row before the stamp
113    /// to the live reading), filled by the CLI after [`plan`] (which reads no
114    /// probes). A raise an increment declares is ledgered only if its probe
115    /// appears here; empty means no growth probe rose.
116    pub growth_rises: Vec<crate::greenfield_status::GrowthRise>,
117}
118
119impl Plan {
120    /// The version the manifests end on — the last increment's, or the base if
121    /// there is nothing to stamp.
122    pub fn final_version(&self) -> Version {
123        self.increments
124            .last()
125            .map(|s| s.version)
126            .unwrap_or(self.base_version)
127    }
128
129    pub fn is_empty(&self) -> bool {
130        self.increments.is_empty()
131    }
132}
133
134/// Build the plan for `root`: read the workspace version and the pending files,
135/// and assign each pending file (in filename order — a deterministic proxy for
136/// merge order) its own next version. Returns validation errors verbatim.
137pub fn plan(root: &Path) -> Result<Plan, Vec<String>> {
138    let cargo = root.join("Cargo.toml");
139    let cargo_src = fs::read_to_string(&cargo)
140        .map_err(|e| vec![format!("cannot read {}: {e}", cargo.display())])?;
141    let base_version = parse_workspace_version(&cargo_src)
142        .ok_or_else(|| vec![format!("no `version = \"X.Y.Z\"` in {}", cargo.display())])?;
143
144    let pending = validated_pending_in(root)?;
145    let first_adr_number = next_adr_number(root).map_err(|e| {
146        vec![format!(
147            "cannot scan {}: {e}",
148            root.join("design/decisions").display()
149        )]
150    })?;
151
152    let mut version = base_version;
153    let mut increments = Vec::new();
154    for (file, p) in pending {
155        version = version.next(&p.level);
156        increments.push(Stamped {
157            file,
158            version,
159            changelog: p.changelog,
160            adrs: p.adrs,
161            closes_rule: p.closes_rule,
162            probes: p.probes,
163            raises: p.raises,
164            breaking: p.breaking,
165        });
166    }
167
168    Ok(Plan {
169        base_version,
170        increments,
171        first_adr_number,
172        growth_rises: Vec::new(),
173    })
174}
175
176/// Apply `plan` to `root`: write ADR files + index rows, insert changelog rows,
177/// run `bump` for the final version, then delete the consumed pending files.
178///
179/// The whole thing is transactional. Every write is *staged* in memory first —
180/// the changelog and index edits are computed, ADR contents rendered, and any
181/// ADR-number collision detected — before a single byte hits disk, so a
182/// malformed table or a stale number fails with nothing written. During the
183/// commit phase the tree is mutated in a fixed order (ADR files, changelog,
184/// index, then the flaky `bump`); if any step fails, the tree is *rolled back*
185/// to its pre-apply state — the edited docs restored and the freshly written
186/// ADR files removed. Only once everything has succeeded are the consumed
187/// pending files deleted.
188///
189/// This is what makes a re-run safe: a failed run (a `bump` that errors, most
190/// likely) leaves the pending files intact *and* no partial changelog/ADR edits
191/// behind, so a retry recomputes the identical plan rather than duplicating rows
192/// or re-numbering ADRs past the files a previous attempt wrote. (`bump`'s own
193/// partial effects on the manifests it rewrites are outside this function's
194/// reach; the CLI additionally refuses to `--apply` on a dirty worktree so that
195/// debris is surfaced too.)
196///
197/// `bump` is injected so tests exercise the whole flow on a fixture tree with a
198/// stub that just rewrites the fixture's `Cargo.toml`. `pr_number` is the PR
199/// whose merge triggered *this run*, if it could be recovered from the
200/// triggering commit message (#1001) — `None` records a ledger row without
201/// one (e.g. a local `stamp --apply` run outside CI) rather than guessing.
202/// Only trusted for a single-increment plan: a multi-increment run (a prior
203/// run's failed push left its pending file for this one to pick up) has no
204/// way to tell which increment the recovered number actually belongs to, so
205/// every row in that case gets a blank cell instead of one confidently wrong
206/// number applied to increments from different PRs.
207pub fn apply(
208    root: &Path,
209    plan: &Plan,
210    pr_number: Option<u32>,
211    bump: impl Fn(Version) -> io::Result<()>,
212) -> io::Result<()> {
213    if plan.is_empty() {
214        return Ok(());
215    }
216
217    let decisions = root.join("design/decisions");
218    // The changelog rows go to the Book's Unreleased page; `cargo xtask
219    // release-page` later cuts them into a release's page (#3868).
220    let changelog_path = root.join(crate::release_pages::UNRELEASED_PAGE);
221    let readme_path = decisions.join("README.md");
222    let rule_ledger_path = root.join("design/greenfield-status-rules.md");
223    let raise_ledger_path = root.join(RAISE_LEDGER_PATH);
224    let upgrading_path = root.join(crate::release_notes::UPGRADING_PAGE);
225
226    // `pr_number` names the PR whose merge triggered *this run*, not any one
227    // increment in `plan` — those are usually the same increment, but not
228    // always: a stamp run that exhausts its push retries (`stamp.yml`) exits
229    // without consuming its pending file, so the *next* run's plan can carry
230    // two increments from two different PRs. Attributing both to the second
231    // PR would be a confidently wrong provenance record — worse than the
232    // blank cell this design already accepts for "couldn't recover a PR
233    // number" — so the recovered number is only trusted when it can only mean
234    // one increment.
235    let ledger_pr_number = if plan.increments.len() == 1 {
236        pr_number
237    } else {
238        None
239    };
240
241    // --- Stage: compute every write in memory. Nothing is on disk yet, so a
242    // fault here (a missing table anchor, an ADR-number collision) aborts with
243    // the tree untouched. ---
244    let mut number = plan.first_adr_number;
245    let mut adr_files: Vec<(PathBuf, String)> = Vec::new();
246    let mut changelog_rows = Vec::new();
247    let mut index_rows = Vec::new();
248    let mut rule_ledger_rows_all = Vec::new();
249    let mut raise_ledger_rows_all = Vec::new();
250    let mut upgrading_entries = Vec::new();
251    for inc in &plan.increments {
252        for adr in &inc.adrs {
253            let path = decisions.join(format!("{number:04}-{}.md", adr.slug));
254            // Refuse to clobber an ADR that already exists: a number that is not
255            // actually free (e.g. debris from a prior partial run) must surface,
256            // not be silently overwritten and the series restarted.
257            if path.exists() {
258                return Err(io::Error::new(
259                    io::ErrorKind::AlreadyExists,
260                    format!(
261                        "ADR {} already exists — refusing to overwrite",
262                        path.display()
263                    ),
264                ));
265            }
266            adr_files.push((path, adr_file_contents(number, adr, inc.version)));
267            index_rows.push(index_row(number, adr, inc.version));
268            number += 1;
269        }
270        changelog_rows.push(changelog_row(inc.version, &inc.changelog));
271        rule_ledger_rows_all.extend(rule_ledger_rows(inc, ledger_pr_number));
272        raise_ledger_rows_all.extend(raise_ledger_rows(inc, &plan.growth_rises, ledger_pr_number));
273        if let Some(note) = &inc.breaking {
274            upgrading_entries.push(crate::release_notes::upgrading_entry(inc.version, note));
275        }
276    }
277
278    // Newest on top: the highest version/number is applied last, so reverse the
279    // ascending lists before prepending them as a block.
280    changelog_rows.reverse();
281    index_rows.reverse();
282    rule_ledger_rows_all.reverse();
283    raise_ledger_rows_all.reverse();
284    upgrading_entries.reverse();
285
286    let changelog_before = fs::read_to_string(&changelog_path)?;
287    let changelog_after =
288        insert_after_table_separator(&changelog_before, "| Version |", &changelog_rows)
289            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
290
291    // Only touch the index when there are ADRs to add; `None` means "leave it".
292    let readme_edit = if index_rows.is_empty() {
293        None
294    } else {
295        let before = fs::read_to_string(&readme_path)?;
296        let after = insert_after_table_separator(&before, "| # | Decision |", &index_rows)
297            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
298        Some((before, after))
299    };
300
301    // Only touch the ledger when some increment actually closes a rule.
302    // Unlike the changelog/index, this file may not exist yet — no increment
303    // has ever cited `closes_rule` before #1001 — so a missing file synthesises
304    // a fresh header rather than erroring; `ledger_before` stays `None` in that
305    // case so a rollback removes the file instead of restoring stale content.
306    let ledger_existed = rule_ledger_path.exists();
307    let ledger_edit = if rule_ledger_rows_all.is_empty() {
308        None
309    } else {
310        let ledger_before = if ledger_existed {
311            Some(fs::read_to_string(&rule_ledger_path)?)
312        } else {
313            None
314        };
315        let base = ledger_before
316            .clone()
317            .unwrap_or_else(|| RULE_LEDGER_HEADER.to_string());
318        let after = insert_after_table_separator(&base, "| Rule |", &rule_ledger_rows_all)
319            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
320        Some((ledger_before, after))
321    };
322
323    // Same shape for the raise ledger: touched only when a declared raise
324    // actually happened, synthesised on first use, removed on rollback if new.
325    let raise_existed = raise_ledger_path.exists();
326    let raise_edit = if raise_ledger_rows_all.is_empty() {
327        None
328    } else {
329        let before = if raise_existed {
330            Some(fs::read_to_string(&raise_ledger_path)?)
331        } else {
332            None
333        };
334        let base = before
335            .clone()
336            .unwrap_or_else(|| RAISE_LEDGER_HEADER.to_string());
337        let after = insert_after_table_separator(&base, "| Probe |", &raise_ledger_rows_all)
338            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
339        Some((before, after))
340    };
341
342    // Only touch the upgrading page when some increment declared `breaking:` —
343    // a tree whose increments break nothing never needs the page to exist, which
344    // keeps the stamp backward-compatible with fixtures and forks that lack it.
345    let upgrading_edit = if upgrading_entries.is_empty() {
346        None
347    } else {
348        let before = fs::read_to_string(&upgrading_path)?;
349        let after = crate::release_notes::insert_upgrading_entries(&before, &upgrading_entries)
350            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
351        Some((before, after))
352    };
353
354    // --- Commit: mutate the tree. Track what we write so a mid-flight failure
355    // (the injected `bump` is the likely one) can be unwound. ---
356    let mut written_adrs: Vec<PathBuf> = Vec::new();
357    let commit = (|| -> io::Result<()> {
358        for (path, contents) in &adr_files {
359            fs::write(path, contents)?;
360            written_adrs.push(path.clone());
361        }
362        fs::write(&changelog_path, &changelog_after)?;
363        if let Some((_, after)) = &readme_edit {
364            fs::write(&readme_path, after)?;
365        }
366        if let Some((_, after)) = &ledger_edit {
367            fs::write(&rule_ledger_path, after)?;
368        }
369        if let Some((_, after)) = &raise_edit {
370            fs::write(&raise_ledger_path, after)?;
371        }
372        if let Some((_, after)) = &upgrading_edit {
373            fs::write(&upgrading_path, after)?;
374        }
375        // The flaky step, run last so its failure unwinds cleanly here rather
376        // than stranding a changelog that cites a version the manifests never
377        // reached.
378        bump(plan.final_version())
379    })();
380
381    if let Err(e) = commit {
382        // Roll back, best effort: restore the edited docs to their pre-apply
383        // bytes and delete the ADR files we created. The pending files were not
384        // touched (they are consumed only below), so the run is a clean retry.
385        let _ = fs::write(&changelog_path, &changelog_before);
386        if let Some((before, _)) = &readme_edit {
387            let _ = fs::write(&readme_path, before);
388        }
389        if let Some((before, _)) = &upgrading_edit {
390            let _ = fs::write(&upgrading_path, before);
391        }
392        if let Some((before, _)) = &ledger_edit {
393            match before {
394                Some(orig) => {
395                    let _ = fs::write(&rule_ledger_path, orig);
396                }
397                None => {
398                    let _ = fs::remove_file(&rule_ledger_path);
399                }
400            }
401        }
402        if let Some((before, _)) = &raise_edit {
403            match before {
404                Some(orig) => {
405                    let _ = fs::write(&raise_ledger_path, orig);
406                }
407                None => {
408                    let _ = fs::remove_file(&raise_ledger_path);
409                }
410            }
411        }
412        for path in &written_adrs {
413            let _ = fs::remove_file(path);
414        }
415        return Err(e);
416    }
417
418    // Consume last: delete each pending file only once everything else has
419    // succeeded, so a re-run finds nothing to do.
420    for inc in &plan.increments {
421        fs::remove_file(root.join("design/pending").join(&inc.file))?;
422    }
423    Ok(())
424}
425
426// --- Pure rendering / parsing helpers (unit-tested without the filesystem) ---
427
428/// The `[workspace.package] version = "X.Y.Z"` from a `Cargo.toml`. Scoped to
429/// the `[workspace.package]` section: the first line-anchored `version = "..."`
430/// *within that table*, not a `version` under some other section (e.g. a stray
431/// top-level `[package]`) nor the inline `version = "..."` inside a dependency
432/// spec — the same value `bump-version.sh` rewrites.
433pub fn parse_workspace_version(cargo_toml: &str) -> Option<Version> {
434    let mut in_section = false;
435    for line in cargo_toml.lines() {
436        let trimmed = line.trim();
437        // A `[section]` header ends the previous table and opens a new one.
438        if trimmed.starts_with('[') && trimmed.ends_with(']') {
439            in_section = trimmed == "[workspace.package]";
440            continue;
441        }
442        if in_section
443            && let Some(value) = line
444                .strip_prefix("version = \"")
445                .and_then(|r| r.strip_suffix('"'))
446        {
447            return Version::parse(value);
448        }
449    }
450    None
451}
452
453/// The next free ADR number: one past the highest `NNNN-*.md` in
454/// `design/decisions`. Errors if the directory can't be read — a swallowed
455/// failure would silently default to `1` and restart the ADR series.
456pub fn next_adr_number(root: &Path) -> io::Result<u32> {
457    let dir = root.join("design/decisions");
458    let mut max = 0;
459    for entry in fs::read_dir(&dir)? {
460        let name = entry?.file_name().to_string_lossy().into_owned();
461        let bytes = name.as_bytes();
462        let is_adr = name.ends_with(".md")
463            && bytes.len() > 5
464            && bytes[4] == b'-'
465            && bytes[..4].iter().all(u8::is_ascii_digit);
466        if is_adr && let Ok(n) = name[..4].parse::<u32>() {
467            max = max.max(n);
468        }
469    }
470    Ok(max + 1)
471}
472
473/// The changelog table row for a stamped increment.
474pub fn changelog_row(version: Version, blurb: &str) -> String {
475    format!("| **v{version}** | {blurb} |")
476}
477
478/// The `design/decisions/NNNN-<slug>.md` file contents: a `# NNNN — <title>`
479/// heading, a status line carrying the version, then the body verbatim.
480pub fn adr_file_contents(number: u32, adr: &Adr, version: Version) -> String {
481    format!(
482        "# {number:04} — {title}\n\n- **Status:** {status} (v{ver})\n\n{body}\n",
483        title = adr.title,
484        status = adr.status(),
485        ver = version.short(),
486        body = adr.body,
487    )
488}
489
490/// The `design/decisions/README.md` index row for a materialised ADR.
491pub fn index_row(number: u32, adr: &Adr, version: Version) -> String {
492    format!(
493        "| [{number:04}]({number:04}-{slug}.md) | **{title}** (v{ver}) — {summary} | {status} (v{ver}) |",
494        slug = adr.slug,
495        title = adr.title,
496        ver = version.short(),
497        summary = adr.summary(),
498        status = adr.status(),
499    )
500}
501
502/// The header `design/greenfield-status-rules.md` is synthesised with the first
503/// time any increment closes a rule — this file has no other reason to exist,
504/// so `apply` doesn't require it pre-created the way it does the changelog and
505/// the decisions index.
506const RULE_LEDGER_HEADER: &str = "<!-- GENERATED, APPEND-ONLY — written by `cargo xtask stamp \
507--apply` (xtask/src/stamp.rs) at merge, one row per rule id an increment cites in its \
508`closes_rule` frontmatter (#1001).\n     Read by `cargo xtask greenfield-status` to populate \
509the reference's rule-citation surface. Do not hand-edit. -->\n\n# Rules closed\n\n\
510| Rule | Version | PR | Changelog |\n|---|---|---|---|\n";
511
512/// One `design/greenfield-status-rules.md` row per rule id `inc` closes — empty
513/// if `inc.closes_rule` is empty. `pr` renders as `#NNNN`, or the empty string
514/// when it couldn't be recovered (kept as an empty cell, not a placeholder like
515/// `"unknown"`, so the table stays a clean Markdown grid either way).
516pub fn rule_ledger_rows(inc: &Stamped, pr: Option<u32>) -> Vec<String> {
517    let pr_cell = pr.map(|n| format!("#{n}")).unwrap_or_default();
518    inc.closes_rule
519        .iter()
520        .map(|rule| {
521            format!(
522                "| {rule} | v{} | {pr_cell} | {} |",
523                inc.version, inc.changelog
524            )
525        })
526        .collect()
527}
528
529/// Where the raise ledger lives, relative to the repo root.
530pub const RAISE_LEDGER_PATH: &str = "design/greenfield-status-raises.md";
531
532/// The header `design/greenfield-status-raises.md` is synthesised with the first
533/// time an increment raises a growth probe (#3679, ADR 0389/0390 amended).
534const RAISE_LEDGER_HEADER: &str = "<!-- GENERATED, APPEND-ONLY — written by `cargo xtask stamp \
535--apply` (xtask/src/stamp.rs) at merge, one row per growth probe an increment raises with its \
536`raises` frontmatter (#3679).\n     `from` is the probe's committed leading count before the \
537stamp and `to` the live count the stamp commits; a PR that moves no growth probe upward writes \
538nothing here. Do not hand-edit. -->\n\n# Growth-probe raises\n\n\
539| Probe | From | To | Version | PR | Reason |\n|---|---|---|---|---|---|\n";
540
541/// One `design/greenfield-status-raises.md` row per growth probe `inc` raises
542/// *and* that actually rose (`rises`: the committed row before the stamp to the
543/// live reading). A declared raise whose probe did not rise is a stale
544/// declaration and records nothing. When one stamp run covers several
545/// increments that raise the same probe, each row carries the run's whole
546/// from/to, since the stamp reads the probes once. `pr` as in
547/// [`rule_ledger_rows`].
548pub fn raise_ledger_rows(
549    inc: &Stamped,
550    rises: &[crate::greenfield_status::GrowthRise],
551    pr: Option<u32>,
552) -> Vec<String> {
553    let pr_cell = pr.map(|n| format!("#{n}")).unwrap_or_default();
554    inc.raises
555        .iter()
556        .filter_map(|raise| {
557            let rise = rises.iter().find(|r| r.probe == raise.probe)?;
558            Some(format!(
559                "| {} | {} | {} | v{} | {pr_cell} | {} |",
560                raise.probe, rise.from, rise.to, inc.version, raise.reason
561            ))
562        })
563        .collect()
564}
565
566/// Insert `rows` (already newest-first) immediately after the separator line of
567/// the table whose header row contains `header_anchor` (e.g. `"| Version |"`).
568/// Anchoring on the header — rather than the first separator in the file — keeps
569/// the insert correct if another table (a legend, say) is ever added above.
570pub fn insert_after_table_separator(
571    md: &str,
572    header_anchor: &str,
573    rows: &[String],
574) -> Result<String, String> {
575    if rows.is_empty() {
576        return Ok(md.to_string());
577    }
578    let mut out = Vec::new();
579    let mut seen_header = false;
580    let mut inserted = false;
581    for line in md.lines() {
582        out.push(line.to_string());
583        if inserted {
584            continue;
585        }
586        if !seen_header {
587            seen_header = line.contains(header_anchor);
588        } else if is_table_separator(line) {
589            out.extend(rows.iter().cloned());
590            inserted = true;
591        }
592    }
593    if !inserted {
594        return Err(format!(
595            "no table with header {header_anchor:?} (and a `|---|` separator) to insert after"
596        ));
597    }
598    // Preserve a trailing newline if the input had one.
599    let mut joined = out.join("\n");
600    if md.ends_with('\n') {
601        joined.push('\n');
602    }
603    Ok(joined)
604}
605
606/// A Markdown table separator row — `|`, `-`, `:` and spaces only, with at least
607/// one `-`.
608fn is_table_separator(line: &str) -> bool {
609    let t = line.trim();
610    t.starts_with('|') && t.contains('-') && t.chars().all(|c| matches!(c, '|' | '-' | ':' | ' '))
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    fn adr(slug: &str, title: &str) -> Adr {
618        Adr {
619            slug: slug.into(),
620            title: title.into(),
621            summary: None,
622            status: None,
623            body: "**Decision.** Do the thing.".into(),
624        }
625    }
626
627    fn stamped_with_raises(raises: Vec<crate::Raise>) -> Stamped {
628        Stamped {
629            file: "x.md".into(),
630            version: Version::parse("0.250.3").unwrap(),
631            changelog: "c".into(),
632            adrs: vec![],
633            closes_rule: vec![],
634            probes: vec![],
635            raises,
636            breaking: None,
637        }
638    }
639
640    #[test]
641    fn raise_ledger_rows_record_only_actual_rises() {
642        use crate::greenfield_status::GrowthRise;
643        let inc = stamped_with_raises(vec![
644            crate::Raise {
645                probe: "ts_writes".into(),
646                reason: "no typed node for Y yet (#1)".into(),
647            },
648            crate::Raise {
649                probe: "ts_any".into(),
650                reason: "stale declaration".into(),
651            },
652        ]);
653        let rises = [GrowthRise {
654            probe: "ts_writes",
655            from: 1502,
656            to: 1510,
657        }];
658        assert_eq!(
659            raise_ledger_rows(&inc, &rises, Some(42)),
660            vec!["| ts_writes | 1502 | 1510 | v0.250.3 | #42 | no typed node for Y yet (#1) |"]
661        );
662        // No PR recovered: an empty cell, not a placeholder.
663        assert!(raise_ledger_rows(&inc, &rises, None)[0].contains("| v0.250.3 |  |"));
664        assert!(raise_ledger_rows(&inc, &[], Some(42)).is_empty());
665        assert!(raise_ledger_rows(&stamped_with_raises(vec![]), &rises, None).is_empty());
666    }
667
668    #[test]
669    fn raise_ledger_header_has_the_anchored_table() {
670        let row = "| ts_any | 1 | 2 | v0.1.1 |  | why |".to_string();
671        let out = insert_after_table_separator(
672            RAISE_LEDGER_HEADER,
673            "| Probe |",
674            std::slice::from_ref(&row),
675        )
676        .unwrap();
677        assert!(out.trim_end().ends_with(&row));
678    }
679
680    #[test]
681    fn version_next() {
682        let v = Version {
683            major: 0,
684            minor: 185,
685            patch: 0,
686        };
687        assert_eq!(v.next(&Level::Minor).to_string(), "0.186.0");
688        assert_eq!(v.next(&Level::Patch).to_string(), "0.185.1");
689        let p = Version {
690            major: 0,
691            minor: 185,
692            patch: 3,
693        };
694        assert_eq!(p.next(&Level::Minor).to_string(), "0.186.0");
695    }
696
697    #[test]
698    fn parse_workspace_version_ignores_dep_specs() {
699        let cargo = "[workspace.package]\nversion = \"0.185.0\"\n\n[workspace.dependencies]\nbynk = { path = \"bynk\", version = \"0.185.0\" }\n";
700        assert_eq!(
701            parse_workspace_version(cargo).unwrap().to_string(),
702            "0.185.0"
703        );
704    }
705
706    #[test]
707    fn parse_workspace_version_is_scoped_to_the_workspace_package_table() {
708        // A line-anchored `version` outside `[workspace.package]` (here a stray
709        // top-level `[package]`) must not be mistaken for the workspace version.
710        let cargo = "[package]\nname = \"root\"\nversion = \"9.9.9\"\n\n[workspace.package]\nversion = \"0.185.0\"\n";
711        assert_eq!(
712            parse_workspace_version(cargo).unwrap().to_string(),
713            "0.185.0"
714        );
715    }
716
717    #[test]
718    fn parse_workspace_version_none_without_the_table() {
719        // A bare top-level `version` with no `[workspace.package]` table is not
720        // the workspace version.
721        assert!(parse_workspace_version("version = \"1.2.3\"\n").is_none());
722    }
723
724    #[test]
725    fn changelog_row_format() {
726        let v = Version {
727            major: 0,
728            minor: 186,
729            patch: 0,
730        };
731        assert_eq!(
732            changelog_row(v, "Add a thing"),
733            "| **v0.186.0** | Add a thing |"
734        );
735    }
736
737    #[test]
738    fn version_short_follows_the_corpus_convention() {
739        // Minor (patch == 0) → MAJOR.MINOR; patch → full.
740        assert_eq!(
741            Version {
742                major: 0,
743                minor: 186,
744                patch: 0
745            }
746            .short(),
747            "0.186"
748        );
749        assert_eq!(
750            Version {
751                major: 0,
752                minor: 185,
753                patch: 1
754            }
755            .short(),
756            "0.185.1"
757        );
758    }
759
760    #[test]
761    fn adr_file_and_index_row_use_the_short_version() {
762        let v = Version {
763            major: 0,
764            minor: 186,
765            patch: 0,
766        };
767        let a = adr("a-slug", "The title");
768        let file = adr_file_contents(206, &a, v);
769        assert!(file.starts_with("# 0206 — The title\n"));
770        // MINOR-only, matching every existing ADR — not the full 0.186.0.
771        assert!(file.contains("- **Status:** Accepted (v0.186)"));
772        assert!(file.trim_end().ends_with("Do the thing."));
773
774        let row = index_row(206, &a, v);
775        assert_eq!(
776            row,
777            "| [0206](0206-a-slug.md) | **The title** (v0.186) — The title | Accepted (v0.186) |"
778        );
779    }
780
781    #[test]
782    fn patch_increment_index_row_keeps_the_patch() {
783        let v = Version {
784            major: 0,
785            minor: 185,
786            patch: 1,
787        };
788        let a = adr("s", "T");
789        assert!(index_row(9, &a, v).contains("(v0.185.1)"));
790    }
791
792    #[test]
793    fn index_row_uses_explicit_summary_and_status() {
794        let v = Version {
795            major: 0,
796            minor: 1,
797            patch: 0,
798        };
799        let a = Adr {
800            slug: "s".into(),
801            title: "T".into(),
802            summary: Some("the distillation".into()),
803            status: Some("Proposed".into()),
804            body: "b".into(),
805        };
806        assert_eq!(
807            index_row(7, &a, v),
808            "| [0007](0007-s.md) | **T** (v0.1) — the distillation | Proposed (v0.1) |"
809        );
810    }
811
812    #[test]
813    fn insert_prepends_after_the_anchored_table_newest_first() {
814        let md =
815            "## Recent increments\n\n| Version | Highlights |\n|---|---|\n| **v0.185.0** | Old |\n";
816        let out = insert_after_table_separator(
817            md,
818            "| Version |",
819            &["| NEW1 |".into(), "| NEW2 |".into()],
820        )
821        .unwrap();
822        let lines: Vec<&str> = out.lines().collect();
823        let sep = lines.iter().position(|l| *l == "|---|---|").unwrap();
824        assert_eq!(lines[sep + 1], "| NEW1 |");
825        assert_eq!(lines[sep + 2], "| NEW2 |");
826        assert_eq!(lines[sep + 3], "| **v0.185.0** | Old |");
827        assert!(out.ends_with('\n'));
828    }
829
830    #[test]
831    fn insert_skips_an_earlier_unrelated_table() {
832        // A legend table sits above the target; the anchor must route past it.
833        let md = "| Legend | Meaning |\n|---|---|\n| x | y |\n\n\
834                  | Version | Highlights |\n|---|---|\n| **v0.185.0** | Old |\n";
835        let out = insert_after_table_separator(md, "| Version |", &["| NEW |".into()]).unwrap();
836        let lines: Vec<&str> = out.lines().collect();
837        // Inserted below the *second* separator, not the legend's.
838        let target = lines
839            .iter()
840            .position(|l| *l == "| **v0.185.0** | Old |")
841            .unwrap();
842        assert_eq!(lines[target - 1], "| NEW |");
843        assert!(
844            !out.contains("| x | y |\n| NEW |"),
845            "must not touch the legend table"
846        );
847    }
848
849    #[test]
850    fn insert_without_the_anchored_table_errors() {
851        assert!(
852            insert_after_table_separator("no table here\n", "| Version |", &["| r |".into()])
853                .is_err()
854        );
855    }
856}