use crate::engine::BranchMetadata;
use crate::git::GitRepo;
use anyhow::Result;
use colored::Colorize;
pub(crate) fn normalize_scope_parents_for_restack(
repo: &GitRepo,
scope: &[String],
quiet: bool,
) -> Result<usize> {
let trunk = repo.trunk_branch()?;
let mut normalized = 0usize;
for branch in scope {
let Some(meta) = BranchMetadata::read(repo.inner(), branch)? else {
continue;
};
if meta.parent_branch_name == trunk {
continue;
}
let parent_branch = meta.parent_branch_name.clone();
let parent_tip = repo.branch_commit(&parent_branch).ok();
let (should_reparent, reason) = if parent_tip.is_none() {
(true, "missing")
} else if repo
.is_branch_merged_equivalent_to_trunk(&parent_branch)
.unwrap_or(false)
{
(true, "merged")
} else {
(false, "")
};
if !should_reparent {
continue;
}
let old_parent_boundary = parent_tip.unwrap_or_else(|| meta.parent_branch_revision.clone());
let updated_meta = BranchMetadata {
parent_branch_name: trunk.clone(),
parent_branch_revision: old_parent_boundary,
..meta
};
updated_meta.write(repo.inner(), branch)?;
normalized += 1;
if !quiet {
let reason_text = if reason == "missing" {
"parent missing"
} else {
"parent merged into trunk"
};
println!(
" {} normalized {} → {} ({})",
"↪".cyan(),
branch.cyan(),
trunk.cyan(),
reason_text.dimmed()
);
}
}
Ok(normalized)
}