rustyphoenixcommitrelease 1.1.0

Generates the changelog with git-cliff and commits/tags/pushes a Phoenix release
use anyhow::{bail, Context, Result};
use std::fs;
use std::path::Path;
use std::process::Command;

fn run(repo_path: &Path, args: &[&str]) -> Result<()> {
	let status = Command::new("git-cliff")
		.current_dir(repo_path)
		.args(args)
		.status()
		.context("failed to run git-cliff")?;

	if !status.success() {
		bail!("git-cliff {:?} failed", args);
	}

	Ok(())
}

fn prepend_args<'a>(version: &'a str, changelog_path: &'a str, config: Option<&'a str>) -> Vec<&'a str> {
	let mut args = vec!["--unreleased", "--tag", version, "--prepend", changelog_path];
	if let Some(config) = config {
		args.push("--config");
		args.push(config);
	}
	args
}

/// Prepends the unreleased entry (tagged as `version`) to `changelog_path`, creating the file
/// first if this is the project's first release: git-cliff's `--prepend` reads the existing
/// file before writing back to it, and errors out ("No such file or directory") if it is absent.
/// `config` points at a git-cliff `cliff.toml` outside the target repo (eg the one baked into the
/// release_tools image), so every project shares the same config without duplicating the file.
pub fn prepend_changelog(repo_path: &Path, version: &str, changelog_path: &str, config: Option<&str>) -> Result<()> {
	let full_path = repo_path.join(changelog_path);
	if !full_path.exists() {
		fs::write(&full_path, "").with_context(|| format!("failed to create {}", full_path.display()))?;
	}

	run(repo_path, &prepend_args(version, changelog_path, config))
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn prepend_args_targets_the_changelog_file() {
		assert_eq!(
			prepend_args("1.2.3", "CHANGELOG.md", None),
			vec!["--unreleased", "--tag", "1.2.3", "--prepend", "CHANGELOG.md"]
		);
	}

	#[test]
	fn prepend_args_includes_config_when_given() {
		assert_eq!(
			prepend_args("1.2.3", "CHANGELOG.md", Some("/home/PIXI_USER/cliff.toml")),
			vec!["--unreleased", "--tag", "1.2.3", "--prepend", "CHANGELOG.md", "--config", "/home/PIXI_USER/cliff.toml"]
		);
	}
}