use std::io::{self, Write};
use std::path::PathBuf;
use crate::entity::{Artifact, Fileset, Kind, ScaffoldCtx};
use crate::governance::{self, GovKind};
use crate::listing::{Format, ListArgs};
use crate::tomlfmt::toml_string;
const ADR_DIR: &str = ".doctrine/adr";
pub(crate) const ADR_KIND: GovKind = GovKind {
kind: Kind {
dir: ADR_DIR,
prefix: "ADR",
scaffold: adr_scaffold,
},
stem: "adr",
statuses: ADR_STATUSES,
hidden: is_hidden,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum AdrStatus {
Proposed,
Accepted,
Rejected,
Superseded,
Deprecated,
}
impl AdrStatus {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Proposed => "proposed",
Self::Accepted => "accepted",
Self::Rejected => "rejected",
Self::Superseded => "superseded",
Self::Deprecated => "deprecated",
}
}
}
pub(crate) const ADR_STATUSES: &[&str] = &[
"proposed",
"accepted",
"rejected",
"superseded",
"deprecated",
];
fn is_hidden(status: &str) -> bool {
matches!(status, "rejected" | "superseded" | "deprecated")
}
pub(crate) struct SupersedePolicy {
pub(crate) supersedes_field: &'static str,
pub(crate) carveout_field: &'static str,
pub(crate) superseded_status: &'static str,
}
pub(crate) fn supersede_policy(kind: &Kind) -> Option<SupersedePolicy> {
match kind.prefix {
"ADR" => Some(SupersedePolicy {
supersedes_field: "supersedes",
carveout_field: "superseded_by",
superseded_status: "superseded",
}),
_ => None,
}
}
fn render_adr_toml(id: u32, slug: &str, title: &str, date: &str) -> anyhow::Result<String> {
Ok(crate::install::asset_text("templates/adr.toml")?
.replace("{{id}}", &id.to_string())
.replace("{{slug}}", &toml_string(slug))
.replace("{{title}}", &toml_string(title))
.replace("{{date}}", date))
}
fn render_adr_md(canonical_id: &str, title: &str) -> anyhow::Result<String> {
Ok(crate::install::asset_text("templates/adr.md")?
.replace("{{ref}}", canonical_id)
.replace("{{title}}", title))
}
fn adr_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
let id = ctx.id;
let name = format!("{id:03}");
Ok(vec![
Artifact::File {
rel_path: PathBuf::from(format!("{name}/adr-{name}.toml")),
body: render_adr_toml(id, ctx.slug, ctx.title, ctx.date)?,
},
Artifact::File {
rel_path: PathBuf::from(format!("{name}/adr-{name}.md")),
body: render_adr_md(ctx.canonical, ctx.title)?,
},
Artifact::Symlink {
rel_path: PathBuf::from(format!("{name}-{}", ctx.slug)),
target: name,
},
])
}
pub(crate) fn run_new(
path: Option<PathBuf>,
title: Option<String>,
slug: Option<String>,
) -> anyhow::Result<()> {
governance::run_new(&ADR_KIND, path, title, slug)
}
pub(crate) fn run_list(path: Option<PathBuf>, args: ListArgs) -> anyhow::Result<()> {
governance::run_list(&ADR_KIND, path, args)
}
pub(crate) fn run_show(
path: Option<PathBuf>,
reference: &str,
format: Format,
) -> anyhow::Result<()> {
governance::run_show(&ADR_KIND, path, reference, format)
}
pub(crate) fn run_status(path: Option<PathBuf>, id: u32, status: AdrStatus) -> anyhow::Result<()> {
let root = crate::root::find(path, &crate::root::default_markers())?;
let gov_root = root.join(ADR_KIND.kind.dir);
governance::set_status(
&ADR_KIND,
&gov_root,
id,
status.as_str(),
&crate::clock::today(),
)?;
writeln!(io::stdout(), "ADR {id:03}: {}", status.as_str())?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::meta::Meta;
use std::path::Path;
#[test]
fn render_adr_toml_round_trips_to_metadata() {
let body = render_adr_toml(7, "use-rust", "Use Rust", "2026-06-04").unwrap();
let parsed: Meta = toml::from_str(&body).unwrap();
assert_eq!(
parsed,
Meta {
id: 7,
slug: "use-rust".to_string(),
title: "Use Rust".to_string(),
status: "proposed".to_string(),
}
);
assert!(body.contains("created = \"2026-06-04\""));
assert!(!body.contains("{{"));
}
#[test]
fn render_adr_toml_escapes_hostile_title_and_slug() {
let title = crate::tomlfmt::HOSTILE_TITLE;
let slug = crate::tomlfmt::HOSTILE_SLUG;
let body = render_adr_toml(7, slug, title, "2026-06-04").unwrap();
let parsed: Meta = toml::from_str(&body).unwrap();
assert_eq!(parsed.slug, slug);
assert_eq!(parsed.title, title);
}
#[test]
fn render_adr_toml_relationships_are_preserved_and_ignored_by_meta() {
let body = render_adr_toml(1, "s", "T", "2026-06-04").unwrap();
let doc: toml::Value = toml::from_str(&body).unwrap();
assert!(
doc["relationships"]["supersedes"]
.as_array()
.unwrap()
.is_empty()
);
assert!(
doc["relationships"]["superseded_by"]
.as_array()
.unwrap()
.is_empty()
);
assert!(doc["relationships"]["tags"].as_array().unwrap().is_empty());
assert!(toml::from_str::<Meta>(&body).is_ok());
}
#[test]
fn render_adr_md_substitutes_ref_and_title_without_frontmatter() {
let body = render_adr_md("ADR-007", "Use Rust").unwrap();
assert!(body.starts_with("# ADR-007: Use Rust"));
assert!(!body.contains("{{ref}}"));
assert!(!body.contains("{{title}}"));
assert!(!body.starts_with("---"));
assert!(!body.contains("\n---\n"));
}
#[test]
fn adr_scaffold_lays_out_two_files_and_a_symlink() {
let ctx = ScaffoldCtx {
id: 7,
canonical: "ADR-007",
slug: "use-rust",
title: "Use Rust",
date: "2026-06-04",
};
let fileset = adr_scaffold(&ctx).unwrap();
assert_eq!(fileset.len(), 3);
assert!(matches!(&fileset[0],
Artifact::File { rel_path, body }
if rel_path == Path::new("007/adr-007.toml") && body.contains("2026-06-04")));
assert!(matches!(&fileset[1],
Artifact::File { rel_path, body }
if rel_path == Path::new("007/adr-007.md") && body.contains("ADR-007: Use Rust")));
assert!(matches!(&fileset[2],
Artifact::Symlink { rel_path, target }
if rel_path == Path::new("007-use-rust") && target == "007"));
}
#[test]
fn adr_known_set_matches_variants() {
let variants = [
AdrStatus::Proposed,
AdrStatus::Accepted,
AdrStatus::Rejected,
AdrStatus::Superseded,
AdrStatus::Deprecated,
];
let from_variants: Vec<&str> = variants.iter().map(|v| v.as_str()).collect();
assert_eq!(from_variants, ADR_STATUSES.to_vec());
}
#[test]
fn run_new_bails_for_a_slug_on_a_symbol_only_title() {
let dir = tempfile::tempdir().unwrap();
let err = run_new(Some(dir.path().to_path_buf()), Some("!!!".into()), None).unwrap_err();
assert!(err.to_string().contains("pass --slug"));
}
}