use oakum::plan::{format_versions, PlanComparison, Versioning};
use semver::Version;
use super::ci::VERSION_BRANCH;
use super::migrate::{BumpRewrite, VersioningChoice};
use super::migrate_config::{chosen_commit_message, SourceConfig};
use super::migrate_gates::GateLook;
use super::owned_files::{
commit_message_line, ConfigSettings, OwnedPlan, ReadmeState, SchemaState, README_REL,
};
use super::quoted;
use super::say_out;
use super::tag_shape::{ReadableTemplate, TagShape};
use super::CliError;
pub(super) fn pending_owned_line(owned: OwnedPlan) -> String {
let schema = match owned.schema {
SchemaState::Absent => "write .changeset/_schema.json",
SchemaState::Stale => "replace the existing .changeset/_schema.json",
SchemaState::Current => "leave the current .changeset/_schema.json",
};
if owned.readme == ReadmeState::Absent {
format!("write .changeset/_config.toml and .changeset/README.md, and {schema}")
} else {
format!("write .changeset/_config.toml and {schema} (keeping the existing .changeset/README.md)")
}
}
pub(super) fn print_tag_shape(shape: &TagShape, written: Option<ReadableTemplate>) {
if let Some(template) = written {
say_out(&format!(
"carried over: `tag-format = \"{}\"` (derived from the existing tags{})",
template.as_str(),
skipped_clause(shape)
));
return;
}
if let TagShape::Unread(why) = shape {
say_out(&format!(
"not derived: `tag-format` (could not read the existing tags: {why})"
));
}
}
fn skipped_clause(shape: &TagShape) -> String {
let TagShape::Derived { skipped, .. } = shape else {
return String::new();
};
if skipped.is_empty() {
return String::new();
}
format!(
"; {} state no version and were not weighed",
quoted(skipped)
)
}
fn undecided_tag_step(shape: &TagShape) -> Option<String> {
let TagShape::Undecided { why, offerable } = shape else {
return None;
};
Some(format!(
"- set `tag-format` to match the existing tags ({why}); `release` refuses at the first tag rather than writing a shape the repository does not use\n oakum reads {}",
quoted(offerable.iter().map(|template| template.as_str()))
))
}
pub(super) fn versioning_line(chosen: VersioningChoice) -> String {
let versioning = chosen.versioning();
let why = match (chosen, versioning) {
(VersioningChoice::Requested(_), _) => {
String::from("from `--versioning`, not the source tool")
}
(VersioningChoice::Inferred(from), Versioning::ZeroMajor) => {
format!("{} holds a breaking change below 1.0.0", from.name())
}
(VersioningChoice::Inferred(from), Versioning::Semver) => format!(
"{} takes 0.1.3 to 1.0.0, and renumbering an established release line is not a migration's job; oakum's own default is `zero-major`",
from.name()
),
};
format!(" write `versioning = \"{versioning}\"` ({why})")
}
pub(super) fn print_pending(
planned: &[BumpRewrite],
sources: &[SourceConfig],
settings: &ConfigSettings,
owned: OwnedPlan,
chosen: VersioningChoice,
) {
let carried = settings.private_packages;
say_out("pending:");
for rewrite in planned {
match rewrite.leftover() {
Some(source) => say_out(&format!(" write {} from {source}", rewrite.dest())),
None => say_out(&format!(" rewrite {}", rewrite.dest())),
}
}
say_out(&format!(" {}", pending_owned_line(owned)));
for source in sources {
let file = source.file;
if let Some(private) = source.carried_private_packages() {
say_out(&format!(
" carry {} from `{file}`",
private
.axis_names()
.iter()
.map(|axis| format!("`privatePackages.{axis}`"))
.collect::<Vec<_>>()
.join(" and ")
));
}
for key in &source.dropped {
say_out(&format!(" leave `{key}` behind in `{file}` (not carried)"));
}
}
if carried.any() {
say_out(&format!(" write `{}`", carried.toml_line()));
}
say_out(&versioning_line(chosen));
if let Some((file, message)) = chosen_commit_message(sources) {
say_out(&format!(
" carry `versionCommitMessage` from `{file}` as `{}`",
commit_message_line(message)
));
}
if let Some(template) = settings.tag_format {
say_out(&format!(
" carry the existing tag shape as `tag-format = \"{}\"`",
template.as_str()
));
}
}
pub(super) fn print_left_alone(
readme: ReadmeState,
sources: &[SourceConfig],
unreadable: &[String],
) {
if readme == ReadmeState::Theirs {
say_out(&format!(
"kept {README_REL} (oakum did not write it; left as is)"
));
}
for line in unreadable {
say_out(line);
}
if let Some((file, _)) = chosen_commit_message(sources) {
say_out(&format!(
"carried over: `versionCommitMessage` from `{file}` as `commit-message`"
));
}
for source in sources {
let file = source.file;
if let Some(private) = source.carried_private_packages() {
say_out(&format!(
"carried over: {} from `{file}`",
private
.axis_names()
.iter()
.map(|axis| format!("`privatePackages.{axis}`"))
.collect::<Vec<_>>()
.join(" and ")
));
}
for key in &source.dropped {
say_out(&format!(
"not carried over: `{key}` (`{file}` is untouched)"
));
}
}
}
pub(super) struct Remaining<'a> {
pub(super) detections: &'a [oakum::detect::Detection],
pub(super) knope: bool,
pub(super) foreign_changelogs: &'a [String],
pub(super) pinned: bool,
pub(super) npm: bool,
pub(super) binary: &'a Version,
pub(super) shape: &'a TagShape,
pub(super) leftovers: &'a [&'a str],
pub(super) gates: &'a GateLook,
pub(super) owed: &'a [String],
}
pub(super) fn print_remaining_steps(remaining: &Remaining<'_>) {
let Remaining {
detections,
knope,
foreign_changelogs,
pinned,
npm,
binary,
shape,
leftovers,
gates,
owed,
} = *remaining;
say_out("remaining (oakum does not perform these):");
for report in foreign_changelogs {
say_out(&format!("- {report}"));
}
if let Some(step) = undecided_tag_step(shape) {
say_out(&step);
}
if !pinned {
let install = if npm {
format!("pnpm add -D @oakoss/oakum@{binary}")
} else {
format!("cargo binstall --no-confirm oakum@{binary}")
};
say_out(&format!(
"- pin the same version as `tool-version` (`{binary}`): the workflow below carries one, or add `{install}` to this repository"
));
}
say_out("- add oakum to a workflow (YAML printed below)");
say_out(
"- publish: `oakum release` only tags and creates the GitHub release; the old workflow's publish step (`npm publish`, `cargo publish`) needs a job of its own on the tag push (`on: push: tags`)"
);
say_out(&format!(
"- the version PR opens on branch `{VERSION_BRANCH}`; add it to any branch-name filters that need it"
));
for hit in detections {
if let Some(path) = remaining_removal(hit.evidence()) {
say_out(&format!("- remove {path} ({})", hit.tool().name()));
}
}
if let Some(step) = leftover_bump_files_step(leftovers) {
say_out(&step);
}
if let Some(step) = bump_file_gate_step(gates) {
say_out(&step);
}
for step in owed {
say_out(step);
}
say_out("- remove the old tool's dependency and its workflow");
if knope {
say_out(
"- `.changeset/README.md` aborts knope until `knope.toml` and its workflow are removed",
);
}
print_adoptable();
}
fn print_adoptable() {
say_out("also available (oakum does these; the old tool may not have):");
say_out(
"- `extra-files`: declare a JSON file that carries a version — a plugin manifest, a \
marketplace entry — and `oakum version` writes it in the same pass as the manifest, \
under the same rollback. A sync script, its drift job and its tests can go. v1 writes \
JSON only (ADR-0033)",
);
say_out(
"- the changelog oakum writes is generated markdown that also reads as prose, so a \
repository linting it needs no per-release fixup step — once it applies the two lint \
settings `init` prints (ADR-0031)",
);
}
fn leftover_bump_files_step(leftovers: &[&str]) -> Option<String> {
if leftovers.is_empty() {
return None;
}
Some(format!(
"- remove the bump files oakum copied out and left behind ({}); the old tool still counts them, so a workflow still wired to it releases the same packages a second time",
quoted(leftovers)
))
}
const UNSEARCHED: &str = "oakum searched git's index outside `.changeset/`, so a gate that is untracked, an unstaged edit, inside a submodule, or in `.git/hooks/` is not covered — check those before the first release";
fn bump_file_gate_step(gates: &GateLook) -> Option<String> {
match gates {
GateLook::NothingToRepoint => None,
GateLook::Failed(why) => Some(format!(
"- unverified: oakum {}; a commit or CI gate pointed at it will reject oakum's bump files",
gate_look_failed(why)
)),
GateLook::NothingTracked => Some(format!(
"- git reports no commit and its index lists no file, so no tracked file could have gated anything. {UNSEARCHED}"
)),
GateLook::Found(paths) if paths.is_empty() => Some(format!(
"- no file in the index outside `.changeset/` names the old bump-file directory. {UNSEARCHED}"
)),
GateLook::Found(paths) => {
Some(format!(
"- check what names the old bump-file directory ({}); oakum cannot tell a commit or CI gate from a mention in prose, and a gate matching those paths rejects the bump files oakum writes. {UNSEARCHED}",
quoted(paths)
))
}
}
}
pub(super) fn gate_look_failed(why: &str) -> String {
format!(
"could not look for files gating on the old bump-file directory ({})",
one_line(why)
)
}
const KEPT: &str = "migrated files were kept; ";
pub(super) fn verdict(causes: impl IntoIterator<Item = CliError>) -> Result<(), CliError> {
let Some(joined) = causes.into_iter().reduce(|first, second| {
first.recast(format!("{}; and {}", first.detail(), second.detail()))
}) else {
return Ok(());
};
Err(joined.recast(format!("{KEPT}{}", joined.detail())))
}
pub(super) fn gate_look_refusal(why: &str) -> CliError {
CliError::unverified(format!("oakum {}", gate_look_failed(why)))
}
fn one_line(detail: &str) -> String {
let mut seen: Vec<&str> = Vec::new();
for line in detail
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
{
if !seen.contains(&line) {
seen.push(line);
}
}
seen.join("; ")
}
fn remaining_removal(evidence: &str) -> Option<&str> {
if evidence == ".changeset/" {
return None;
}
if evidence.starts_with(".changeset/") && evidence != ".changeset/config.json" {
return None;
}
Some(evidence)
}
pub(super) fn print_plan_comparison(
comparison: &PlanComparison,
before_label: &str,
planned_by: &str,
match_suffix: &str,
planned: usize,
) {
if let Some(diffs) = comparison.expected_knope_feature() {
say_out(
"plan comparison: knope maps a pending feature on a pre-1.0 package to patch; oakum maps it to minor"
);
for diff in diffs {
say_out(&format!(
" {}: {} ({before_label}) vs {} (oakum)",
diff.id(),
format_versions(diff.before()),
format_versions(diff.after()),
));
}
return;
}
if let Some(parts) = comparison.unexpected() {
say_out("plan comparison: unexpected difference");
for diff in parts.expected.iter().chain(parts.unexpected.iter()) {
say_out(&format!(
" {}: {} vs {}",
diff.id(),
format_versions(diff.before()),
format_versions(diff.after()),
));
}
return;
}
if planned == 0 {
say_out(&format!(
"plan comparison: nothing pending under {before_label} or oakum; the transform was not exercised{match_suffix}"
));
return;
}
say_out(&format!(
"plan comparison: {planned} package(s) {planned_by} and by oakum; match{match_suffix}"
));
}
#[cfg(test)]
mod gate_steps {
use super::super::migrate_gates::GateLook;
use super::{bump_file_gate_step, gate_look_refusal, one_line, verdict};
#[test]
fn every_outcome_has_its_own_line() {
assert_eq!(bump_file_gate_step(&GateLook::NothingToRepoint), None);
let empty = bump_file_gate_step(&GateLook::Found(Vec::new())).expect("empty look speaks");
assert!(empty.contains("no file in the index"), "{empty}");
for unsearched in ["untracked", "unstaged edit", "submodule", ".git/hooks/"] {
assert!(empty.contains(unsearched), "{unsearched}: {empty}");
}
let nothing =
bump_file_gate_step(&GateLook::NothingTracked).expect("an empty index speaks");
assert!(nothing.contains("git reports no commit"), "{nothing}");
assert!(
nothing.contains(".git/hooks/"),
"every arm carries the caveat: {nothing}"
);
assert_ne!(
nothing, empty,
"searched nothing is not searched and found none"
);
let one = bump_file_gate_step(&GateLook::Found(Vec::from([String::from("hook.sh")])))
.expect("a hit speaks");
assert!(
one.contains("check what names the old bump-file directory (`hook.sh`)"),
"{one}"
);
assert!(
one.contains("cannot tell a commit or CI gate from a mention in prose"),
"a match is a mention, not a proven gate: {one}"
);
assert_ne!(one, empty);
let two = bump_file_gate_step(&GateLook::Found(Vec::from([
String::from("hook.sh"),
String::from("gate.yml"),
])))
.expect("two hits speak");
assert!(two.contains("(`hook.sh`, `gate.yml`)"), "{two}");
let failed =
bump_file_gate_step(&GateLook::Failed(String::from("boom"))).expect("a failure speaks");
assert!(failed.starts_with("- unverified:"), "{failed}");
}
#[test]
fn a_multi_line_git_diagnostic_becomes_one_bullet() {
let detail = "exit 1: error: failed to stat 'gate.sh': Permission denied\nerror: failed to stat 'gate.sh': Permission denied";
assert_eq!(
one_line(detail),
"exit 1: error: failed to stat 'gate.sh': Permission denied; error: failed to stat 'gate.sh': Permission denied"
);
let step = bump_file_gate_step(&GateLook::Failed(String::from(detail))).expect("a line");
assert_eq!(step.lines().count(), 1, "{step}");
}
#[test]
fn the_step_and_the_refusal_state_one_fact() {
let why = "exit 1: error: failed to stat 'gate.sh': Permission denied";
let fact = "could not look for files gating on the old bump-file directory";
let step = bump_file_gate_step(&GateLook::Failed(String::from(why))).expect("a step");
let refusal = verdict([gate_look_refusal(why)]).unwrap_err().to_string();
for said in [&step, &refusal] {
assert!(said.contains(fact), "{said}");
assert!(said.contains(one_line(why).as_str()), "{said}");
}
assert!(
refusal.starts_with("migrated files were kept; oakum"),
"{refusal}"
);
assert_eq!(refusal.matches("unverified").count(), 0, "{refusal}");
}
#[test]
fn only_a_failed_look_is_a_failure() {
assert_eq!(
GateLook::Failed(String::from("boom")).failure(),
Some("boom")
);
for looked in [
GateLook::Found(Vec::new()),
GateLook::Found(Vec::from([String::from("hook.sh")])),
GateLook::NothingTracked,
GateLook::NothingToRepoint,
] {
assert_eq!(looked.failure(), None, "{looked:?}");
}
}
}
#[cfg(test)]
mod versioning_wording {
use oakum::detect::ReleaseTool;
use oakum::plan::Versioning;
use super::super::migrate::VersioningChoice;
use super::versioning_line;
#[test]
fn each_provenance_names_the_mode_and_what_settled_it() {
assert_eq!(
versioning_line(VersioningChoice::Inferred(ReleaseTool::Bumpy)),
" write `versioning = \"semver\"` (bumpy takes 0.1.3 to 1.0.0, and renumbering an established release line is not a migration's job; oakum's own default is `zero-major`)"
);
assert_eq!(
versioning_line(VersioningChoice::Inferred(ReleaseTool::Knope)),
" write `versioning = \"zero-major\"` (knope holds a breaking change below 1.0.0)"
);
assert_eq!(
versioning_line(VersioningChoice::Requested(Versioning::ZeroMajor)),
" write `versioning = \"zero-major\"` (from `--versioning`, not the source tool)"
);
}
}
#[cfg(test)]
mod pending_wording {
use super::super::owned_files::{OwnedPlan, ReadmeState, SchemaState};
use super::pending_owned_line;
fn plan(schema: SchemaState, readme: ReadmeState) -> OwnedPlan {
OwnedPlan { schema, readme }
}
#[test]
fn every_owned_file_state_has_its_sentence() {
assert_eq!(
pending_owned_line(plan(SchemaState::Absent, ReadmeState::Absent)),
"write .changeset/_config.toml and .changeset/README.md, and write .changeset/_schema.json"
);
assert_eq!(
pending_owned_line(plan(SchemaState::Stale, ReadmeState::Absent)),
"write .changeset/_config.toml and .changeset/README.md, and replace the existing .changeset/_schema.json"
);
assert_eq!(
pending_owned_line(plan(SchemaState::Current, ReadmeState::Absent)),
"write .changeset/_config.toml and .changeset/README.md, and leave the current .changeset/_schema.json"
);
assert_eq!(
pending_owned_line(plan(SchemaState::Absent, ReadmeState::Theirs)),
"write .changeset/_config.toml and write .changeset/_schema.json (keeping the existing .changeset/README.md)"
);
assert_eq!(
pending_owned_line(plan(SchemaState::Stale, ReadmeState::Ours)),
"write .changeset/_config.toml and replace the existing .changeset/_schema.json (keeping the existing .changeset/README.md)"
);
assert_eq!(
pending_owned_line(plan(SchemaState::Current, ReadmeState::Ours)),
"write .changeset/_config.toml and leave the current .changeset/_schema.json (keeping the existing .changeset/README.md)"
);
}
}