use std::{fs, path::PathBuf, time::Instant};
use scriba::{SelectOption, SelectRequest};
use crate::{
core::{Context, CoreResult},
engine::{
PromptTrait,
capabilities::changelog::{
BuildOptions, Release, ReleaseSpec, RenderedBlock, apply_links, build_release,
format_date, links::Links, merge_markdown, render_header, render_json,
render_markdown_release,
},
constants::emoji::SUCCESS,
error::ErrorCode,
models::{
git::CommitSummary,
policy::{
changelog::{ChangelogModel, ChangelogOutputFormat},
commit::CommitModel,
versioning::{Version, VersioningModel},
},
},
},
};
#[derive(Debug, Clone)]
pub struct Options {
pub all: bool,
pub from: Option<String>,
pub to: String,
pub output: Option<String>,
pub format: Option<ChangelogOutputFormat>,
pub group_by_scope: bool,
pub next_tag: Option<String>,
pub include_non_cc: bool,
pub prereleases: bool,
}
struct Range {
label: String,
date: Option<String>,
from: Option<String>,
to: String,
link_to: String,
}
impl Options {
fn is_untouched(&self) -> bool {
!self.all
&& self.from.is_none()
&& self.to == "HEAD"
&& self.output.is_none()
&& self.format.is_none()
&& !self.group_by_scope
&& self.next_tag.is_none()
&& !self.include_non_cc
&& !self.prereleases
}
}
fn ask(ctx: &Context, mut options: Options) -> CoreResult<Options> {
let ui = ctx.ui();
let invalid =
|field: &'static str| move |_| ErrorCode::InvalidInput.error().with_context("field", field);
let choice = ui
.select(&SelectRequest::new(
"What would you like to generate?".to_string(),
vec![
SelectOption::new("pending", "Changes since the last tag")
.description("An Unreleased section, or a version you name".to_string()),
SelectOption::new("all", "Full history")
.description("Every release found in the tag history".to_string()),
SelectOption::new("range", "Custom range")
.description("Everything between two revisions".to_string()),
],
))
.map_err(invalid("scope"))?;
match choice.as_str() {
"all" => options.all = true,
"range" => {
let from = ui.text(
"From (tag or commit)",
None,
Some("Required; excluded from the range"),
)?;
if from.trim().is_empty() {
return Err(ErrorCode::InvalidInput
.error()
.with_context("field", "from")
.with_context("reason", "the start of the range is required"));
}
options.from = Some(from.trim().to_string());
let to = ui.text("To (tag or commit)", Some("HEAD"), Some("Defaults to HEAD"))?;
if !to.trim().is_empty() {
options.to = to.trim().to_string();
}
}
_ => {}
}
if choice != "all" {
let label = ui.text(
"Version label",
None,
Some("Leave empty to call this section Unreleased"),
)?;
if !label.trim().is_empty() {
options.next_tag = Some(label.trim().to_string());
}
}
options.group_by_scope = ui.confirm("Group entries by scope?", false)?;
options.include_non_cc =
ui.confirm("Include commits that are not Conventional Commits?", false)?;
Ok(options)
}
pub fn run(ctx: &Context, options: Options) -> CoreResult<()> {
let options = if ctx.is_interactive() && !ctx.auto_yes() && options.is_untouched() {
ask(ctx, options)?
} else {
options
};
let ui = ctx.ui();
let git = ctx.git();
let start = Instant::now();
let resolved_config = ctx.config().ok_or_else(|| {
ErrorCode::ConfigUnreadable
.error()
.with_context("context", "Config not resolved")
})?;
let commit_model = CommitModel::from_config(resolved_config);
let changelog = ChangelogModel::from_config(resolved_config);
let versioning = VersioningModel::from_config(resolved_config);
if options.all && options.from.is_some() {
return Err(ErrorCode::InvalidInput
.error()
.with_context("reason", "--all and --from cannot be combined"));
}
let format = options.format.unwrap_or(changelog.format);
let target = resolve_output(&options, &changelog, format, ctx.repo_root());
let today = format_date(
chrono::Utc::now().timestamp(),
changelog.date_format.as_deref(),
);
let next_label = options
.next_tag
.as_deref()
.map(|tag| normalize_label(tag, &versioning.tag_prefix));
let tags = release_tags(
git.tags_reachable_from(&options.to)?,
&versioning.tag_prefix,
options.prereleases,
);
let mut ranges: Vec<Range> = Vec::new();
if let Some(from) = &options.from {
ranges.push(Range {
label: next_label
.clone()
.unwrap_or_else(|| format!("{from}..{}", options.to)),
date: today.clone(),
from: Some(from.clone()),
to: options.to.clone(),
link_to: next_label.clone().unwrap_or_else(|| options.to.clone()),
});
} else {
let latest = tags.first().map(|(tag, _)| tag.clone());
let pending = git.list_commits(latest.as_deref(), &options.to)?;
if !pending.is_empty() || next_label.is_some() {
ranges.push(Range {
label: next_label
.clone()
.unwrap_or_else(|| changelog.unreleased_label.clone()),
date: next_label.as_ref().and(today.clone()),
from: latest,
to: options.to.clone(),
link_to: next_label.clone().unwrap_or_else(|| options.to.clone()),
});
}
if options.all {
for (index, (tag, _)) in tags.iter().enumerate() {
let timestamp = git.tag_timestamp(tag)?;
ranges.push(Range {
label: tag.clone(),
date: timestamp
.and_then(|seconds| format_date(seconds, changelog.date_format.as_deref())),
from: tags.get(index + 1).map(|(older, _)| older.clone()),
to: tag.clone(),
link_to: tag.clone(),
});
}
}
}
let build_options = BuildOptions {
include_non_cc: options.include_non_cc,
};
let links = repo_links(ctx, &changelog);
let mut releases: Vec<Release> = Vec::new();
for range in ranges {
let commits: Vec<CommitSummary> = git
.list_commits(range.from.as_deref(), &range.to)
.map_err(|err| {
err.with_context(
"hint",
format!(
"could not read commits in {}..{}; check that both revisions exist",
range.from.as_deref().unwrap_or("<start>"),
range.to
),
)
})?;
let mut release = build_release(
ReleaseSpec {
label: range.label,
date: range.date,
from: range.from,
to: range.to,
},
&commits,
&commit_model,
&changelog,
build_options,
);
if let Some(links) = &links {
apply_links(&mut release, links, &range.link_to);
}
releases.push(release);
}
let entries: usize = releases.iter().map(Release::entry_count).sum();
let rendered = match format {
ChangelogOutputFormat::Json => render_json(&releases),
ChangelogOutputFormat::Markdown => {
let blocks: Vec<RenderedBlock> = releases
.iter()
.map(|release| RenderedBlock {
label: release.label.clone(),
text: render_markdown_release(release, &changelog, options.group_by_scope),
})
.collect();
let existing = match &target {
Target::File(path) if !ctx.force() && path.exists() => {
Some(fs::read_to_string(path)?)
}
_ => None,
};
merge_markdown(
existing.as_deref(),
&render_header(&changelog),
&blocks,
&changelog.unreleased_label,
)
}
};
let nothing_to_do = releases.is_empty();
let mut written = false;
match &target {
Target::Stdout => {
print!("{rendered}");
return Ok(());
}
Target::File(path) if !ctx.dry_run() && !nothing_to_do => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
crate::engine::fs::write_text(path, &rendered)?;
written = true;
}
Target::File(_) => {}
}
if nothing_to_do {
ui.logger().info("No unreleased changes found");
} else if written {
ui.logger().ok(&format!(
"{SUCCESS} Changelog updated: {}",
target.display()
));
}
let meta = ui
.new_output_meta()
.with_command("changelog".to_string())
.with_duration_ms(start.elapsed().as_millis() as u64)
.with_timestamp(chrono::Utc::now().to_string())
.with_dry_run(ctx.dry_run());
let mut content = ui
.new_output_content()
.title("Changelog")
.subtitle("Release notes generated from Conventional Commits")
.data("output", target.display())
.data("format", format_name(format))
.data("releases", releases.len().to_string())
.data("entries", entries.to_string())
.data("written", written.to_string());
if !releases.is_empty() {
let labels = releases
.iter()
.map(|release| release.label.clone())
.collect::<Vec<_>>()
.join(", ");
content = content.data("labels", labels);
}
if ctx.dry_run() && !nothing_to_do {
content = content.section("Preview", rendered, "markdown".to_string());
}
ui.print_with_meta(&content, Some(&meta), true)
}
fn repo_links(ctx: &Context, changelog: &ChangelogModel) -> Option<Links> {
if !changelog.links_enabled {
return None;
}
match &changelog.links_url {
Some(url) => Some(Links::new(url)),
None => ctx
.git()
.remote_url("origin")
.and_then(|remote| Links::from_remote(&remote)),
}
}
enum Target {
Stdout,
File(PathBuf),
}
impl Target {
fn display(&self) -> String {
match self {
Target::Stdout => "-".to_string(),
Target::File(path) => path.display().to_string(),
}
}
}
fn resolve_output(
options: &Options,
changelog: &ChangelogModel,
format: ChangelogOutputFormat,
repo_root: &std::path::Path,
) -> Target {
if options.output.as_deref() == Some("-") {
return Target::Stdout;
}
let mut path = PathBuf::from(options.output.as_deref().unwrap_or(&changelog.output));
if options.output.is_none()
&& format == ChangelogOutputFormat::Json
&& path.extension().is_some_and(|ext| ext == "md")
{
path.set_extension("json");
}
Target::File(if path.is_absolute() {
path
} else {
repo_root.join(path)
})
}
fn format_name(format: ChangelogOutputFormat) -> &'static str {
match format {
ChangelogOutputFormat::Markdown => "markdown",
ChangelogOutputFormat::Json => "json",
}
}
fn normalize_label(tag: &str, prefix: &str) -> String {
match Version::parse(tag, prefix) {
Some(version) => version.format(prefix),
None => tag.to_string(),
}
}
fn release_tags(tags: Vec<String>, prefix: &str, prereleases: bool) -> Vec<(String, Version)> {
let mut versions: Vec<(String, Version)> = tags
.into_iter()
.filter_map(|tag| Version::parse(&tag, prefix).map(|version| (tag, version)))
.filter(|(_, version)| prereleases || !version.is_prerelease())
.collect();
versions.sort_by(|a, b| b.1.cmp(&a.1));
versions
}