use std::num::NonZeroU8;
use std::path::Path;
use std::sync::atomic::AtomicBool;
use gix::bstr::{BString, ByteSlice};
use gix::filter::plumbing::pipeline::convert::ToWorktreeOutcome;
use gix::objs::tree::EntryKind;
use crate::applied::capture::{self, CaptureInputs};
use crate::applied::project::Project;
use crate::applied::record::{Application, Origin, RepoPath, Revision};
#[allow(clippy::large_enum_variant)]
pub enum Base {
Application(Application),
Empty,
}
#[derive(Debug, Default, Clone, Copy)]
pub struct MergeOptions {
pub trusted: bool,
pub dry_run: bool,
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Merged {
AlreadyCurrent,
NeedsTrust,
Planned {
changes: Vec<Change>,
},
Written {
record: String,
changes: Vec<Change>,
conflicted: Vec<RepoPath>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Change {
pub path: RepoPath,
pub action: Action,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
Added,
Updated,
Merged,
Deleted,
Conflicted(ConflictKind),
NotPreviewed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictKind {
Content,
AddAdd,
ModifyDelete,
FileDirectory,
Binary,
Driver,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MergeError {
#[error("the update was prepared for another target")]
WrongTarget,
#[error("git error during merge: {0}")]
Git(String),
#[error("git error during merge: apply: {0}")]
Apply(Box<crate::ApplyError>),
#[error("a path the update would write is occupied: {0:?}")]
Occupied(Vec<RepoPath>),
#[error("the target or index changed during the update")]
Changed,
#[error("{0}")]
Io(String),
}
fn git(err: impl std::fmt::Display) -> MergeError {
MergeError::Git(err.to_string())
}
pub struct RecordInputs {
pub template: String,
pub revision: Revision,
}
#[allow(clippy::too_many_arguments)]
pub fn merge_apply(
project: &Project,
base: Base,
template: &crate::template::Template,
completed: &crate::interview::Completed,
inputs: RecordInputs,
options: MergeOptions,
runner: &dyn crate::hook::HookRunner,
) -> Result<Merged, MergeError> {
merge_apply_reported(project, base, template, completed, inputs, options, runner)
.map(|(merged, _)| merged)
}
#[derive(Debug, Default)]
pub struct UpdateReport {
pub messages: Vec<String>,
pub hooks: Vec<crate::apply::HookReport>,
}
#[allow(clippy::too_many_arguments)]
pub fn merge_apply_reported(
project: &Project,
base: Base,
template: &crate::template::Template,
completed: &crate::interview::Completed,
inputs: RecordInputs,
options: MergeOptions,
runner: &dyn crate::hook::HookRunner,
) -> Result<(Merged, UpdateReport), MergeError> {
merge_apply_reported_with_force(
project, base, template, completed, inputs, options, false, runner,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn merge_apply_reported_with_force(
project: &Project,
base: Base,
template: &crate::template::Template,
completed: &crate::interview::Completed,
inputs: RecordInputs,
options: MergeOptions,
force: bool,
runner: &dyn crate::hook::HookRunner,
) -> Result<(Merged, UpdateReport), MergeError> {
let target_path = candidate_target(project)?;
let mut plan = crate::plan::Plan::build(template, completed, &target_path)
.map_err(|err| MergeError::Git(err.to_string()))?;
let mut report = UpdateReport {
messages: completed.messages.clone(),
hooks: vec![],
};
if let Some(before) = &plan.before_apply {
report.messages.push(before.clone());
}
if !options.trusted && !plan.hooks.is_empty() {
return Ok((Merged::NeedsTrust, report));
}
plan.record_identity(inputs.template.clone(), inputs.revision.clone());
let capture_inputs = plan
.record
.take()
.expect("a completed plan has record inputs");
let directories = plan.directories.clone();
let missing_directories: Vec<_> = directories
.iter()
.filter(|path| !target_path.as_path().join(path.as_path()).is_dir())
.cloned()
.collect();
let (new, candidate_report) = build_candidate_reported(
project,
&base,
plan,
capture_inputs,
!options.dry_run,
force,
runner,
)?;
report.messages.extend(candidate_report.messages);
report.hooks = candidate_report.hooks;
if missing_directories.is_empty()
&& let Base::Application(base_application) = &base
&& is_already_current(project, base_application, &new, &inputs)?
{
return Ok((Merged::AlreadyCurrent, report));
}
crate::plan::check_directories(&directories, &target_path).map_err(MergeError::Io)?;
let mut merged = merge_inner(project, &base, &new, &options, &directories)?;
if let Merged::Planned { changes } | Merged::Written { changes, .. } = &mut merged {
for directory in &missing_directories {
changes.push(Change {
path: repo_path_for(project.target(), &BString::from(directory.to_string())),
action: Action::Added,
});
}
}
Ok((merged, report))
}
fn candidate_target(project: &Project) -> Result<crate::staging::CanonicalTarget, MergeError> {
let repo = project.repo();
let workdir = repo
.workdir()
.ok_or_else(|| MergeError::Io("bare".into()))?;
let path = if project.target().is_root() {
workdir.to_owned()
} else {
workdir.join(project.target().as_str())
};
crate::staging::canonical_target(&path).map_err(|err| MergeError::Io(err.to_string()))
}
#[cfg(test)]
fn build_candidate(
project: &Project,
base: &Base,
plan: crate::plan::Plan,
inputs: CaptureInputs,
run_hooks: bool,
runner: &dyn crate::hook::HookRunner,
) -> Result<Application, MergeError> {
build_candidate_reported(project, base, plan, inputs, run_hooks, false, runner)
.map(|(application, _)| application)
}
fn build_candidate_reported(
project: &Project,
base: &Base,
plan: crate::plan::Plan,
inputs: CaptureInputs,
run_hooks: bool,
force: bool,
runner: &dyn crate::hook::HookRunner,
) -> Result<(Application, UpdateReport), MergeError> {
let mut report = UpdateReport::default();
let repo = project.repo();
let target = project.target().clone();
let checkout = tempfile::tempdir().map_err(|e| MergeError::Io(e.to_string()))?;
checkout_head(repo, checkout.path())?;
let checkout_target_path = if target.is_root() {
checkout.path().to_owned()
} else {
checkout.path().join(target.as_str())
};
let checkout_target = crate::staging::canonical_target(&checkout_target_path)
.map_err(|e| MergeError::Io(e.to_string()))?;
let base_application = match base {
Base::Application(application) => Some(application),
Base::Empty => None,
};
if let Some(base_application) = base_application {
plan.preflight_owned_regions(&checkout_target, base_application, force)
.map_err(|e| MergeError::Apply(Box::new(e)))?;
}
let plan_paths = capture::group_plan(&plan);
if let Some(base_application) = base_application {
capture::retract_uncovered(checkout.path(), &target, &plan_paths, base_application)
.map_err(|e| MergeError::Git(e.to_string()))?;
}
let mut plan = plan;
if !run_hooks {
plan.hooks.clear();
}
plan.git = None;
plan.record = None;
plan.preflight_edits(&checkout_target, force)
.map_err(|e| MergeError::Apply(Box::new(e)))?;
if let Some(base_application) = base_application {
plan.preflight_takeovers(&checkout_target, base_application, force)
.map_err(|e| MergeError::Apply(Box::new(e)))?;
}
let before = capture::observe(checkout_target.as_path()).map_err(git)?;
match plan
.apply(
&checkout_target,
crate::apply::ApplyOptions {
force: true,
trusted: true,
},
runner,
)
.map_err(|e| MergeError::Apply(Box::new(e)))?
{
crate::apply::Applied::Written {
hooks, after_apply, ..
} => {
report.hooks = hooks;
if run_hooks {
report.messages.extend(after_apply);
}
}
crate::apply::Applied::NeedsTrust(_) => {
return Err(MergeError::Git(
"internal: a candidate build reached an untrusted-hooks refusal \
after trust was already established"
.to_owned(),
));
}
}
let application = capture::capture(
repo,
checkout.path(),
&target,
&plan_paths,
base_application,
inputs,
Some(&before),
)
.map_err(|e| MergeError::Git(e.to_string()))?;
Ok((application, report))
}
fn is_already_current(
project: &Project,
base: &Application,
new: &Application,
inputs: &RecordInputs,
) -> Result<bool, MergeError> {
if base.revision() != &inputs.revision
|| base.answers != new.answers
|| base.parts != new.parts
|| base.context != new.context
{
return Ok(false);
}
if base.files == new.files {
return Ok(true);
}
Ok(normalized_files(project, base)? == normalized_files(project, new)?)
}
fn normalized_files(project: &Project, application: &Application) -> Result<Entries, MergeError> {
use gix::filter::plumbing::pipeline::convert::ToGitOutcome;
let repo = project.repo();
let (mut pipeline, _) = super::project::worktree_filter_pipeline(repo).map_err(git)?;
let (comparison, _) = super::project::worktree_filter_pipeline(repo).map_err(git)?;
let (mut comparison, mut attributes) = comparison.into_parts();
comparison.options_mut().crlf_roundtrip_check =
gix::filter::plumbing::pipeline::CrlfRoundTripCheck::Skip;
let mut entries = Entries::new();
for (path, (id, kind)) in &application.files {
let mode = gix::index::entry::Mode::from(*kind);
let id = if *kind == EntryKind::Link {
*id
} else {
let relative = repo_path_for(project.target(), &BString::from(path.as_str()));
let bytes = worktree_bytes(repo, &mut pipeline, *id, relative.as_str(), mode)?;
let entry = attributes
.at_path(Path::new(relative.as_str()), None, &repo.objects)
.map_err(git)?;
let converted = comparison
.convert_to_git(
bytes.as_slice(),
Path::new(relative.as_str()),
&mut |_, attrs| {
entry.matching_attributes(attrs);
},
&mut |_| Ok(None),
)
.map_err(git)?;
match converted {
ToGitOutcome::Unchanged(bytes) | ToGitOutcome::Buffer(bytes) => {
gix::objs::compute_hash(repo.object_hash(), gix::objs::Kind::Blob, bytes)
}
ToGitOutcome::Process(_) => {
return Err(MergeError::Git(
"unexpected process filter after driver strip".into(),
));
}
}
.map_err(git)?
};
entries.insert(BString::from(path.as_str()), (id, mode));
}
Ok(entries)
}
pub(super) fn checkout_head(repo: &gix::Repository, dest: &Path) -> Result<(), MergeError> {
let tree_id = repo.head_tree_id().map_err(git)?;
let mut index = repo.index_from_tree(&tree_id).map_err(git)?;
let mut opts = repo
.checkout_options(gix::worktree::stack::state::attributes::Source::IdMapping)
.map_err(git)?;
opts.destination_is_initially_empty = true;
std::fs::create_dir_all(dest).map_err(|e| MergeError::Io(e.to_string()))?;
gix::worktree::state::checkout(
&mut index,
dest,
repo.objects.clone().into_arc().map_err(git)?,
&gix::progress::Discard,
&gix::progress::Discard,
&AtomicBool::new(false),
opts,
)
.map_err(git)?;
Ok(())
}
#[cfg(test)]
pub(crate) fn merge_into_worktree(
project: &Project,
base: &Base,
new: &Application,
options: &MergeOptions,
) -> Result<Merged, MergeError> {
merge_inner(project, base, new, options, &[])
}
fn merge_inner(
project: &Project,
base: &Base,
new: &Application,
options: &MergeOptions,
directories: &[crate::TargetPath],
) -> Result<Merged, MergeError> {
let repo = project.repo();
let target = project.target();
let head_start = repo.head_id().map_err(git)?.detach();
let index_digest_start = index_digest(repo);
let head_tree = repo.head_tree().map_err(git)?.id().detach();
let base_files = match base {
Base::Application(application) => {
let files = application_files_tree(project, application)?;
let mut editor = repo.edit_tree(files).map_err(git)?;
for entry in application.paths() {
if matches!(entry.origin(), Origin::Edit { regions, values } if regions.is_empty() && values.is_empty())
&& !new
.paths()
.iter()
.any(|candidate| candidate.path() == entry.path())
{
editor
.remove(entry.path().to_string().as_str())
.map_err(git)?;
}
}
editor.write().map_err(git)?.detach()
}
Base::Empty => repo
.write_object(gix::objs::Tree::empty())
.map_err(git)?
.detach(),
};
let new_files = application_files_tree(project, new)?;
let base_full = graft(project, head_tree, target, base_files)?;
let theirs_full = graft(project, head_tree, target, new_files)?;
let ours_full = head_tree;
let mut opts: gix::merge::plumbing::tree::Options =
repo.tree_merge_options().map_err(git)?.into();
opts.rewrites = None;
opts.blob_merge.text.conflict = gix::merge::blob::builtin_driver::text::Conflict::Keep {
style: gix::merge::blob::builtin_driver::text::ConflictStyle::Diff3,
marker_size: NonZeroU8::new(7).expect("nonzero"),
};
let labels = gix::merge::blob::builtin_driver::text::Labels {
ancestor: Some("toha (old template)".into()),
current: Some("operator".into()),
other: Some("toha (new template)".into()),
};
let mut merge_repo = repo.clone();
let mut config = merge_repo.config_snapshot_mut();
config
.set_raw_value("merge.renormalize", "true")
.map_err(git)?;
config.commit().map_err(git)?;
let mut blob_merge = merge_repo
.merge_resource_cache(Default::default())
.map_err(git)?;
blob_merge.filter.filter.options_mut().crlf_roundtrip_check =
gix::filter::plumbing::pipeline::CrlfRoundTripCheck::Skip;
let mut diff_cache = merge_repo
.diff_resource_cache_for_tree_diff()
.map_err(git)?;
let mut outcome = gix::merge::plumbing::tree(
base_full.as_ref(),
ours_full.as_ref(),
theirs_full.as_ref(),
labels,
&merge_repo,
|buf| merge_repo.write_blob(buf).map(|id| id.detach()),
&mut Default::default(),
&mut diff_cache,
&mut blob_merge,
opts,
)
.map_err(git)?;
let how = gix::merge::tree::TreatAsUnresolved::git();
let merged_full = outcome.tree.write(|tree| {
use gix::objs::WriteTo;
let mut data = Vec::new();
tree.write_to(&mut data).map_err(git)?;
let id = gix::objs::compute_hash(merge_repo.object_hash(), gix::objs::Kind::Tree, &data)
.map_err(git)?;
gix::Tree::from_data(id, data, &merge_repo)
.edit()
.map_err(git)?
.write()
.map(|id| id.detach())
.map_err(git)
})?;
let mut outcome = gix::merge::tree::Outcome {
tree: merge_repo.edit_tree(merged_full).map_err(git)?,
conflicts: outcome.conflicts,
failed_on_first_unresolved_conflict: outcome.failed_on_first_unresolved_conflict,
};
let theirs_sub = subtree(project, theirs_full, target)?;
let merged_sub = subtree(project, merged_full, target)?;
let ours_sub = subtree(project, ours_full, target)?;
let ours_entries = flat_entries(project, ours_sub)?;
let merged_entries = flat_entries(project, merged_sub)?;
let theirs_entries = flat_entries(project, theirs_sub)?;
let base_sub = subtree(project, base_full, target)?;
let base_entries = flat_entries(project, base_sub)?;
let mut conflict_kinds: std::collections::BTreeMap<String, ConflictKind> =
std::collections::BTreeMap::new();
for c in outcome.conflicts.iter().filter(|c| c.is_unresolved(how)) {
let location = c.ours.location().to_str_lossy().into_owned();
conflict_kinds.insert(location, classify_conflict(repo, c));
}
let mut driver_stages: DriverStages = std::collections::BTreeMap::new();
for path in driver_attributed_paths(repo, target, &base_entries, &theirs_entries)? {
let repo_rel = repo_path_for(target, &path).as_str().to_owned();
conflict_kinds.insert(repo_rel.clone(), ConflictKind::Driver);
driver_stages.insert(
repo_rel,
[
base_entries.get(&path).copied(),
ours_entries.get(&path).copied(),
theirs_entries.get(&path).copied(),
],
);
}
if let Base::Application(application) = base {
for owned in application.paths() {
let path = owned.path().to_string();
if !matches!(owned.origin(), Origin::Edit { .. })
&& !application.files.contains_key(&path)
&& !theirs_entries.contains_key(path.as_bytes())
&& let Some(ours) = ours_entries.get(path.as_bytes())
{
let relative = repo_path_for(target, &BString::from(path.as_str())).to_string();
conflict_kinds.insert(relative.clone(), ConflictKind::ModifyDelete);
driver_stages.insert(relative, [None, Some(*ours), None]);
}
}
}
let conflicted: Vec<RepoPath> = conflict_kinds
.keys()
.filter_map(|p| RepoPath::parse(p).ok())
.collect();
let mut changes = Vec::new();
for (path, (id, mode)) in &merged_entries {
let repo_path = repo_path_for(target, path);
let action = if let Some(kind) = conflict_kinds.get(repo_path.as_str()) {
Action::Conflicted(*kind)
} else if let Some((ours_id, _)) = ours_entries.get(path) {
if ours_id == id {
continue; } else if theirs_entries.contains_key(path) {
Action::Merged
} else {
Action::Updated
}
} else {
Action::Added
};
let _ = mode;
changes.push(Change {
path: repo_path,
action,
});
}
for path in ours_entries.keys() {
if !merged_entries.contains_key(path) {
let repo_path = repo_path_for(target, path);
let action = match conflict_kinds.get(repo_path.as_str()) {
Some(kind) => Action::Conflicted(*kind),
None => Action::Deleted,
};
changes.push(Change {
path: repo_path,
action,
});
}
}
for (path, kind) in &conflict_kinds {
if !changes.iter().any(|c| c.path.as_str() == path) {
changes.push(Change {
path: RepoPath::parse(path).map_err(git)?,
action: Action::Conflicted(*kind),
});
}
}
changes.sort_by(|a, b| a.path.as_str().cmp(b.path.as_str()));
if options.dry_run {
return Ok(Merged::Planned { changes });
}
let workdir = repo
.workdir()
.ok_or_else(|| MergeError::Io("bare".into()))?;
let mut occupied = Vec::new();
for path in merged_entries.keys() {
if !ours_entries.contains_key(path) {
let repo_path = repo_path_for(target, path);
let on_disk = workdir.join(repo_path.as_str());
if on_disk.symlink_metadata().is_ok() {
occupied.push(repo_path);
}
}
}
if !occupied.is_empty() {
return Err(MergeError::Occupied(occupied));
}
let keep_operator: std::collections::BTreeSet<String> = conflict_kinds
.iter()
.filter(|(path, kind)| {
!matches!(kind, ConflictKind::Content)
|| outcome.conflicts.iter().any(|conflict| {
conflict.is_unresolved(how)
&& conflict.ours.location().as_bstr() == path.as_bytes().as_bstr()
&& conflict
.entries()
.iter()
.flatten()
.any(|entry| entry.mode.is_link())
})
})
.map(|(path, _)| path.clone())
.collect();
commit_transaction(
project,
&ours_entries,
&merged_entries,
target,
&keep_operator,
&driver_stages,
&mut outcome,
merged_full,
how,
head_start,
index_digest_start,
new,
directories,
)?;
Ok(Merged::Written {
record: project.record_relative().map_err(git)?,
changes,
conflicted,
})
}
fn index_digest(repo: &gix::Repository) -> Option<Vec<u8>> {
let path = repo.git_dir().join("index");
std::fs::read(path).ok().map(|bytes| {
use sha2::{Digest, Sha256};
Sha256::digest(&bytes).to_vec()
})
}
struct Restorable {
repo_rel: String,
head: Option<(gix::ObjectId, gix::index::entry::Mode)>,
wrote: Option<gix::ObjectId>,
}
#[allow(clippy::too_many_arguments)]
fn commit_transaction(
project: &Project,
ours: &Entries,
merged: &Entries,
target: &RepoPath,
keep_operator: &std::collections::BTreeSet<String>,
driver_stages: &DriverStages,
outcome: &mut gix::merge::tree::Outcome<'_>,
merged_full: gix::ObjectId,
how: gix::merge::tree::TreatAsUnresolved,
head_start: gix::ObjectId,
index_digest_start: Option<Vec<u8>>,
application: &Application,
directories: &[crate::TargetPath],
) -> Result<(), MergeError> {
let repo = project.repo();
let workdir = repo
.workdir()
.ok_or_else(|| MergeError::Io("bare".into()))?
.to_owned();
let index_path = repo.git_dir().join("index");
let lock = gix::lock::File::acquire_to_update_resource(
&index_path,
gix::lock::acquire::Fail::Immediately,
None,
)
.map_err(|err| MergeError::Io(err.to_string()))?;
if repo.head_id().map_err(git)?.detach() != head_start
|| index_digest(repo) != index_digest_start
|| project.ensure_record_clean().is_err()
|| !matches!(
project.cleanliness(),
Ok(crate::applied::Cleanliness::Clean)
)
{
return Err(MergeError::Changed);
}
let (mut pipeline, index) = super::project::worktree_filter_pipeline(repo).map_err(git)?;
let state: &gix::index::State = &index;
let target_path = candidate_target(project)?;
crate::plan::check_directories(directories, &target_path).map_err(MergeError::Io)?;
let mut created = CreatedDirectories::default();
for directory in directories {
let path = repo_path_for(target, &BString::from(directory.to_string()));
let path = crate::TargetPath::parse(path.as_str()).map_err(MergeError::Io)?;
created.create(&workdir, &path)?;
}
let mut done: Vec<Restorable> = Vec::new();
let result = write_all(
repo,
&mut pipeline,
state,
&workdir,
ours,
merged,
target,
keep_operator,
&mut done,
);
if let Err(err) = result {
rollback(repo, &mut pipeline, state, &workdir, &done)?;
return Err(err);
}
let record_path = project.record_path().map_err(git)?;
let previous_record = std::fs::read(&record_path).ok();
if let Err(error) = project.write_application(application.clone()) {
rollback(repo, &mut pipeline, state, &workdir, &done)?;
return Err(git(error));
}
if let Err(err) = write_index(
project,
outcome,
merged_full,
target,
driver_stages,
how,
lock,
) {
match previous_record {
Some(bytes) => {
std::fs::write(&record_path, bytes).map_err(|e| MergeError::Io(e.to_string()))?;
}
None => {
std::fs::remove_file(&record_path).map_err(|e| MergeError::Io(e.to_string()))?;
}
}
rollback(repo, &mut pipeline, state, &workdir, &done)?;
return Err(err);
}
created.0.clear();
Ok(())
}
#[derive(Default)]
struct CreatedDirectories(Vec<std::path::PathBuf>);
impl CreatedDirectories {
fn create(&mut self, root: &Path, directory: &crate::TargetPath) -> Result<(), MergeError> {
let mut path = root.to_owned();
for component in directory.as_path().components() {
path.push(component);
match std::fs::create_dir(&path) {
Ok(()) => self.0.push(path.clone()),
Err(error)
if error.kind() == std::io::ErrorKind::AlreadyExists
&& path.symlink_metadata().is_ok_and(|meta| meta.is_dir()) => {}
Err(error) => return Err(MergeError::Io(error.to_string())),
}
}
Ok(())
}
}
impl Drop for CreatedDirectories {
fn drop(&mut self) {
for path in self.0.iter().rev() {
let _ = std::fs::remove_dir(path);
}
}
}
#[allow(clippy::too_many_arguments)]
fn write_all(
repo: &gix::Repository,
pipeline: &mut gix::filter::Pipeline<'_>,
state: &gix::index::State,
workdir: &Path,
ours: &Entries,
merged: &Entries,
target: &RepoPath,
keep_operator: &std::collections::BTreeSet<String>,
done: &mut Vec<Restorable>,
) -> Result<(), MergeError> {
for (path, (id, mode)) in merged {
let expected = ours.get(path);
if expected == Some(&(*id, *mode)) {
continue; }
let repo_rel = repo_path_for(target, path).as_str().to_owned();
if keep_operator.contains(&repo_rel) || ancestor_kept(&repo_rel, keep_operator) {
continue;
}
drift_check(pipeline, state, &repo_rel, expected.map(|(o, _)| *o))?;
let bytes = worktree_bytes(repo, pipeline, *id, &repo_rel, *mode)?;
write_atomically(workdir, &repo_rel, &bytes, *mode)?;
done.push(Restorable {
repo_rel,
head: expected.copied(),
wrote: Some(*id),
});
#[cfg(test)]
inject_fail::check(done, workdir)?;
}
for (path, (id, _)) in ours {
if merged.contains_key(path) {
continue;
}
let repo_rel = repo_path_for(target, path).as_str().to_owned();
if keep_operator.contains(&repo_rel) {
continue; }
drift_check(pipeline, state, &repo_rel, Some(*id))?;
let full = workdir.join(&repo_rel);
if full.symlink_metadata().is_ok() {
std::fs::remove_file(&full).map_err(|e| MergeError::Io(e.to_string()))?;
}
done.push(Restorable {
repo_rel,
head: ours.get(path).copied(),
wrote: None,
});
#[cfg(test)]
inject_fail::check(done, workdir)?;
}
Ok(())
}
#[cfg(test)]
mod inject_fail {
use super::{MergeError, Restorable};
use std::cell::{Cell, RefCell};
use std::path::Path;
thread_local! {
static AFTER: Cell<Option<usize>> = const { Cell::new(None) };
static COUNT: Cell<usize> = const { Cell::new(0) };
static OBSERVED: RefCell<Vec<(String, Option<Vec<u8>>)>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn arm(after: usize) {
AFTER.with(|a| a.set(Some(after)));
COUNT.with(|c| c.set(0));
OBSERVED.with(|o| o.borrow_mut().clear());
}
pub(super) fn disarm() {
AFTER.with(|a| a.set(None));
}
pub(super) fn observed() -> Vec<(String, Option<Vec<u8>>)> {
OBSERVED.with(|o| o.borrow().clone())
}
pub(super) fn check(done: &[Restorable], workdir: &Path) -> Result<(), MergeError> {
let n = COUNT.with(|c| {
let v = c.get() + 1;
c.set(v);
v
});
if AFTER.with(|a| a.get()) == Some(n) {
let snap: Vec<_> = done
.iter()
.map(|r| {
(r.repo_rel.clone(), {
let full = workdir.join(&r.repo_rel);
if full.symlink_metadata().is_ok_and(|md| md.is_symlink()) {
std::fs::read_link(&full)
.ok()
.map(|target| gix::path::into_bstr(target).to_vec())
} else {
std::fs::read(full).ok()
}
})
})
.collect();
OBSERVED.with(|o| *o.borrow_mut() = snap);
return Err(MergeError::Io(
"injected transaction failure after push".into(),
));
}
Ok(())
}
}
fn drift_check(
pipeline: &mut gix::filter::Pipeline<'_>,
state: &gix::index::State,
repo_rel: &str,
expected: Option<gix::ObjectId>,
) -> Result<(), MergeError> {
let current = pipeline
.worktree_file_to_object(gix::bstr::BStr::new(repo_rel.as_bytes()), state)
.map_err(git)?
.map(|(oid, _, _)| oid);
if current != expected {
return Err(MergeError::Changed);
}
Ok(())
}
fn worktree_bytes(
repo: &gix::Repository,
pipeline: &mut gix::filter::Pipeline<'_>,
id: gix::ObjectId,
repo_rel: &str,
mode: gix::index::entry::Mode,
) -> Result<Vec<u8>, MergeError> {
let data = repo.find_object(id).map_err(git)?.data.clone();
if mode == gix::index::entry::Mode::SYMLINK {
return Ok(data); }
let outcome = pipeline
.convert_to_worktree(
&data,
gix::bstr::BStr::new(repo_rel.as_bytes()),
Default::default(),
)
.map_err(git)?;
Ok(match outcome {
ToWorktreeOutcome::Unchanged(bytes) => bytes.to_vec(),
ToWorktreeOutcome::Buffer(bytes) => bytes.to_vec(),
ToWorktreeOutcome::Process(_) => {
return Err(MergeError::Git(
"unexpected process filter after driver strip".into(),
));
}
})
}
fn write_atomically(
workdir: &Path,
repo_rel: &str,
bytes: &[u8],
mode: gix::index::entry::Mode,
) -> Result<(), MergeError> {
let full = workdir.join(repo_rel);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(|e| MergeError::Io(e.to_string()))?;
}
if mode == gix::index::entry::Mode::SYMLINK {
let temporary = tempfile::Builder::new()
.prefix(".toha-")
.tempdir_in(full.parent().expect("a worktree path has a parent"))
.map_err(|e| MergeError::Io(e.to_string()))?;
let link = temporary.path().join("link");
let target = gix::path::from_bstr(gix::bstr::BStr::new(bytes));
#[cfg(not(windows))]
gix::fs::symlink::create(target.as_ref(), &link)
.map_err(|e| MergeError::Io(e.to_string()))?;
#[cfg(windows)]
{
let result = if full.parent().expect("parent").join(&target).is_dir() {
std::os::windows::fs::symlink_dir(&target, &link)
} else {
std::os::windows::fs::symlink_file(&target, &link)
};
result.map_err(|e| MergeError::Io(e.to_string()))?;
}
std::fs::rename(&link, &full).map_err(|e| MergeError::Io(e.to_string()))?;
return Ok(());
}
let mut builder = tempfile::Builder::new();
builder.prefix(".toha-");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
builder.permissions(std::fs::Permissions::from_mode(0o666));
}
let mut tmp = builder
.tempfile_in(full.parent().expect("a worktree path has a parent"))
.map_err(|e| MergeError::Io(e.to_string()))?;
use std::io::Write;
tmp.write_all(bytes)
.map_err(|e| MergeError::Io(e.to_string()))?;
#[cfg(unix)]
if mode == gix::index::entry::Mode::FILE_EXECUTABLE {
use std::os::unix::fs::PermissionsExt;
tmp.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o755))
.map_err(|e| MergeError::Io(e.to_string()))?;
}
tmp.persist(&full)
.map_err(|e| MergeError::Io(e.to_string()))?;
Ok(())
}
fn rollback(
repo: &gix::Repository,
pipeline: &mut gix::filter::Pipeline<'_>,
state: &gix::index::State,
workdir: &Path,
done: &[Restorable],
) -> Result<(), MergeError> {
let mut stuck = Vec::new();
for entry in done.iter().rev() {
let current = pipeline
.worktree_file_to_object(gix::bstr::BStr::new(entry.repo_rel.as_bytes()), state)
.map_err(git)?
.map(|(oid, _, _)| oid);
if current != entry.wrote {
stuck.push(entry.repo_rel.clone());
continue;
}
match entry.head {
Some((oid, mode)) => {
let bytes = worktree_bytes(repo, pipeline, oid, &entry.repo_rel, mode)?;
write_atomically(workdir, &entry.repo_rel, &bytes, mode)?;
}
None => {
let full = workdir.join(&entry.repo_rel);
if full.symlink_metadata().is_ok() {
std::fs::remove_file(&full).map_err(|e| MergeError::Io(e.to_string()))?;
}
}
}
}
if stuck.is_empty() {
Ok(())
} else {
Err(MergeError::Io(format!(
"rollback left paths changed by another program: {stuck:?}; recover with `git restore --source=HEAD --staged --worktree -- <target>` and `git clean -d --force -- <target>`"
)))
}
}
#[allow(clippy::too_many_arguments)]
fn write_index(
project: &Project,
outcome: &mut gix::merge::tree::Outcome<'_>,
merged_full: gix::ObjectId,
target: &RepoPath,
driver_stages: &DriverStages,
how: gix::merge::tree::TreatAsUnresolved,
mut lock: gix::lock::File,
) -> Result<(), MergeError> {
let repo = project.repo();
let mut index = repo.open_index().map_err(git)?;
let prefix = if target.is_root() {
String::new()
} else {
format!("{}/", target.as_str())
};
if prefix.is_empty() {
index.remove_entries(|_, _, _| true);
} else {
index.remove_entries(|_, path, _| path.starts_with(prefix.as_bytes()));
}
let merged_sub = subtree(project, merged_full, target)?;
let merged_entries = flat_entries(project, merged_sub)?;
let workdir = repo
.workdir()
.ok_or_else(|| MergeError::Io("bare".into()))?
.to_owned();
for (path, (id, mode)) in &merged_entries {
let repo_path = repo_path_for(target, path);
let full: BString = repo_path.as_str().into();
let stat = gix::index::fs::Metadata::from_path_no_follow(&workdir.join(repo_path.as_str()))
.ok()
.and_then(|md| gix::index::entry::Stat::from_fs(&md).ok())
.unwrap_or_default();
index.dangerously_push_entry(
stat,
*id,
gix::index::entry::Flags::empty(),
*mode,
full.as_bstr(),
);
}
index.sort_entries();
index.remove_tree();
index.remove_resolve_undo();
outcome.index_changed_after_applying_conflicts(
&mut index,
how,
gix::merge::tree::apply_index_entries::RemovalMode::Prune,
);
for (repo_rel, stages) in driver_stages {
let full: BString = repo_rel.as_str().into();
index.remove_entries(|_, path, _| path == full.as_slice());
for (i, entry) in stages.iter().enumerate() {
if let Some((oid, mode)) = entry {
let stage = match i {
0 => gix::index::entry::Stage::Base,
1 => gix::index::entry::Stage::Ours,
_ => gix::index::entry::Stage::Theirs,
};
index.dangerously_push_entry(
Default::default(),
*oid,
gix::index::entry::Flags::from_stage(stage),
*mode,
full.as_bstr(),
);
}
}
}
let relative = project.record_relative().map_err(git)?;
let record = std::fs::read(project.record_path().map_err(git)?)
.map_err(|e| MergeError::Io(e.to_string()))?;
let oid = repo.write_blob(&record).map_err(git)?.detach();
index.remove_entries(|_, path, _| path == relative.as_bytes());
index.dangerously_push_entry(
Default::default(),
oid,
gix::index::entry::Flags::empty(),
gix::index::entry::Mode::FILE,
gix::bstr::BStr::new(relative.as_bytes()),
);
index.sort_entries();
lock.with_mut(|file| {
index
.write_to(file, Default::default())
.map(|_| ())
.map_err(std::io::Error::other)
})
.map_err(|e| MergeError::Io(e.to_string()))?;
lock.commit().map_err(|e| MergeError::Io(e.to_string()))?;
Ok(())
}
type Entries = std::collections::BTreeMap<BString, (gix::ObjectId, gix::index::entry::Mode)>;
type DriverStages =
std::collections::BTreeMap<String, [Option<(gix::ObjectId, gix::index::entry::Mode)>; 3]>;
fn driver_attributed_paths(
repo: &gix::Repository,
target: &RepoPath,
base_entries: &Entries,
theirs_entries: &Entries,
) -> Result<Vec<BString>, MergeError> {
let index = repo.index_or_empty().map_err(git)?;
let mut stack = repo
.attributes_only(
&index,
gix::worktree::stack::state::attributes::Source::WorktreeThenIdMapping,
)
.map_err(git)?;
let mut out = gix::attrs::search::Outcome::default();
out.initialize_with_selection(&Default::default(), ["merge", "filter"]);
let mut paths = Vec::new();
for (path, theirs) in theirs_entries {
if base_entries.get(path) == Some(theirs) {
continue; }
let repo_rel = repo_path_for(target, path);
out.reset();
let platform = stack
.at_entry(repo_rel.as_str(), Some(gix::index::entry::Mode::FILE))
.map_err(|e| MergeError::Io(e.to_string()))?;
platform.matching_attributes(&mut out);
if is_driver_attributed(&out) {
paths.push(path.clone());
}
}
Ok(paths)
}
fn is_driver_attributed(out: &gix::attrs::search::Outcome) -> bool {
use gix::attrs::StateRef;
let mut selected = out.iter_selected();
let merge = selected.next();
let filter = selected.next();
let merge_driver = merge.is_some_and(|m| match m.assignment.state {
StateRef::Value(v) => !matches!(
v.as_bstr().to_str_lossy().as_ref(),
"text" | "binary" | "union"
),
_ => false,
});
let filter_driver =
filter.is_some_and(|m| matches!(m.assignment.state, StateRef::Value(_) | StateRef::Set));
merge_driver || filter_driver
}
fn application_files_tree(
project: &Project,
application: &Application,
) -> Result<gix::ObjectId, MergeError> {
let repo = project.repo();
let mut editor = repo
.edit_tree(gix::ObjectId::empty_tree(repo.object_hash()))
.map_err(git)?;
for (path, (oid, kind)) in &application.files {
editor.upsert(path.as_str(), *kind, *oid).map_err(git)?;
}
Ok(editor.write().map_err(git)?.detach())
}
fn graft(
project: &Project,
base: gix::ObjectId,
target: &RepoPath,
sub: gix::ObjectId,
) -> Result<gix::ObjectId, MergeError> {
let repo = project.repo();
if target.is_root() {
return Ok(sub);
}
let mut editor = repo.edit_tree(base).map_err(git)?;
editor
.upsert(target.as_str(), EntryKind::Tree, sub)
.map_err(git)?;
Ok(editor.write().map_err(git)?.detach())
}
fn subtree(
project: &Project,
tree: gix::ObjectId,
target: &RepoPath,
) -> Result<gix::ObjectId, MergeError> {
if target.is_root() {
return Ok(tree);
}
let repo = project.repo();
let t = repo.find_tree(tree).map_err(git)?;
Ok(
match t.lookup_entry_by_path(target.as_str()).map_err(git)? {
Some(entry) if entry.mode().is_tree() => entry.oid().to_owned(),
_ => gix::ObjectId::empty_tree(repo.object_hash()),
},
)
}
fn flat_entries(project: &Project, tree: gix::ObjectId) -> Result<Entries, MergeError> {
let repo = project.repo();
let state =
gix::index::State::from_tree(&tree, &repo.objects, Default::default()).map_err(git)?;
Ok(state
.entries()
.iter()
.map(|e| (e.path(&state).to_owned(), (e.id, e.mode)))
.collect())
}
fn repo_path_for(target: &RepoPath, sub: &BString) -> RepoPath {
let sub = sub.to_str_lossy();
let joined = if target.is_root() {
sub.into_owned()
} else {
format!("{}/{}", target.as_str(), sub)
};
RepoPath::parse(&joined).unwrap_or_else(|_| RepoPath::root())
}
fn classify_conflict(
repo: &gix::Repository,
conflict: &gix::merge::tree::Conflict,
) -> ConflictKind {
use gix::merge::tree::ResolutionFailure;
let entries = conflict.entries();
let is_dir = |i: usize| entries[i].as_ref().is_some_and(|e| e.mode.is_tree());
let present = |i: usize| entries[i].is_some();
if is_dir(0)
|| is_dir(1)
|| is_dir(2)
|| matches!(
conflict.resolution,
Err(ResolutionFailure::OursDirectoryTheirsNonDirectoryTheirsRenamed { .. })
| Err(ResolutionFailure::OursModifiedTheirsDirectoryThenOursRenamed { .. })
)
{
return ConflictKind::FileDirectory;
}
let (bp, op, tp) = (present(0), present(1), present(2));
if !bp && op && tp {
return ConflictKind::AddAdd;
}
if bp && (op ^ tp) {
return ConflictKind::ModifyDelete;
}
if op && tp {
let binary = [1usize, 2]
.iter()
.any(|&i| entries[i].as_ref().is_some_and(|e| is_binary(repo, e.id)));
if binary {
return ConflictKind::Binary;
}
}
ConflictKind::Content
}
fn ancestor_kept(repo_rel: &str, keep_operator: &std::collections::BTreeSet<String>) -> bool {
let mut prefix = repo_rel;
while let Some((parent, _)) = prefix.rsplit_once('/') {
if keep_operator.contains(parent) {
return true;
}
prefix = parent;
}
false
}
fn is_binary(repo: &gix::Repository, id: gix::ObjectId) -> bool {
match repo.find_object(id) {
Ok(object) => object.data.iter().take(8000).any(|&b| b == 0),
Err(_) => false,
}
}
#[cfg(test)]
mod tests;