use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use cap_std::fs::Dir;
use oakum::plan::{
AggregatedBump, BumpLevel, ChangeSource, Ecosystem, Package, PackageId, Plan, PlannedChange,
Workspace,
};
use oakum::template;
use semver::Version;
use serde::Serialize;
use super::fs::repo_path_display;
use super::git::{Git, Op};
use super::markdown::{indent_columns, Fence};
use super::write_set::{read_text, PlannedWrite};
use super::CliError;
const CHANGELOG_NAME: &str = "CHANGELOG.md";
const TITLE: &str = "# Changelog";
const FOOTER_PREFIX: &str = "Generated by oakum ";
pub(super) struct ChangelogPlan<'a> {
date: &'a str,
tool_version: &'a str,
template: Option<&'a str>,
supplied_notes: Option<&'a str>,
links: Option<&'a Links>,
}
impl<'a> ChangelogPlan<'a> {
pub(super) fn new(
date: &'a str,
tool_version: &'a str,
template: Option<&'a str>,
supplied_notes: Option<&'a str>,
links: Option<&'a Links>,
) -> Self {
Self {
date,
tool_version,
template,
supplied_notes,
links,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Links {
pub(super) repo: Option<(String, String)>,
pub(super) by_file: BTreeMap<String, Provenance>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Provenance {
pub(super) commit: String,
pub(super) author: String,
pub(super) email: String,
pub(super) subject: String,
}
impl Provenance {
pub(super) fn of(git: &Git, path: &str) -> Result<Option<Self>, CliError> {
let Some(line) = git.optional_text(Op::FileAddedBy { path })? else {
return Ok(None);
};
let mut fields = line.splitn(4, '\0');
let (Some(commit), Some(author), Some(email), Some(subject)) =
(fields.next(), fields.next(), fields.next(), fields.next())
else {
return Err(CliError::unverified(format!(
"unverified: git log for `{path}` did not print four fields"
)));
};
Ok(Some(Self {
commit: commit.to_owned(),
author: author.to_owned(),
email: email.to_owned(),
subject: subject.to_owned(),
}))
}
pub(super) fn pull_request(&self) -> Option<u64> {
pull_request_number(&self.subject)
}
}
fn pull_request_number(subject: &str) -> Option<u64> {
let trimmed = subject.trim_end();
let inner = trimmed.strip_suffix(')')?;
let (_, tail) = inner.rsplit_once("(#")?;
tail.parse().ok()
}
pub(super) fn utc_date(now: SystemTime) -> Result<String, Box<dyn std::error::Error>> {
let secs = now
.duration_since(UNIX_EPOCH)
.map_err(|_| CliError::new("system clock is before the Unix epoch"))?
.as_secs();
Ok(ymd_from_unix_days(secs / 86_400))
}
pub(super) fn plan_changelog_writes(
dir: &Dir,
workspace: &Workspace,
plan: &Plan,
intent: &BTreeMap<PackageId, AggregatedBump>,
input: &ChangelogPlan<'_>,
) -> Result<Vec<PlannedWrite>, Box<dyn std::error::Error>> {
let mut sections_by_path: BTreeMap<PathBuf, Vec<String>> = BTreeMap::new();
for change in plan.changes().values() {
let package = workspace.get(change.id()).ok_or_else(|| {
CliError::new(format!(
"{} is in the plan but not in the workspace",
change.id().name
))
})?;
let section = emit_section(package, change, intent.get(change.id()), plan, input)?;
sections_by_path
.entry(changelog_path(package))
.or_default()
.push(section);
}
let mut writes = Vec::new();
for (path, sections) in sections_by_path {
match read_text(dir, &path)? {
None => {
let next = assemble_new(§ions, input.tool_version);
writes.push(PlannedWrite::create(path, next));
}
Some(original) => {
let next = splice(&path, &original, §ions, input.tool_version)?;
writes.push(PlannedWrite::new(path, original, next));
}
}
}
Ok(writes)
}
pub(super) fn changelog_repo_path(package: &Package) -> String {
repo_path_display(&changelog_path(package))
}
fn changelog_path(package: &Package) -> PathBuf {
let dir = package.manifest_dir();
if dir.is_empty() {
PathBuf::from(CHANGELOG_NAME)
} else {
Path::new(dir).join(CHANGELOG_NAME)
}
}
fn emit_section(
package: &Package,
change: &PlannedChange,
bump: Option<&AggregatedBump>,
plan: &Plan,
input: &ChangelogPlan<'_>,
) -> Result<String, Box<dyn std::error::Error>> {
let notes = match input.supplied_notes {
Some(body) => supplied_note(body).into_iter().collect(),
None => release_notes(bump),
};
if let Some(source) = input.template {
let bump = if input.supplied_notes.is_some() {
None
} else {
bump
};
return render_template(source, package, change, bump, ¬es, input);
}
if input.supplied_notes.is_some() {
return Ok(supplied_section(
change.to(),
input.date,
notes.first().copied(),
));
}
Ok(builtin_section(
change.to(),
input.date,
bump,
cascade_attribution(change, plan)?,
))
}
fn cascade_attribution<'a>(
change: &'a PlannedChange,
plan: &'a Plan,
) -> Result<Option<(&'a str, &'a Version)>, CliError> {
match change.source() {
ChangeSource::Intent => Ok(None),
ChangeSource::Cascade { trigger } => {
let Some(trigger_change) = plan.get(trigger) else {
return Err(CliError::new(format!(
"{} cascaded from {trigger} but that package is not in the plan",
change.id()
)));
};
Ok(Some((trigger.name.as_str(), trigger_change.to())))
}
}
}
fn supplied_section(version: &Version, date: &str, body: Option<&str>) -> String {
match body {
Some(body) => format!("## {version} ({date})\n\n{body}\n"),
None => format!("## {version} ({date})\n"),
}
}
const SECTIONS: [&str; 6] = [
"Added",
"Changed",
"Deprecated",
"Removed",
"Fixed",
"Security",
];
fn builtin_section(
version: &Version,
date: &str,
bump: Option<&AggregatedBump>,
cascade: Option<(&str, &Version)>,
) -> String {
let mut out = format!("## {version} ({date})\n");
let mut grouped = grouped_notes(bump);
let cascade_line = cascade.map(|(name, to)| format!("Updated {name} to {to}"));
if let Some(line) = cascade_line.as_deref() {
grouped[1].1.push(line);
}
for (heading, notes) in grouped {
if notes.is_empty() {
continue;
}
out.push('\n');
out.push_str("### ");
out.push_str(heading);
out.push_str("\n\n");
out.push_str(¬es.join("\n\n"));
out.push('\n');
}
out
}
fn grouped_notes(bump: Option<&AggregatedBump>) -> [(&'static str, Vec<&str>); 6] {
let mut grouped = SECTIONS.map(|heading| (heading, Vec::new()));
if let Some(bump) = bump {
for contribution in bump.contributions() {
if !contribution.level().is_release() {
continue;
}
for (section, body) in note_sections(contribution.note(), contribution.level()) {
if let Some(slot) = grouped.iter_mut().find(|(heading, _)| *heading == section) {
slot.1.push(body);
}
}
}
}
grouped
}
fn note_sections(note: &str, level: BumpLevel) -> Vec<(&'static str, &str)> {
let default = match level {
BumpLevel::Minor => "Added",
BumpLevel::Major => "Changed",
BumpLevel::Patch => "Fixed",
BumpLevel::None => return Vec::new(),
};
let Some(body) = note_body(note) else {
return Vec::new();
};
let mut sections = Vec::new();
let mut fence = Fence::default();
let mut section = default;
let mut start = 0;
let mut offset = 0;
for line in body.split_inclusive('\n') {
let fenced = fence.observe(line);
if !fenced {
if let Some(named) = section_heading(line) {
sections.extend(section_body(&body[start..offset]).map(|text| (section, text)));
section = named;
start = offset + line.len();
}
}
offset += line.len();
}
sections.extend(section_body(&body[start..]).map(|text| (section, text)));
sections
}
fn section_body(chunk: &str) -> Option<&str> {
note_body(chunk).filter(|text| !text.trim().is_empty())
}
fn section_heading(line: &str) -> Option<&'static str> {
let (columns, rest) = indent_columns(line);
if columns >= 4 {
return None;
}
let named = rest.trim_end().strip_prefix("### ")?;
SECTIONS
.iter()
.find(|section| section.eq_ignore_ascii_case(named.trim()))
.copied()
}
fn release_notes(bump: Option<&AggregatedBump>) -> Vec<&str> {
let Some(bump) = bump else {
return Vec::new();
};
bump.contributions()
.iter()
.flat_map(|contribution| note_sections(contribution.note(), contribution.level()))
.map(|(_, body)| body)
.collect()
}
fn note_body(note: &str) -> Option<&str> {
let note = note.trim_matches(['\n', '\r']);
if note.is_empty() {
None
} else {
Some(note)
}
}
pub(super) fn supplied_note(body: &str) -> Option<&str> {
let body = body.trim_end_matches(['\n', '\r']);
if body.is_empty() {
None
} else {
Some(body)
}
}
#[derive(Serialize)]
struct SectionContext<'a> {
version: String,
date: &'a str,
notes: Vec<&'a str>,
changes: Vec<ChangeContext<'a>>,
repo: Option<RepoContext>,
package: &'a str,
ecosystem: &'a str,
bump: String,
source: &'a str,
trigger: Option<&'a str>,
tool_version: &'a str,
target: &'static str,
}
#[derive(Serialize)]
struct RepoContext {
owner: String,
name: String,
url: String,
}
#[derive(Serialize)]
struct ChangeContext<'a> {
note: &'a str,
section: &'static str,
level: String,
file: &'a str,
commit: Option<CommitContext>,
pr: Option<PrContext>,
author: Option<AuthorContext<'a>>,
}
#[derive(Serialize)]
struct CommitContext {
sha: String,
short: String,
url: Option<String>,
}
#[derive(Serialize)]
struct PrContext {
number: u64,
url: Option<String>,
}
#[derive(Serialize)]
struct AuthorContext<'a> {
name: &'a str,
email: &'a str,
}
fn repo_context(links: Option<&Links>) -> Option<RepoContext> {
let (owner, name) = links?.repo.clone()?;
let url = format!("https://github.com/{owner}/{name}");
Some(RepoContext { owner, name, url })
}
fn change_contexts<'a>(
bump: Option<&'a AggregatedBump>,
links: Option<&'a Links>,
) -> Vec<ChangeContext<'a>> {
let Some(bump) = bump else {
return Vec::new();
};
let repo_url = repo_context(links).map(|repo| repo.url);
bump.contributions()
.iter()
.flat_map(|contribution| {
let provenance = links.and_then(|links| links.by_file.get(contribution.source()));
note_sections(contribution.note(), contribution.level())
.into_iter()
.map(|(section, note)| ChangeContext {
note,
section,
level: contribution.level().to_string(),
file: contribution.source(),
commit: provenance.map(|found| CommitContext {
sha: found.commit.clone(),
short: found.commit.chars().take(7).collect(),
url: repo_url
.as_ref()
.map(|url| format!("{url}/commit/{}", found.commit)),
}),
pr: provenance
.and_then(Provenance::pull_request)
.map(|number| PrContext {
number,
url: repo_url.as_ref().map(|url| format!("{url}/pull/{number}")),
}),
author: provenance.map(|found| AuthorContext {
name: &found.author,
email: &found.email,
}),
})
.collect::<Vec<_>>()
})
.collect()
}
fn render_template(
source: &str,
package: &Package,
change: &PlannedChange,
bump: Option<&AggregatedBump>,
notes: &[&str],
input: &ChangelogPlan<'_>,
) -> Result<String, Box<dyn std::error::Error>> {
let (source_kind, trigger) = match change.source() {
ChangeSource::Intent => ("intent", None),
ChangeSource::Cascade { trigger } => ("cascade", Some(trigger.name.as_str())),
};
let rendered = template::render(
"changelog",
source,
SectionContext {
version: change.to().to_string(),
date: input.date,
notes: notes.to_vec(),
changes: change_contexts(bump, input.links),
repo: repo_context(input.links),
package: package.id().name.as_str(),
ecosystem: ecosystem_label(package.id().ecosystem),
bump: change.applied().effective().to_string(),
source: source_kind,
trigger,
tool_version: input.tool_version,
target: "changelog",
},
)
.map_err(|err| CliError::new(err.to_string()))?;
let mut rendered = rendered.trim_start_matches('\u{FEFF}').to_owned();
if !rendered.ends_with('\n') {
rendered.push('\n');
}
Ok(rendered)
}
fn ecosystem_label(ecosystem: Ecosystem) -> &'static str {
match ecosystem {
Ecosystem::Cargo => "cargo",
Ecosystem::Npm => "npm",
}
}
fn assemble_new(sections: &[String], tool_version: &str) -> String {
let footer = format!("{FOOTER_PREFIX}{tool_version}.");
join_blocks(&[TITLE, §ions.join("\n"), &footer])
}
fn splice(
path: &Path,
existing: &str,
sections: &[String],
tool_version: &str,
) -> Result<String, Box<dyn std::error::Error>> {
if let Some(refusal) = splice_refusal(existing) {
return Err(Box::new(CliError::new(refusal.reason(path))));
}
let body = strip_oakum_footer(existing);
let new_sections = sections.join("\n");
let footer = format!("{FOOTER_PREFIX}{tool_version}.");
match version_heading_start(body) {
Some(at) => {
let prefix = &body[..at];
let rest = &body[at..];
Ok(join_blocks(&[prefix, &new_sections, rest, &footer]))
}
None => Ok(join_blocks(&[body, &new_sections, &footer])),
}
}
pub(super) fn version_section(text: &str, version: &Version) -> Option<String> {
let mut fence = Fence::default();
let mut lines = text.lines().map(|line| line.trim_end_matches('\r'));
lines.find(|line| {
!fence.observe(line)
&& line
.strip_prefix("## ")
.and_then(|rest| heading_version(rest, HeadingToken::Whole))
.is_some_and(|found| found == *version)
})?;
let mut fence = Fence::default();
let body: Vec<&str> = lines
.take_while(|line| {
fence.observe(line)
|| !(line.starts_with("## ") || line.starts_with("# ") || is_oakum_footer(line))
})
.collect();
Some(body.join("\n").trim_matches('\n').to_owned())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SpliceRefusal {
Bom,
Title,
}
impl SpliceRefusal {
pub(super) fn reason(self, path: &Path) -> String {
match self {
Self::Bom => format!(
"{} starts with a UTF-8 BOM; oakum will not splice a changelog it cannot recognize",
repo_path_display(path)
),
Self::Title => format!(
"{} does not start with `{TITLE}`; oakum will not append without a recognized heading",
repo_path_display(path)
),
}
}
pub(super) fn fix(self) -> &'static str {
match self {
Self::Bom => "remove the byte-order mark from the start of the file",
Self::Title => {
"change the first line to `# Changelog` (the old title can stay as a line under it)"
}
}
}
}
pub(super) fn splice_refusal(text: &str) -> Option<SpliceRefusal> {
if text.starts_with('\u{FEFF}') {
return Some(SpliceRefusal::Bom);
}
if !starts_with_title(text) {
return Some(SpliceRefusal::Title);
}
None
}
pub(super) fn foreign_changelogs(
dir: &Dir,
workspace: &Workspace,
managed: impl Fn(&Package) -> bool,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let mut seen = BTreeSet::new();
let mut reports = Vec::new();
for package in workspace.packages().filter(|package| managed(package)) {
let path = changelog_path(package);
if !seen.insert(path.clone()) {
continue;
}
if let Some(text) = read_text(dir, &path)? {
if let Some(refusal) = splice_refusal(&text) {
reports.push(format!("{}; {}", refusal.reason(&path), refusal.fix()));
}
}
}
Ok(reports)
}
fn starts_with_title(text: &str) -> bool {
let Some(rest) = text.strip_prefix(TITLE) else {
return false;
};
rest.is_empty() || rest.starts_with('\n') || rest.starts_with("\r\n")
}
fn strip_oakum_footer(text: &str) -> &str {
let trimmed = text.trim_end_matches(['\n', '\r']);
let Some((rest, last)) = trimmed.rsplit_once('\n') else {
return if is_oakum_footer(trimmed) {
""
} else {
trimmed
};
};
let last = last.trim_end_matches('\r');
if is_oakum_footer(last) {
rest.trim_end_matches(['\n', '\r'])
} else {
trimmed
}
}
fn is_oakum_footer(line: &str) -> bool {
line.strip_prefix(FOOTER_PREFIX)
.and_then(|rest| rest.strip_suffix('.'))
.is_some_and(|version| Version::parse(version).is_ok())
}
fn version_heading_start(text: &str) -> Option<usize> {
let mut pos = 0;
let mut fence = Fence::default();
for line in text.split_inclusive('\n') {
let content = line.trim_end_matches(['\n', '\r']);
if !fence.observe(content) && is_version_heading(content) {
return Some(pos);
}
pos += line.len();
}
None
}
fn is_version_heading(line: &str) -> bool {
let Some(rest) = line.strip_prefix("## ") else {
return false;
};
heading_version(rest, HeadingToken::BeforeDate).is_some()
}
#[derive(Clone, Copy)]
enum HeadingToken {
Whole,
BeforeDate,
}
fn heading_version(rest: &str, ends: HeadingToken) -> Option<Version> {
let rest = rest.trim_start_matches('[').trim_start_matches('v');
let cuts_dash = matches!(ends, HeadingToken::BeforeDate);
let token = rest
.split(|c: char| c == ']' || c == ' ' || c == '(' || (cuts_dash && c == '-'))
.next()
.unwrap_or("");
Version::parse(token).ok()
}
fn join_blocks(blocks: &[&str]) -> String {
let mut out = String::new();
for block in blocks {
let block = block.trim_end_matches(['\n', '\r']);
if block.is_empty() {
continue;
}
if !out.is_empty() {
out.push_str("\n\n");
}
out.push_str(block);
}
out.push('\n');
out
}
fn ymd_from_unix_days(days: u64) -> String {
let (year, month, day) = civil_from_days(days);
format!("{year:04}-{month:02}-{day:02}")
}
fn civil_from_days(days: u64) -> (i32, u8, u8) {
let z = i64::try_from(days).unwrap_or(i64::MAX) + 719_468;
let era = z / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let mut year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
if month <= 2 {
year += 1;
}
(
i32::try_from(year).unwrap_or(i32::MAX),
u8::try_from(month).unwrap_or(u8::MAX),
u8::try_from(day).unwrap_or(u8::MAX),
)
}
#[cfg(test)]
mod tests {
use super::super::git::{Git, Reply};
use super::super::CliError;
use super::{
builtin_section, change_contexts, civil_from_days, join_blocks, pull_request_number,
release_notes, repo_path_display, splice, splice_refusal, strip_oakum_footer,
supplied_note, supplied_section, version_section, ymd_from_unix_days, Links, Provenance,
SpliceRefusal,
};
use oakum::plan::{aggregate, BumpFile, BumpLevel, Ecosystem, PackageId};
use semver::Version;
use std::path::Path;
fn cargo(name: &str) -> PackageId {
PackageId::new(Ecosystem::Cargo, name)
}
fn bump(note: &str, level: BumpLevel) -> oakum::plan::AggregatedBump {
let intent = aggregate([BumpFile {
id: String::from("one.md"),
entries: vec![(cargo("demo"), level)],
note: String::from(note),
}]);
intent.into_values().next().expect("bump")
}
#[test]
fn civil_dates_match_known_unix_days() {
assert_eq!(civil_from_days(0), (1970, 1, 1));
assert_eq!(civil_from_days(10_957), (2000, 1, 1));
assert_eq!(civil_from_days(19_993), (2024, 9, 27));
assert_eq!(civil_from_days(20_690), (2026, 8, 25));
assert_eq!(ymd_from_unix_days(20_690), "2026-08-25");
}
#[test]
fn builtin_pins_heading_blank_section_blank_list() {
let bump = bump("\npatch demo\n", BumpLevel::Patch);
let section = builtin_section(&Version::new(0, 1, 1), "2026-08-25", Some(&bump), None);
assert_eq!(
section,
"## 0.1.1 (2026-08-25)\n\n### Fixed\n\npatch demo\n"
);
}
#[test]
fn builtin_groups_notes_by_contribution_level() {
let intent = aggregate([
BumpFile {
id: String::from("one.md"),
entries: vec![(cargo("demo"), BumpLevel::Patch)],
note: String::from("\npatch demo\n"),
},
BumpFile {
id: String::from("two.md"),
entries: vec![(cargo("demo"), BumpLevel::Minor)],
note: String::from("\nminor demo\n"),
},
]);
let bump = intent.values().next().expect("bump");
let section = builtin_section(&Version::new(0, 2, 0), "2026-08-25", Some(bump), None);
assert_eq!(
section,
"## 0.2.0 (2026-08-25)\n\n### Added\n\nminor demo\n\n### Fixed\n\npatch demo\n"
);
}
#[test]
fn builtin_omits_empty_and_none_notes() {
let intent = aggregate([BumpFile {
id: String::from("one.md"),
entries: vec![(cargo("demo"), BumpLevel::None)],
note: String::from("\nno release\n"),
}]);
let bump = intent.values().next().expect("bump");
let section = builtin_section(&Version::new(0, 1, 1), "2026-08-25", Some(bump), None);
assert_eq!(section, "## 0.1.1 (2026-08-25)\n");
}
#[test]
fn supplied_notes_replace_grouped_bump_notes() {
assert_eq!(
supplied_section(&Version::new(0, 1, 1), "2026-08-25", Some("workflow notes")),
"## 0.1.1 (2026-08-25)\n\nworkflow notes\n"
);
assert_eq!(
supplied_section(
&Version::new(0, 1, 1),
"2026-08-25",
supplied_note("\n\nworkflow notes\n"),
),
"## 0.1.1 (2026-08-25)\n\n\n\nworkflow notes\n"
);
assert_eq!(
supplied_section(&Version::new(0, 1, 1), "2026-08-25", None),
"## 0.1.1 (2026-08-25)\n"
);
}
#[test]
fn splice_new_file_is_genre_intersection() {
let bump = bump("\npatch demo\n", BumpLevel::Patch);
let section = builtin_section(&Version::new(0, 1, 1), "2026-08-25", Some(&bump), None);
let next = super::assemble_new(&[section], "0.0.0");
assert_eq!(
next,
"# Changelog\n\n## 0.1.1 (2026-08-25)\n\n### Fixed\n\npatch demo\n\nGenerated by oakum 0.0.0.\n"
);
assert!(!next.contains("<sub>"));
assert!(!next.contains("\n\n\n"));
assert!(next.ends_with('\n'));
assert!(!next.ends_with("\n\n"));
}
#[test]
fn splice_prepends_before_the_first_version_heading() {
let existing = "# Changelog\n\n## [Unreleased]\n\n## 0.1.0 (2026-01-01)\n\n### Added\n\nold\n\nGenerated by oakum 0.0.0.\n";
let section = "## 0.1.1 (2026-08-25)\n\n### Fixed\n\npatch demo\n";
let next = splice(
Path::new("CHANGELOG.md"),
existing,
&[section.to_owned()],
"0.0.0",
)
.expect("splice");
assert_eq!(
next,
"# Changelog\n\n## [Unreleased]\n\n## 0.1.1 (2026-08-25)\n\n### Fixed\n\npatch demo\n\n## 0.1.0 (2026-01-01)\n\n### Added\n\nold\n\nGenerated by oakum 0.0.0.\n"
);
let dated_unreleased = splice(
Path::new("CHANGELOG.md"),
"# Changelog\n\n## [Unreleased] - 2026-01-01\n\n## 0.1.0 (2026-01-01)\n",
&[String::from("## 0.1.1 (2026-08-25)\n")],
"0.0.0",
)
.expect("dated unreleased");
assert!(
dated_unreleased.starts_with(
"# Changelog\n\n## [Unreleased] - 2026-01-01\n\n## 0.1.1 (2026-08-25)\n"
),
"{dated_unreleased}"
);
}
#[test]
fn splice_refuses_a_file_without_the_title() {
let err = splice(
Path::new("crates/core/CHANGELOG.md"),
"notes\n",
&[String::from("## 0.1.1 (2026-08-25)\n")],
"0.0.0",
)
.expect_err("refuse");
assert!(
err.to_string().contains(&format!(
"{} does not start with `# Changelog`",
repo_path_display(Path::new("crates/core/CHANGELOG.md"))
)),
"{err}"
);
let blank = splice(
Path::new("CHANGELOG.md"),
"\n# Changelog\n",
&[String::from("## 0.1.1 (2026-08-25)\n")],
"0.0.0",
)
.expect_err("blank prefix");
assert!(
blank
.to_string()
.contains("does not start with `# Changelog`"),
"{blank}"
);
let empty = splice(
Path::new("CHANGELOG.md"),
"",
&[String::from("## 0.1.1 (2026-08-25)\n")],
"0.0.0",
)
.expect_err("empty existing");
assert!(
empty
.to_string()
.contains("does not start with `# Changelog`"),
"{empty}"
);
}
#[test]
fn builtin_keeps_indented_note_bytes() {
let bump = bump("\n fn foo() {}\n", BumpLevel::Patch);
let section = builtin_section(&Version::new(0, 1, 1), "2026-08-25", Some(&bump), None);
assert_eq!(
section,
"## 0.1.1 (2026-08-25)\n\n### Fixed\n\n fn foo() {}\n"
);
}
#[test]
fn builtin_writes_a_changed_line_for_a_cascade() {
let section = builtin_section(
&Version::new(0, 1, 1),
"2026-08-25",
None,
Some(("core", &Version::new(0, 2, 0))),
);
assert_eq!(
section,
"## 0.1.1 (2026-08-25)\n\n### Changed\n\nUpdated core to 0.2.0\n"
);
}
#[test]
fn splice_refuses_a_bom() {
let err = splice(
Path::new("CHANGELOG.md"),
"\u{FEFF}# Changelog\n",
&[String::from("## 0.1.1 (2026-08-25)\n")],
"0.0.0",
)
.expect_err("bom");
assert!(err.to_string().contains("BOM"), "{err}");
}
#[test]
fn strip_footer_leaves_foreign_last_lines() {
assert_eq!(
strip_oakum_footer("body\nGenerated by oakum 1.2.3.\n"),
"body"
);
assert_eq!(
strip_oakum_footer("body\nGenerated by oakum contributors.\n"),
"body\nGenerated by oakum contributors."
);
assert_eq!(
strip_oakum_footer("body\nnot a footer\n"),
"body\nnot a footer"
);
}
#[test]
fn join_blocks_skips_empty_and_ends_with_one_newline() {
assert_eq!(
join_blocks(&["# Changelog", "", "tail"]),
"# Changelog\n\ntail\n"
);
}
#[test]
fn version_section_returns_the_body_under_the_matching_heading() {
let text = "# Changelog\n\n## 0.8.6 (2026-09-09)\n\n### Added\n\n- later\n\n## 0.8.5 (2026-09-08)\n\n### Fixed\n\n- archive notice\n\n## 0.8.4\n\n- older\n\nGenerated by oakum 0.1.4.\n";
assert_eq!(
version_section(text, &Version::new(0, 8, 5)).as_deref(),
Some("### Fixed\n\n- archive notice")
);
assert_eq!(
version_section(text, &Version::new(0, 8, 4)).as_deref(),
Some("- older")
);
assert_eq!(version_section(text, &Version::new(0, 9, 0)), None);
}
#[test]
fn version_section_matches_prereleases_exactly_and_stops_at_any_heading() {
let text = "# Changelog\n\n## 0.1.1-rc.1 (2026-09-08)\n\n- rc only\n\n## 0.1.1 (2026-09-09)\n\n- final\n\n## Migration notes\n\n- prose\n";
let rc = Version::parse("0.1.1-rc.1").expect("rc");
assert_eq!(version_section(text, &rc).as_deref(), Some("- rc only"));
assert_eq!(
version_section(text, &Version::new(0, 1, 1)).as_deref(),
Some("- final")
);
let crlf = "# Changelog\r\n\r\n## 1.2.3\r\n\r\nbody\r\n\r\n## 1.2.2\r\n";
assert_eq!(
version_section(crlf, &Version::new(1, 2, 3)).as_deref(),
Some("body")
);
assert_eq!(
version_section(crlf, &Version::new(1, 2, 2)).as_deref(),
Some("")
);
}
#[test]
fn version_section_ignores_headings_inside_fenced_code() {
let text = "# Changelog\n\n## 0.2.0\n\nExample:\n\n```md\n## 0.1.1\n\n- FAKE\n```\n\n## 0.1.1 (2026-09-08)\n\nInstall it:\n\n```sh\n# grab the binary\ncargo install oakum\n```\n\nThen run it.\n\n## 0.1.0\n";
assert_eq!(
version_section(text, &Version::new(0, 1, 1)).as_deref(),
Some(
"Install it:\n\n```sh\n# grab the binary\ncargo install oakum\n```\n\nThen run it."
)
);
assert_eq!(
version_section(text, &Version::new(0, 2, 0)).as_deref(),
Some("Example:\n\n```md\n## 0.1.1\n\n- FAKE\n```")
);
}
#[test]
fn version_section_closes_fences_only_with_the_opening_marker() {
let text = "# Changelog\n\n## 0.1.1\n\n```text\n~~~\n```\n\nTail line.\n\n## 0.1.0\n\n- older\n\nGenerated by oakum 0.1.4.\n";
assert_eq!(
version_section(text, &Version::new(0, 1, 1)).as_deref(),
Some("```text\n~~~\n```\n\nTail line.")
);
let odd =
"# Changelog\n\n## 0.1.1\n\n````md\n```sh\n````\n\nTail line.\n\n## 0.1.0\n\n- older\n";
assert_eq!(
version_section(odd, &Version::new(0, 1, 1)).as_deref(),
Some("````md\n```sh\n````\n\nTail line.")
);
let indented = "# Changelog\n\n## 0.1.1\n\n ```\n not a fence\n\n## 0.1.0\n";
assert_eq!(
version_section(indented, &Version::new(0, 1, 1)).as_deref(),
Some(" ```\n not a fence")
);
let tab_indented = "# Changelog\n\n## 0.1.1\n\n\t```\n\tnot a fence\n\n## 0.1.0\n";
assert_eq!(
version_section(tab_indented, &Version::new(0, 1, 1)).as_deref(),
Some("\t```\n\tnot a fence")
);
let info_string_closer =
"# Changelog\n\n## 0.1.1\n\n```text\n```sh\n```\n\n## 0.1.0\n\n- older\n";
assert_eq!(
version_section(info_string_closer, &Version::new(0, 1, 1)).as_deref(),
Some("```text\n```sh\n```")
);
let backtick_in_info = "# Changelog\n\n## 0.1.1\n\n```lang`x\n\n## 0.1.0\n\n- older\n";
assert_eq!(
version_section(backtick_in_info, &Version::new(0, 1, 1)).as_deref(),
Some("```lang`x")
);
assert_eq!(
version_section(backtick_in_info, &Version::new(0, 1, 0)).as_deref(),
Some("- older")
);
}
#[test]
fn splice_skips_a_heading_inside_a_fence() {
let existing = "# Changelog\n\nExample entry:\n\n```md\n## 9.9.9\n\n- fake\n```\n\n## 0.1.0 (2026-01-01)\n\n- first\n";
let at = super::version_heading_start(existing).expect("real heading");
assert!(
existing[at..].starts_with("## 0.1.0"),
"{}",
&existing[at..]
);
}
#[test]
fn version_section_tolerates_bracketed_and_prefixed_headings() {
let text = "# Changelog\n\n## [1.2.3] - 2026-01-01\n\nbody\n\n## v1.2.2\n";
assert_eq!(
version_section(text, &Version::new(1, 2, 3)).as_deref(),
Some("body")
);
assert_eq!(
version_section(text, &Version::new(1, 2, 2)).as_deref(),
Some("")
);
}
#[test]
fn a_note_opening_with_a_keep_a_changelog_heading_picks_its_section() {
let file = BumpFile {
id: String::from("archive.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("### Changed\n\nArchived; no further releases.\n"),
};
let intent = aggregate(vec![file]);
let bump = intent.get(&PackageId::new(Ecosystem::Cargo, "demo"));
let section = builtin_section(&Version::parse("0.8.5").unwrap(), "2026-09-08", bump, None);
assert_eq!(
section,
"## 0.8.5 (2026-09-08)\n\n### Changed\n\nArchived; no further releases.\n"
);
}
#[test]
fn sections_render_in_keep_a_changelog_order_and_unknown_headings_stay_in_the_body() {
let files = vec![
BumpFile {
id: String::from("a.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("### security\n\nrotate keys\n"),
},
BumpFile {
id: String::from("b.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("### Notes\n\nnot a section\n"),
},
BumpFile {
id: String::from("c.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Minor)],
note: String::from("### Removed\n\nthe old flag\n"),
},
BumpFile {
id: String::from("d.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("### Fixed\n"),
},
];
let intent = aggregate(files);
let bump = intent.get(&PackageId::new(Ecosystem::Cargo, "demo"));
let section = builtin_section(&Version::parse("0.2.0").unwrap(), "2026-09-09", bump, None);
assert_eq!(
section,
"## 0.2.0 (2026-09-09)\n\n### Removed\n\nthe old flag\n\n### Fixed\n\n### Notes\n\nnot a section\n\n### Security\n\nrotate keys\n"
);
}
#[test]
fn a_bump_file_declaring_two_sections_renders_each_under_its_own_heading() {
let bump = bump(
"### Changed\n\nthe workflow note\n\n### Added\n\nthe migration guide\n",
BumpLevel::Minor,
);
let section = builtin_section(&Version::new(0, 3, 0), "2026-09-12", Some(&bump), None);
assert_eq!(
section,
"## 0.3.0 (2026-09-12)\n\n### Added\n\nthe migration guide\n\n### Changed\n\nthe workflow note\n"
);
}
#[test]
fn no_section_heading_repeats_within_one_rendered_release() {
let files = vec![
BumpFile {
id: String::from("a.md"),
entries: vec![(cargo("demo"), BumpLevel::Minor)],
note: String::from("### Added\n\nA\n\n### Changed\n\nB\n"),
},
BumpFile {
id: String::from("b.md"),
entries: vec![(cargo("demo"), BumpLevel::Major)],
note: String::from("### Changed\n\nC\n\n### Fixed\n\nD\n"),
},
BumpFile {
id: String::from("c.md"),
entries: vec![(cargo("demo"), BumpLevel::Patch)],
note: String::from("### Fixed\n\nE\n"),
},
];
let intent = aggregate(files);
let bump = intent.get(&cargo("demo"));
let section = builtin_section(&Version::new(0, 4, 0), "2026-09-14", bump, None);
let headings: Vec<&str> = section
.lines()
.filter(|line| line.starts_with("### "))
.collect();
assert_eq!(
headings,
["### Added", "### Changed", "### Fixed"],
"{section}"
);
assert_eq!(
section,
"## 0.4.0 (2026-09-14)\n\n### Added\n\nA\n\n### Changed\n\nB\n\nC\n\n### Fixed\n\nD\n\nE\n"
);
}
#[test]
fn a_known_heading_inside_a_fence_is_content_not_a_section() {
let bump = bump(
"### Fixed\n\nthe renderer\n\n```md\n### Changed\n```\n",
BumpLevel::Patch,
);
let section = builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&bump), None);
assert_eq!(
section,
"## 0.3.1 (2026-09-14)\n\n### Fixed\n\nthe renderer\n\n```md\n### Changed\n```\n"
);
}
#[test]
fn a_two_section_note_is_two_changes_sharing_one_provenance() {
let bump = bump(
"### Added\n\nthe guide\n\n### Changed\n\nthe workflow note\n",
BumpLevel::Minor,
);
let mut by_file = std::collections::BTreeMap::new();
by_file.insert(
String::from("one.md"),
Provenance {
commit: String::from("abc1234def"),
author: String::from("Jace Babin"),
email: String::from("jbabin91@gmail.com"),
subject: String::from("docs(guide): write the migration guide (#204)"),
},
);
let links = Links {
repo: Some((String::from("oakoss"), String::from("oakum"))),
by_file,
};
let changes = change_contexts(Some(&bump), Some(&links));
assert_eq!(changes.len(), 2, "one row per section");
assert_eq!(changes[0].section, "Added");
assert_eq!(changes[0].note, "the guide");
assert_eq!(changes[1].section, "Changed");
assert_eq!(changes[1].note, "the workflow note");
for change in &changes {
assert_eq!(change.file, "one.md");
assert_eq!(change.pr.as_ref().map(|pr| pr.number), Some(204));
assert_eq!(
change.commit.as_ref().map(|commit| commit.short.as_str()),
Some("abc1234")
);
}
}
#[test]
fn prose_above_the_first_heading_lands_under_the_level_default() {
let bump = bump(
"a loose sentence\n\n### Added\n\nthe guide\n",
BumpLevel::Patch,
);
let section = builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&bump), None);
assert_eq!(
section,
"## 0.3.1 (2026-09-14)\n\n### Added\n\nthe guide\n\n### Fixed\n\na loose sentence\n"
);
}
#[test]
fn a_heading_with_nothing_under_it_renders_no_section() {
let bump = bump(
"### Added\n\nthe guide\n\n### Fixed\n \n",
BumpLevel::Minor,
);
let section = builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&bump), None);
assert_eq!(section, "## 0.3.1 (2026-09-14)\n\n### Added\n\nthe guide\n");
}
#[test]
fn a_heading_is_a_heading_up_to_three_columns_and_code_at_four() {
let indented = bump(
"### Added\n\nthe guide\n\n ### Fixed\n\nthe renderer\n",
BumpLevel::Minor,
);
assert_eq!(
builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&indented), None),
"## 0.3.1 (2026-09-14)\n\n### Added\n\nthe guide\n\n### Fixed\n\nthe renderer\n"
);
let code = bump(
"### Added\n\nthe guide\n\n ### Fixed\n",
BumpLevel::Minor,
);
assert_eq!(
builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&code), None),
"## 0.3.1 (2026-09-14)\n\n### Added\n\nthe guide\n\n ### Fixed\n"
);
let padded = bump("### Added \n\nthe guide\n", BumpLevel::Patch);
assert_eq!(
builtin_section(&Version::new(0, 3, 1), "2026-09-14", Some(&padded), None),
"## 0.3.1 (2026-09-14)\n\n### Added\n\nthe guide\n"
);
}
#[test]
fn a_template_reads_every_section_of_a_two_section_note() {
let bump = bump(
"### Added\n\nthe guide\n\n### Changed\n\nthe workflow note\n",
BumpLevel::Minor,
);
assert_eq!(
release_notes(Some(&bump)),
vec!["the guide", "the workflow note"]
);
}
#[test]
fn a_sectioned_coverage_only_note_stays_out_of_every_render() {
let files = vec![
BumpFile {
id: String::from("cover.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::None)],
note: String::from("### Changed\n\ncoverage only\n"),
},
BumpFile {
id: String::from("real.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("a fix\n"),
},
];
let intent = aggregate(files);
let bump = intent.get(&PackageId::new(Ecosystem::Cargo, "demo"));
assert_eq!(release_notes(bump), vec!["a fix"]);
let section = builtin_section(&Version::parse("0.1.1").unwrap(), "2026-09-09", bump, None);
assert!(!section.contains("coverage only"), "{section}");
}
#[test]
fn template_notes_lose_the_opening_heading_line() {
let file = BumpFile {
id: String::from("archive.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("### Changed\n\nArchived; no further releases.\n"),
};
let intent = aggregate(vec![file]);
let bump = intent.get(&PackageId::new(Ecosystem::Cargo, "demo"));
assert_eq!(release_notes(bump), vec!["Archived; no further releases."]);
}
#[test]
fn a_git_log_line_short_of_four_fields_is_unverified() {
let git = Git::answering([("log --diff-filter=A", Reply::said("sha\0Ada\0"))]);
let err = Provenance::of(&git, ".changeset/one.md").expect_err("three fields");
assert!(matches!(err, CliError::Unverified { .. }), "{err:?}");
assert!(
err.to_string().contains("did not print four fields"),
"{err}"
);
let git = Git::answering([(
"log --diff-filter=A",
Reply::said("sha\0Ada\0ada@example.com\0feat: x (#3)"),
)]);
let found = Provenance::of(&git, ".changeset/one.md")
.expect("four fields")
.expect("committed");
assert_eq!(found.pull_request(), Some(3));
}
#[test]
fn a_pull_request_number_is_the_squash_suffix() {
assert_eq!(pull_request_number("feat: thing (#42)"), Some(42));
assert_eq!(pull_request_number("feat: thing (#42) "), Some(42));
assert_eq!(pull_request_number("fix: (#1) then more"), None);
assert_eq!(pull_request_number("Merge pull request #7 from x"), None);
assert_eq!(pull_request_number("feat: thing"), None);
assert_eq!(pull_request_number("feat: thing (#)"), None);
}
#[test]
fn splice_refusal_names_the_title_or_the_bom() {
let path = Path::new("CHANGELOG.md");
assert_eq!(splice_refusal("# Changelog\n\n## 0.1.0\n"), None);
assert_eq!(splice_refusal("# Changelog"), None);
assert_eq!(
splice_refusal("# @scope/pkg\n\n## 0.1.0\n"),
Some(SpliceRefusal::Title)
);
assert_eq!(splice_refusal("# Changelogs\n"), Some(SpliceRefusal::Title));
assert_eq!(
splice_refusal("\u{FEFF}# Changelog\n"),
Some(SpliceRefusal::Bom)
);
assert_eq!(
SpliceRefusal::Title.reason(path),
"CHANGELOG.md does not start with `# Changelog`; oakum will not append without a recognized heading"
);
assert_eq!(
SpliceRefusal::Bom.reason(path),
"CHANGELOG.md starts with a UTF-8 BOM; oakum will not splice a changelog it cannot recognize"
);
assert_eq!(
SpliceRefusal::Bom.fix(),
"remove the byte-order mark from the start of the file"
);
}
#[test]
fn the_schema_names_every_variable_the_changelog_template_renders_with() {
crate::cli::schema_names_every_variable(
"template",
super::SectionContext {
version: String::from("1.2.3"),
date: "2026-09-11",
notes: Vec::new(),
changes: Vec::new(),
repo: None,
package: "demo",
ecosystem: "cargo",
bump: String::from("patch"),
source: "intent",
trigger: None,
tool_version: "0.3.0",
target: "changelog",
},
);
}
}