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::config::LoadedConfig;
use super::fs::{read_resolved_text, repo_path_display};
use super::git::{Git, Op};
use super::markdown::{indent_columns, Hidden};
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, Copy, Debug)]
pub(super) struct Owner<'a> {
name: &'a str,
shared: bool,
}
impl<'a> Owner<'a> {
pub(super) const fn new(name: &'a str, shared: bool) -> Self {
Self { name, shared }
}
pub(super) fn of(workspace: &Workspace, config: &LoadedConfig, package: &'a Package) -> Self {
Self::new(
&package.id().name,
shares_changelog(workspace, config, package),
)
}
pub(super) const fn shared(self) -> bool {
self.shared
}
pub(super) fn heading(self, version: &Version) -> String {
if self.shared {
format!("{}@{version}", self.name)
} else {
version.to_string()
}
}
}
pub(super) fn shares_changelog(
workspace: &Workspace,
config: &LoadedConfig,
package: &Package,
) -> bool {
let path = changelog_path(package);
workspace.packages().any(|other| {
other.id() != package.id()
&& (config.version_managed(other) || config.tag_managed(other))
&& changelog_path(other) == path
})
}
pub(super) fn unnamed_heading(
path: &str,
text: &str,
owner: Owner,
version: &Version,
) -> Option<CliError> {
let bare = Owner::new(owner.name, false);
(owner.shared
&& section_for_version(text, owner, version).is_none()
&& section_for_version(text, bare, version).is_some())
.then(|| {
CliError::new(format!(
"{path} is shared by more than one package, so `## {version}` names none of them; put the package it was written for into the heading, as in `## {}@{version}`",
owner.name
))
})
}
#[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,
config: &LoadedConfig,
plan: &Plan,
intent: &BTreeMap<PackageId, AggregatedBump>,
input: &ChangelogPlan<'_>,
) -> Result<(Vec<PlannedWrite>, Vec<ReleaseNote>), Box<dyn std::error::Error>> {
let mut sections_by_path: BTreeMap<PathBuf, Vec<(String, &Package, Owner, &Version)>> =
BTreeMap::new();
for change in plan.changes().values() {
let (section, package, owner) = plan_entry(workspace, config, plan, intent, change, input)?;
sections_by_path
.entry(changelog_path(package))
.or_default()
.push((section, package, owner, change.to()));
}
let mut writes = Vec::new();
let mut notes = Vec::new();
for (path, entries) in sections_by_path {
let sections: Vec<String> = entries
.iter()
.map(|(section, ..)| section.clone())
.collect();
let names: Vec<&str> = workspace
.packages()
.filter(|package| changelog_path(package) == path)
.map(|package| package.id().name.as_str())
.collect();
let original = read_text(dir, &path)?;
let next = match &original {
None => assemble_new(§ions, input.tool_version),
Some(original) => splice(&path, original, §ions, &names, input.tool_version)?,
};
notes.extend(read_back_sections(&path, &next, &entries)?);
writes.push(match original {
None => PlannedWrite::create(path, next),
Some(original) => PlannedWrite::new(path, original, next),
});
}
sort_like_the_plan_table(&mut notes);
Ok((writes, notes))
}
fn plan_entry<'w>(
workspace: &'w Workspace,
config: &LoadedConfig,
plan: &Plan,
intent: &BTreeMap<PackageId, AggregatedBump>,
change: &PlannedChange,
input: &ChangelogPlan<'_>,
) -> Result<(String, &'w Package, Owner<'w>), Box<dyn std::error::Error>> {
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 owner = Owner::of(workspace, config, package);
let bump = intent.get(change.id());
let section = emit_section(package, owner, change, bump, plan, input)?;
if let Some(open) = Hidden::left_open(§ion) {
return Err(Box::new(CliError::new(format!(
"the changelog entry for {} {} leaves {open} open, which would hide every heading after it; close it in {}",
change.id(),
change.to(),
left_open_by(bump, input)
))));
}
Ok((section, package, owner))
}
pub(super) enum EntryRefusal {
Refused(String),
Unsettled(String),
}
pub(super) fn entry_refusals(
workspace: &Workspace,
config: &LoadedConfig,
plan: &Plan,
intent: &BTreeMap<PackageId, AggregatedBump>,
input: &ChangelogPlan<'_>,
settled: Option<&ChangelogPlan<'_>>,
) -> Vec<EntryRefusal> {
plan.changes()
.values()
.filter_map(|change| {
let err = plan_entry(workspace, config, plan, intent, change, input).err()?;
let Some(settled) = settled else {
return Some(EntryRefusal::Refused(err.to_string()));
};
Some(
match plan_entry(workspace, config, plan, intent, change, settled) {
Ok(_) => {
EntryRefusal::Unsettled(format!("{} {}: {err}", change.id(), change.to()))
}
Err(merged) => EntryRefusal::Refused(merged.to_string()),
},
)
})
.collect()
}
fn left_open_by(bump: Option<&AggregatedBump>, input: &ChangelogPlan<'_>) -> String {
if let Some(body) = input.supplied_notes {
return if Hidden::left_open(body).is_some() {
String::from("the `--notes-file` body")
} else {
String::from("the template")
};
}
let files: Vec<String> = bump
.map(AggregatedBump::contributions)
.unwrap_or_default()
.iter()
.filter(|contribution| {
contribution.level().is_release() && Hidden::left_open(contribution.note()).is_some()
})
.map(|contribution| format!("`{}`", contribution.source()))
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
match (files.is_empty(), input.template) {
(false, _) => format!("the note of {}", files.join(", ")),
(true, Some(_)) => String::from("the template"),
(true, None) => String::from("the bump file's note"),
}
}
fn sort_like_the_plan_table(notes: &mut [ReleaseNote]) {
notes.sort_by(|a, b| {
let npm = |note: &ReleaseNote| note.ecosystem == Ecosystem::Npm;
npm(a).cmp(&npm(b)).then_with(|| a.package.cmp(&b.package))
});
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ReleaseNote {
pub ecosystem: Ecosystem,
pub package: String,
pub version: Version,
pub path: String,
pub entry: String,
}
fn read_back_sections(
path: &Path,
next: &str,
entries: &[(String, &Package, Owner, &Version)],
) -> Result<Vec<ReleaseNote>, CliError> {
entries
.iter()
.map(|(_, package, owner, to)| {
let id = package.id();
let Some(entry) = version_section(next, *owner, to) else {
let open = Hidden::left_open(next).unwrap_or("a code fence");
return Err(CliError::new(format!(
"{}: the {id} {to} heading would be hidden by {open} left open above it; close it in the changelog",
repo_path_display(path)
)));
};
Ok(ReleaseNote {
ecosystem: id.ecosystem,
package: id.name.clone(),
version: (*to).clone(),
path: repo_path_display(path),
entry,
})
})
.collect()
}
pub(super) fn changelog_repo_path(package: &Package) -> String {
repo_path_display(&changelog_path(package))
}
pub(super) fn has_version_section(
dir: &Dir,
package: &Package,
owner: Owner,
) -> Result<bool, CliError> {
let path = changelog_path(package);
let Some(text) = read_resolved_text(dir, &path)? else {
if dir.symlink_metadata(&path).is_ok() {
return Err(CliError::unverified(format!(
"unverified: `{}` is a symlink whose target does not exist",
repo_path_display(&path)
)));
}
return Ok(false);
};
section_or_refusal(&path, &text, owner, package.version())
}
pub(super) fn has_earlier_section(
dir: &Dir,
package: &Package,
owner: Owner,
) -> Result<bool, CliError> {
let Some(text) = read_resolved_text(dir, &changelog_path(package))? else {
return Ok(false);
};
let mut hidden = Hidden::of(&text).lines();
Ok(text
.lines()
.map(|line| line.trim_end_matches('\r'))
.any(|line| {
!hidden.next().unwrap_or(false)
&& line
.strip_prefix("## ")
.and_then(|rest| {
heading_version(rest, HeadingToken::Whole, &[owner.name], !owner.shared)
})
.is_some_and(|found| found.cmp_precedence(package.version()).is_lt())
}))
}
pub(super) fn section_or_refusal(
path: &Path,
text: &str,
owner: Owner,
version: &Version,
) -> Result<bool, CliError> {
if let Some(refusal) = open_html(text) {
return Err(refusal.into_error(path));
}
if let Some(refusal) = unnamed_heading(&repo_path_display(path), text, owner, version) {
return Err(refusal);
}
Ok(holds_version_section(text, owner, version))
}
pub(super) fn holds_version_section(text: &str, owner: Owner, version: &Version) -> bool {
section_for_version(text, owner, version).is_some()
}
pub(super) fn section_for_version(text: &str, owner: Owner, version: &Version) -> Option<String> {
version_section(text, owner, version).or_else(|| {
let mut bare = version.clone();
bare.build = semver::BuildMetadata::EMPTY;
version_section(text, owner, &bare)
})
}
fn changelog_path(package: &Package) -> PathBuf {
PathBuf::from(package.file_path(CHANGELOG_NAME))
}
fn emit_section(
package: &Package,
owner: Owner,
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, owner, change, bump, ¬es, input);
}
let heading = owner.heading(change.to());
if input.supplied_notes.is_some() {
return Ok(supplied_section(
&heading,
input.date,
notes.first().copied(),
));
}
Ok(builtin_section(
&heading,
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(heading: &dyn std::fmt::Display, date: &str, body: Option<&str>) -> String {
match body {
Some(body) => format!("## {heading} ({date})\n\n{body}\n"),
None => format!("## {heading} ({date})\n"),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Section {
Added,
Changed,
Deprecated,
Removed,
Fixed,
Security,
}
impl Section {
const ALL: [Self; 6] = [
Self::Added,
Self::Changed,
Self::Deprecated,
Self::Removed,
Self::Fixed,
Self::Security,
];
const fn heading(self) -> &'static str {
match self {
Self::Added => "Added",
Self::Changed => "Changed",
Self::Deprecated => "Deprecated",
Self::Removed => "Removed",
Self::Fixed => "Fixed",
Self::Security => "Security",
}
}
}
fn builtin_section(
heading: &dyn std::fmt::Display,
date: &str,
bump: Option<&AggregatedBump>,
cascade: Option<(&str, &Version)>,
) -> String {
let mut out = format!("## {heading} ({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[Section::Changed as usize].push(line);
}
for (section, notes) in Section::ALL.into_iter().zip(grouped) {
if notes.is_empty() {
continue;
}
out.push('\n');
out.push_str("### ");
out.push_str(section.heading());
out.push_str("\n\n");
out.push_str(¬es.join("\n\n"));
out.push('\n');
}
out
}
fn grouped_notes(bump: Option<&AggregatedBump>) -> [Vec<&str>; 6] {
let mut grouped: [Vec<&str>; 6] = Default::default();
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()) {
grouped[section as usize].push(body);
}
}
}
grouped
}
fn note_sections(note: &str, level: BumpLevel) -> Vec<(Section, &str)> {
walk_note(note, level).rendered
}
struct NoteWalk<'a> {
rendered: Vec<(Section, &'a str)>,
dropped: Vec<Section>,
}
fn walk_note(note: &str, level: BumpLevel) -> NoteWalk<'_> {
let mut walk = NoteWalk {
rendered: Vec::new(),
dropped: Vec::new(),
};
let default = match level {
BumpLevel::Minor => Section::Added,
BumpLevel::Major => Section::Changed,
BumpLevel::Patch => Section::Fixed,
BumpLevel::None => return walk,
};
let Some(body) = note_body(note) else {
return walk;
};
let mut hidden = Hidden::of(body).lines();
let mut heading: Option<Section> = None;
let mut start = 0;
let mut offset = 0;
let mut written = Vec::new();
let mut close = |heading: Option<Section>, chunk| match section_body(chunk) {
Some(text) => {
written.extend(heading);
walk.rendered.push((heading.unwrap_or(default), text));
}
None => walk.dropped.extend(heading),
};
for line in body.split_inclusive('\n') {
if !hidden.next().unwrap_or(false) {
if let Some(named) = section_heading(line) {
close(heading, &body[start..offset]);
heading = Some(named);
start = offset + line.len();
}
}
offset += line.len();
}
close(heading, &body[start..]);
let mut named = Vec::new();
walk.dropped.retain(|heading| {
let lost = !written.contains(heading) && !named.contains(heading);
named.push(*heading);
lost
});
walk
}
pub(super) fn dropped_headings(note: &str, level: BumpLevel) -> Vec<&'static str> {
walk_note(note, level)
.dropped
.into_iter()
.map(Section::heading)
.collect()
}
pub(super) fn heading_list(headings: &[&str]) -> String {
headings
.iter()
.map(|heading| format!("`### {heading}`"))
.collect::<Vec<_>>()
.join(", ")
}
fn section_body(chunk: &str) -> Option<&str> {
note_body(chunk).filter(|text| !text.trim().is_empty())
}
fn section_heading(line: &str) -> Option<Section> {
let (columns, rest) = indent_columns(line);
if columns >= 4 {
return None;
}
let named = rest.trim_end().strip_prefix("### ")?;
Section::ALL
.into_iter()
.find(|section| section.heading().eq_ignore_ascii_case(named.trim()))
}
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: section.heading(),
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,
owner: Owner,
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');
}
let (id, to) = (package.id(), change.to());
if rendered.trim().is_empty() {
return Err(Box::new(CliError::new(format!(
"the changelog template renders nothing for {id} {to} ({source_kind}, {} note(s)); every bumped version needs its section, cascades included",
notes.len()
))));
}
let mut hidden = Hidden::of(&rendered).lines();
let first_heading = rendered
.lines()
.map(|line| line.trim_end_matches('\r'))
.find(|line| !hidden.next().unwrap_or(false) && line.trim_start().starts_with('#'))
.and_then(|line| line.strip_prefix("## "));
let reads_back = |bare: bool| {
first_heading
.and_then(|rest| heading_version(rest, HeadingToken::Whole, &[owner.name], bare))
.is_some_and(|found| found == *to)
};
if !reads_back(!owner.shared) {
let fix = if reads_back(true) {
format!(
"{} is shared with other packages, so only `## {{{{ package }}}}@{{{{ version }}}}` names {id}'s section",
changelog_repo_path(package)
)
} else {
String::from(READABLE_HEADINGS)
};
return Err(Box::new(CliError::new(format!(
"the changelog template renders no heading oakum can read back for {id} {to}; {fix}"
))));
}
Ok(rendered)
}
pub(super) 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],
names: &[&str],
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, names) {
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, owner: Owner, version: &Version) -> Option<String> {
let mut hidden = Hidden::of(text).lines();
let mut lines = text
.lines()
.map(|line| (line.trim_end_matches('\r'), hidden.next().unwrap_or(false)));
lines.find(|(line, hidden)| {
!hidden
&& line
.strip_prefix("## ")
.and_then(|rest| {
heading_version(rest, HeadingToken::Whole, &[owner.name], !owner.shared)
})
.is_some_and(|found| found == *version)
})?;
let body: Vec<&str> = lines
.take_while(|(line, hidden)| {
*hidden || !(line.starts_with("## ") || line.starts_with("# ") || is_oakum_footer(line))
})
.map(|(line, _)| line)
.collect();
Some(body.join("\n").trim_matches('\n').to_owned())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SpliceRefusal {
Bom,
Title,
OpenHtml {
block: &'static str,
line: usize,
},
}
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)
),
Self::OpenHtml { block, line } => format!(
"{} leaves {block} open from line {line}, which hides every heading after it",
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)"
}
Self::OpenHtml { .. } => "close it, or remove the opening tag",
}
}
pub(super) fn into_error(self, path: &Path) -> CliError {
CliError::new(format!("{}; {}", self.reason(path), self.fix()))
}
}
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);
}
open_html(text)
}
pub(super) fn open_html(text: &str) -> Option<SpliceRefusal> {
Hidden::open_html(text).map(|(block, line)| SpliceRefusal::OpenHtml { block, line })
}
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;
}
match read_text(dir, &path)? {
Some(text) => {
if let Some(refusal) = splice_refusal(&text) {
reports.push(format!("{}; {}", refusal.reason(&path), refusal.fix()));
}
}
None => match dir.symlink_metadata(&path) {
Ok(_) => reports.push(format!(
"{} is a symlink whose target does not exist; point it at a file, or remove it",
repo_path_display(&path)
)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
return Err(std::io::Error::new(
err.kind(),
format!("failed to inspect {}: {err}", repo_path_display(&path)),
)
.into());
}
},
}
}
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, names: &[&str]) -> Option<usize> {
let mut pos = 0;
let mut hidden = Hidden::of(text).lines();
for line in text.split_inclusive('\n') {
let content = line.trim_end_matches(['\n', '\r']);
if !hidden.next().unwrap_or(false) && is_version_heading(content, names) {
return Some(pos);
}
pos += line.len();
}
None
}
fn is_version_heading(line: &str, names: &[&str]) -> bool {
let Some(rest) = line.strip_prefix("## ") else {
return false;
};
heading_version(rest, HeadingToken::BeforeDate, names, true).is_some()
}
#[derive(Clone, Copy)]
enum HeadingToken {
Whole,
BeforeDate,
}
fn heading_version(rest: &str, ends: HeadingToken, names: &[&str], bare: bool) -> Option<Version> {
let word = rest
.trim_start_matches('[')
.split([']', ' ', '('])
.next()
.unwrap_or("");
let word = match word.rsplit_once('@') {
Some((name, version)) if names.contains(&name) => version,
None if bare => word,
Some(_) | None => return None,
};
let word = word.trim_start_matches('v');
let token = match ends {
HeadingToken::BeforeDate => word.split('-').next().unwrap_or(""),
HeadingToken::Whole => word,
};
Version::parse(token).ok()
}
pub(super) const READABLE_HEADINGS: &str =
"start the section with `## {{ version }}` (or `## [{{ version }}]`, `## v{{ version }}`, `## {{ package }}@{{ version }}`)";
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::{
builtin_section, change_contexts, civil_from_days, join_blocks, left_open_by,
pull_request_number, release_notes, repo_path_display, sort_like_the_plan_table,
splice_refusal, strip_oakum_footer, supplied_note, supplied_section, ymd_from_unix_days,
ChangelogPlan, Links, Owner, Provenance, ReleaseNote, Section, SpliceRefusal,
};
use oakum::plan::{aggregate, BumpFile, BumpLevel, Ecosystem, PackageId};
use semver::Version;
use std::path::Path;
const NAME: &str = "demo";
#[test]
fn sections_are_keep_a_changelogs_in_its_order() {
assert_eq!(
Section::ALL.map(Section::heading),
[
"Added",
"Changed",
"Deprecated",
"Removed",
"Fixed",
"Security"
]
);
for (index, section) in Section::ALL.into_iter().enumerate() {
assert_eq!(section as usize, index, "{section:?}");
}
}
#[test]
fn release_notes_sort_like_the_plan_table() {
let note = |ecosystem, package: &str| ReleaseNote {
ecosystem,
package: package.to_owned(),
version: Version::new(1, 0, 0),
path: String::from("CHANGELOG.md"),
entry: String::new(),
};
let mut notes = vec![
note(Ecosystem::Npm, "app"),
note(Ecosystem::Cargo, "lib"),
note(Ecosystem::Cargo, "core"),
];
sort_like_the_plan_table(&mut notes);
let order: Vec<&str> = notes.iter().map(|note| note.package.as_str()).collect();
assert_eq!(order, ["core", "lib", "app"]);
}
fn version_section(text: &str, version: &Version) -> Option<String> {
super::version_section(text, Owner::new(NAME, false), version)
}
fn splice(
path: &Path,
existing: &str,
sections: &[String],
tool_version: &str,
) -> Result<String, Box<dyn std::error::Error>> {
super::splice(path, existing, sections, &[NAME], tool_version)
}
fn cargo(name: &str) -> PackageId {
PackageId::new(Ecosystem::Cargo, name)
}
#[test]
fn a_build_version_holds_its_own_heading_or_the_bare_one() {
let version = Version::parse("0.1.0+local").expect("version");
for (text, holds) in [
("## 0.1.0+local\n", true),
("## 0.1.0\n", true),
("## 0.1.1\n", false),
] {
assert_eq!(
super::holds_version_section(text, Owner::new(NAME, false), &version),
holds,
"{text}"
);
}
}
#[test]
fn a_build_version_prefers_its_own_heading_to_the_bare_one() {
let version = Version::parse("0.1.0+local").expect("version");
assert_eq!(
super::section_for_version(
"## 0.1.0\n\n- bare\n\n## 0.1.0+local\n\n- own\n",
Owner::new(NAME, false),
&version
)
.as_deref(),
Some("- own")
);
}
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 an_open_block_is_traced_to_what_opened_it() {
let templated = ChangelogPlan::new("2026-08-25", "0.0.0", Some(""), None, None);
assert_eq!(
left_open_by(Some(&bump("<pre>\nx", BumpLevel::Patch)), &templated),
"the note of `one.md`"
);
assert_eq!(
left_open_by(Some(&bump("<pre>\nx", BumpLevel::None)), &templated),
"the template",
"a `none` note renders nowhere, so it opens nothing"
);
assert_eq!(
left_open_by(Some(&bump("closed", BumpLevel::Patch)), &templated),
"the template"
);
let supplied = ChangelogPlan::new("2026-08-25", "0.0.0", Some(""), Some("<!--\nx"), None);
assert_eq!(
left_open_by(Some(&bump("<pre>\nx", BumpLevel::Patch)), &supplied),
"the `--notes-file` body",
"a supplied body replaces the notes"
);
}
#[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_hidden_heading() {
for hiding in [
"```md\n## 9.9.9\n\n- fake\n```",
"<!--\n## 9.9.9\n-->",
"<details>\n\n## 9.9.9\n\n</details>",
] {
let existing = format!(
"# Changelog\n\nExample entry:\n\n{hiding}\n\n## 0.1.0 (2026-01-01)\n\n- first\n"
);
let at = super::version_heading_start(&existing, &[NAME]).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 version_section_reads_name_at_version_headings() {
let text = "## my-pkg@1.2.3 - 2026-01-01\n\nmine\n\n## @scope/pkg@1.2.2\n\nscoped\n\n## @scope/pkg@v1.2.1\n\nprefixed\n";
for (name, version, body) in [
("my-pkg", Version::new(1, 2, 3), "mine"),
("@scope/pkg", Version::new(1, 2, 2), "scoped"),
("@scope/pkg", Version::new(1, 2, 1), "prefixed"),
] {
assert_eq!(
super::version_section(text, Owner::new(name, false), &version).as_deref(),
Some(body)
);
}
let spliced = super::splice(
Path::new("CHANGELOG.md"),
&format!("# Changelog\n\n{text}"),
&[String::from("## my-pkg@1.2.4\n\nnew\n")],
&["my-pkg"],
"0.0.0",
)
.unwrap();
assert!(
spliced.starts_with("# Changelog\n\n## my-pkg@1.2.4\n"),
"{spliced}"
);
}
#[test]
fn a_heading_in_a_comment_or_details_block_is_no_section() {
for text in [
"<!-- ## 0.1.1 -->\n",
"<!--\n## 0.1.1\n\n- draft\n-->\n",
"<details>\n<summary>old</summary>\n\n## 0.1.1\n\n- old\n</details>\n",
] {
assert_eq!(
version_section(text, &Version::new(0, 1, 1)),
None,
"{text}"
);
}
assert_eq!(
version_section(
"## 0.1.2\n\n- new\n<!--\n## 0.1.1\n-->\n- more\n\n## 0.1.1\n",
&Version::new(0, 1, 2)
)
.as_deref(),
Some("- new\n<!--\n## 0.1.1\n-->\n- more")
);
}
#[test]
fn a_block_left_open_refuses_the_read() {
let owner = Owner::new(NAME, false);
let path = Path::new("CHANGELOG.md");
for text in [
"# Changelog\n\n## 0.2.0\n\n- b\n<details>\n\n## 0.1.0\n\n- a\n",
"# Changelog\n\n<!-- draft\n## 0.1.0\n",
] {
let err = super::section_or_refusal(path, text, owner, &Version::new(0, 1, 0))
.expect_err(text);
assert!(err.to_string().contains("open from line"), "{err}");
}
assert_eq!(
super::section_or_refusal(
path,
"<!-->\n## 0.1.0\n\n- a\n",
owner,
&Version::new(0, 1, 0)
)
.ok(),
Some(true)
);
assert_eq!(
super::splice_refusal("# Changelog\n\n## 0.1.0\n\n<!-- x\n"),
Some(SpliceRefusal::OpenHtml {
block: "an HTML comment",
line: 5
})
);
}
#[test]
fn a_shared_changelog_reads_only_named_headings() {
let text = "## 1.2.3\n\nbare\n\n## demo@1.2.2\n\nnamed\n";
let shared = Owner::new("demo", true);
assert_eq!(
super::version_section(text, shared, &Version::new(1, 2, 3)),
None
);
assert_eq!(
super::version_section(text, shared, &Version::new(1, 2, 2)).as_deref(),
Some("named")
);
assert_eq!(shared.heading(&Version::new(1, 2, 4)), "demo@1.2.4");
assert_eq!(
Owner::new("demo", false).heading(&Version::new(1, 2, 4)),
"1.2.4"
);
}
#[test]
fn a_name_at_version_heading_is_read_only_for_its_package() {
let text = "## react@18.2.0 migration\n\nprose\n\n## @1.2.3\n\nbare\n\n## Version 1.2.4\n\nworded\n\n## 1.2.2\n\nreal\n";
for version in ["18.2.0", "1.2.3", "1.2.4"] {
let version = Version::parse(version).unwrap();
assert_eq!(
super::version_section(text, Owner::new("demo", false), &version),
None,
"{version}"
);
}
assert_eq!(
super::version_section(text, Owner::new("react", false), &Version::new(18, 2, 0))
.as_deref(),
Some("prose")
);
let spliced = super::splice(
Path::new("CHANGELOG.md"),
&format!("# Changelog\n\n{text}"),
&[String::from("## 1.2.5\n\nnew\n")],
&["demo"],
"0.0.0",
)
.unwrap();
assert!(
spliced.contains("worded\n\n## 1.2.5\n\nnew\n\n## 1.2.2\n"),
"{spliced}"
);
}
#[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 a_heading_inside_a_pre_block_does_not_split_the_note() {
let file = BumpFile {
id: String::from("pre.md"),
entries: vec![(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)],
note: String::from("<pre>\n### Added\nexample\n</pre>\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### Fixed\n\n<pre>\n### Added\nexample\n</pre>\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!(err.is_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",
},
);
}
}
#[cfg(test)]
mod dropped_note_tests {
use super::dropped_headings;
use oakum::plan::bump::BumpLevel;
const NONE: [&str; 0] = [];
#[test]
fn a_heading_with_no_body_is_dropped() {
assert_eq!(dropped_headings("### Added\n", BumpLevel::Minor), ["Added"]);
assert_eq!(
dropped_headings("### Added\n\n \n", BumpLevel::Minor),
["Added"]
);
}
#[test]
fn one_empty_heading_among_populated_ones_is_dropped() {
assert_eq!(
dropped_headings("### Added\n\nreal text\n\n### Fixed", BumpLevel::Minor),
["Fixed"]
);
assert_eq!(
dropped_headings(
"### Changed\n\n### Added\n\nreal\n\n### Fixed\n",
BumpLevel::Major
),
["Changed", "Fixed"]
);
}
#[test]
fn a_repeated_heading_is_dropped_only_when_no_copy_renders() {
assert_eq!(
dropped_headings("### Fixed\n\n### Fixed\n\ntext\n", BumpLevel::Patch),
NONE
);
assert_eq!(
dropped_headings("### Fixed\n### Fixed\n### Added\nx\n", BumpLevel::Minor),
["Fixed"]
);
for level in [BumpLevel::Patch, BumpLevel::Minor, BumpLevel::Major] {
assert_eq!(
dropped_headings("leading text\n\n### Fixed\n", level),
["Fixed"],
"{level:?}"
);
}
assert_eq!(
super::heading_list(&dropped_headings(
"### Changed\n\n### Added\n\nreal\n\n### Fixed\n",
BumpLevel::Major
)),
"`### Changed`, `### Fixed`"
);
}
#[test]
fn unnamed_and_fenced_text_drops_no_heading() {
assert_eq!(
dropped_headings("\n\n### Added\n\nreal\n", BumpLevel::Minor),
NONE
);
assert_eq!(
dropped_headings("text\n\n```\n### Fixed\n```\n", BumpLevel::Patch),
NONE
);
}
#[test]
fn a_coverage_only_note_and_an_empty_note_are_not_dropped() {
assert_eq!(dropped_headings("### Added\n", BumpLevel::None), NONE);
assert_eq!(dropped_headings("", BumpLevel::Minor), NONE);
assert_eq!(dropped_headings("\n\n", BumpLevel::Minor), NONE);
}
#[test]
fn a_whitespace_only_note_is_not_dropped() {
assert_eq!(dropped_headings(" \n\t\n", BumpLevel::Minor), NONE);
assert_eq!(dropped_headings(" ", BumpLevel::Patch), NONE);
}
#[test]
fn a_note_that_renders_is_not_dropped() {
assert_eq!(
dropped_headings("### Added\n\nreal text\n", BumpLevel::Minor),
NONE
);
assert_eq!(
dropped_headings("bare body with no heading\n", BumpLevel::Patch),
NONE
);
}
}