use oakum::detect::ReleaseTool;
use oakum::plan::{format_versions, PlanComparison, Versioning};
use semver::Version;
use super::ci::VERSION_BRANCH;
use super::install_pin::Owed;
use super::migrate::{BumpRewrite, VersioningChoice};
use super::migrate_config::{chosen_commit_message, SourceConfig};
use super::migrate_gates::{GateLook, HookLook, IndexLook};
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::workflow::{workflow_text, WorkflowPins};
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",
};
match owned.readme {
ReadmeState::Absent => {
format!("write .changeset/_config.toml and .changeset/README.md, and {schema}")
}
ReadmeState::Stale => format!(
"write .changeset/_config.toml, replace the earlier oakum .changeset/README.md, and {schema}"
),
ReadmeState::Ours | ReadmeState::Theirs => 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) owed_pin: Option<&'a Owed>,
pub(super) pins: &'a WorkflowPins,
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,
owed_pin,
pins,
binary,
shape,
leftovers,
gates,
owed,
} = *remaining;
say_out("remaining (oakum does not perform these):");
for step in pins.owed_steps(owed_pin, binary, &workflow_text(binary, pins)) {
say_out(&format!("- {step}"));
}
for report in foreign_changelogs {
say_out(&format!("- {report}"));
}
if let Some(step) = undecided_tag_step(shape) {
say_out(&step);
}
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);
}
for step in bump_file_gate_steps(gates) {
say_out(&step);
}
if let Some(step) =
kept_bump_directory_step(detections.iter().map(oakum::detect::Detection::tool))
{
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 its linter turns MD041 \
off for `.changeset/*.md` and sets MD024 `siblings_only` (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)
))
}
fn unsearched(hooks: &HookLook) -> String {
let (searched, untracked) = match hooks {
HookLook::Read { .. } => (
" and the directories git runs hooks from",
"untracked elsewhere",
),
HookLook::Failed(_) => ("", "untracked"),
};
format!(
"oakum searched git's index outside `.changeset/`{searched}, so a gate that is {untracked}, an unstaged edit, inside a submodule, or a hook set in git config (`hook.<name>.command`) is not covered — check those before the first release"
)
}
fn bump_file_gate_steps(gates: &GateLook) -> Vec<String> {
let mut steps: Vec<String> = gates
.failure()
.map(|why| {
format!(
"- unverified: oakum {}; a commit or CI gate pointed at it will reject oakum's bump files",
gate_look_failed(&why)
)
})
.into_iter()
.collect();
if let GateLook::Looked { index, hooks } = gates {
steps.extend(index_step(index, hooks));
steps.extend(hooks_step(hooks));
}
steps
}
fn kept_bump_directory_step(tools: impl IntoIterator<Item = ReleaseTool>) -> Option<String> {
tools
.into_iter()
.any(|tool| matches!(tool, ReleaseTool::Changesets | ReleaseTool::Knope))
.then(|| {
String::from(
"- check any commit or CI gate that reads `.changeset/*.md`: oakum writes its own bump files there, and a gate written for the old tool's files may reject them; oakum did not look for one",
)
})
}
fn index_step(index: &IndexLook, hooks: &HookLook) -> Option<String> {
let unsearched = unsearched(hooks);
match index {
IndexLook::Failed(_) => None,
IndexLook::NothingTracked => Some(format!(
"- git reports no commit and its index lists no file, so no tracked file could have gated anything. {unsearched}"
)),
IndexLook::Found { named, unmerged } if named.is_empty() => {
let other = if unmerged.is_empty() { "" } else { " other" };
Some(format!(
"- no{other} file in the index outside `.changeset/` names the old bump-file directory. {unsearched}"
))
}
IndexLook::Found { named, .. } => 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(named)
)),
}
}
fn hooks_step(hooks: &HookLook) -> Option<String> {
match hooks {
HookLook::Failed(_) => None,
HookLook::Read {
dirs,
named,
unread,
} if named.is_empty() => {
let other = if unread.is_empty() { "" } else { " other" };
let dirs = dirs
.iter()
.map(|dir| format!("`{dir}`"))
.collect::<Vec<_>>()
.join(" or ");
Some(format!(
"- no{other} hook in {dirs} names the old bump-file directory"
))
}
HookLook::Read { named, .. } => Some(format!(
"- check the hooks git runs that name the old bump-file directory ({}); a hook matching those paths rejects the bump files oakum writes",
quoted(named)
)),
}
}
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, HookLook, IndexLook};
use super::{
bump_file_gate_steps, gate_look_refusal, hooks_step, kept_bump_directory_step, one_line,
verdict,
};
use oakum::detect::ReleaseTool;
fn index_step(index: &IndexLook) -> Option<String> {
super::index_step(index, &hooks(&[], &[]))
}
fn found(named: &[&str], unmerged: &[&str]) -> IndexLook {
IndexLook::Found {
named: named.iter().map(ToString::to_string).collect(),
unmerged: unmerged.iter().map(ToString::to_string).collect(),
}
}
fn hooks(named: &[&str], unread: &[&str]) -> HookLook {
HookLook::Read {
dirs: vec![String::from(".git/hooks")],
named: named.iter().map(ToString::to_string).collect(),
unread: unread.iter().map(ToString::to_string).collect(),
}
}
fn looked(index: IndexLook) -> GateLook {
GateLook::Looked {
index,
hooks: hooks(&[], &[]),
}
}
fn bump_file_gate_step(gates: &GateLook) -> Option<String> {
let mut steps = bump_file_gate_steps(gates);
assert!(steps.len() <= 1, "{steps:?}");
steps.pop()
}
#[test]
fn only_a_kept_bump_directory_is_noted() {
for tools in [
vec![ReleaseTool::Changesets],
vec![ReleaseTool::Knope],
vec![ReleaseTool::Bumpy, ReleaseTool::Changesets],
] {
let kept = kept_bump_directory_step(tools.clone()).expect("a kept directory speaks");
assert!(
kept.contains("`.changeset/*.md`") && kept.contains("did not look"),
"{tools:?}: {kept}"
);
}
for tools in [
vec![ReleaseTool::Bumpy],
vec![ReleaseTool::ReleasePlease],
vec![ReleaseTool::SemanticRelease],
vec![],
] {
assert_eq!(kept_bump_directory_step(tools.clone()), None, "{tools:?}");
}
}
#[test]
fn every_outcome_has_its_own_line() {
assert_eq!(bump_file_gate_step(&GateLook::NothingToRepoint), None);
let empty = index_step(&found(&[], &[])).expect("empty look speaks");
assert!(empty.contains("no file in the index"), "{empty}");
for unsearched in ["untracked", "unstaged edit", "submodule", "git config"] {
assert!(empty.contains(unsearched), "{unsearched}: {empty}");
}
assert!(
empty.contains("the directories git runs hooks from") && !empty.contains(".git/hooks/"),
"the hooks are searched, so the caveat no longer disclaims them: {empty}"
);
let nothing = index_step(&IndexLook::NothingTracked).expect("an empty index speaks");
assert!(nothing.contains("git reports no commit"), "{nothing}");
assert!(
nothing.contains("submodule"),
"every arm carries the caveat: {nothing}"
);
assert_ne!(
nothing, empty,
"searched nothing is not searched and found none"
);
let one = index_step(&found(&["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 = index_step(&found(&["hook.sh", "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}");
assert_eq!(index_step(&IndexLook::Failed(String::from("boom"))), None);
let no_hook = hooks_step(&hooks(&[], &[])).expect("an empty hook look speaks");
assert_eq!(
no_hook,
"- no hook in `.git/hooks` names the old bump-file directory"
);
let both = HookLook::Read {
dirs: vec![String::from("rel"), String::from(".git/rel")],
named: Vec::new(),
unread: Vec::new(),
};
assert_eq!(
hooks_step(&both).expect("an empty hook look speaks"),
"- no hook in `rel` or `.git/rel` names the old bump-file directory"
);
let hook = hooks_step(&hooks(&[".git/hooks/pre-commit"], &[])).expect("a hit speaks");
assert!(
hook.contains("check the hooks git runs that name the old bump-file directory (`.git/hooks/pre-commit`)"),
"{hook}"
);
assert_eq!(hooks_step(&HookLook::Failed(String::from("boom"))), None);
}
#[test]
fn an_unmerged_file_is_named_as_unsearched() {
let steps = bump_file_gate_steps(&looked(found(&[], &["gate.sh"])));
assert_eq!(steps.len(), 3, "{steps:?}");
assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
assert!(
steps[0].contains("unmerged") && steps[0].contains("`gate.sh`"),
"{steps:?}"
);
assert!(
steps[1].starts_with("- no other file in the index"),
"{steps:?}"
);
let steps = bump_file_gate_steps(&looked(found(&["hook.sh"], &["gate.sh"])));
assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
assert!(steps[1].contains("(`hook.sh`)"), "{steps:?}");
}
#[test]
fn an_unread_hook_is_unverified() {
let steps = bump_file_gate_steps(&GateLook::Looked {
index: found(&[], &[]),
hooks: hooks(&[], &["`.git/hooks/pre-push` (Permission denied)"]),
});
assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
assert!(steps[0].contains("`.git/hooks/pre-push`"), "{steps:?}");
assert_eq!(
steps.last().map(String::as_str),
Some("- no other hook in `.git/hooks` names the old bump-file directory")
);
let steps = bump_file_gate_steps(&GateLook::Looked {
index: found(&[], &[]),
hooks: HookLook::Failed(String::from("hooks gone")),
});
assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
assert!(steps[1].starts_with("- no file in the index"), "{steps:?}");
assert!(!steps[1].contains("hooks from"), "{steps:?}");
assert!(steps[1].contains("submodule"), "{steps:?}");
let both = GateLook::Looked {
index: IndexLook::Failed(String::from("index gone")),
hooks: HookLook::Failed(String::from("hooks gone")),
};
assert_eq!(
both.failure().as_deref(),
Some("index gone; hooks gone"),
"both causes, in one fact"
);
}
#[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().as_deref(),
Some("boom")
);
assert!(looked(found(&[], &["gate.sh"])).failure().is_some());
for gates in [
looked(found(&[], &[])),
looked(found(&["hook.sh"], &[])),
looked(IndexLook::NothingTracked),
GateLook::Looked {
index: found(&[], &[]),
hooks: hooks(&[".git/hooks/pre-commit"], &[]),
},
GateLook::NothingToRepoint,
] {
assert_eq!(gates.failure(), None, "{gates:?}");
}
}
}
#[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::Stale)),
"write .changeset/_config.toml, replace the earlier oakum .changeset/README.md, and leave the current .changeset/_schema.json"
);
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)"
);
}
}