use super::{
BlobContent, ConflictKind, ConflictPicks, ConflictSide, MergeDocument, MergeRegion,
WorktreeFileState,
};
fn squeezed(lines: &[String]) -> Vec<String> {
lines
.iter()
.map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::<String>())
.filter(|l| !l.is_empty())
.collect()
}
pub fn is_whitespace_only(ours: &[String], theirs: &[String]) -> bool {
ours != theirs && squeezed(ours) == squeezed(theirs)
}
pub fn whitespace_choice(
base: &[String],
ours: &[String],
theirs: &[String],
) -> Option<ConflictSide> {
if !is_whitespace_only(ours, theirs) {
return None;
}
if !base.is_empty() && base == ours {
return Some(ConflictSide::Theirs);
}
if !base.is_empty() && base == theirs {
return Some(ConflictSide::Ours);
}
let trailing_only = ours.len() == theirs.len()
&& ours
.iter()
.zip(theirs)
.all(|(a, b)| a.trim_end() == b.trim_end());
trailing_only.then_some(ConflictSide::Ours)
}
pub fn whitespace_resolution(doc: &MergeDocument) -> Option<Vec<ConflictPicks>> {
if !matches!(
doc.entry.kind,
ConflictKind::BothModified | ConflictKind::BothAdded
) || doc.entry.mode_changed()
|| doc.entry.is_symlink()
|| doc.entry.is_submodule()
|| doc.worktree != WorktreeFileState::Markers
|| doc.conflict_count() == 0
{
return None;
}
let text = |b: &Option<super::SideBlob>| {
b.as_ref()
.is_none_or(|b| matches!(b.content, BlobContent::Text { .. }))
};
if !(text(&doc.base) && text(&doc.ours) && text(&doc.theirs)) {
return None;
}
let mut picks = Vec::new();
for region in &doc.regions {
if let MergeRegion::Conflict { base, ours, theirs } = region {
let side = whitespace_choice(base, ours, theirs)?;
picks.push(ConflictPicks::take(region, &[side]));
}
}
Some(picks)
}