///| Merge implementation with content-level 3-way merge
///|
pub enum MergeStatus {
AlreadyUpToDate
FastForward
Merged
Conflicted
}
///|
pub struct MergeResult {
status : MergeStatus
commit_id : @bit.ObjectId?
conflicts : Array[String]
/// Conflict type per path: "content", "rename/delete", "rename/add", etc.
conflict_types : Map[String, String]
}
///|
fn merge_fast_forward(
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
git_dir : String,
target : @bit.ObjectId,
) -> Unit raise @bit.GitError {
// A fast-forward is a two-tree checkout like git's: local changes are
// carried over and block it only where the target differs.
let object_git_dir = resolve_common_git_dir(rfs, git_dir)
let sparse = is_sparse_checkout_enabled(rfs, git_dir)
let before : Map[String, Bool] = Map([])
if sparse {
for e in read_index_entries(rfs, git_dir) {
before[e.path] = true
}
}
let updated : Array[String] = []
checkout_two_way(
fs,
rfs,
root,
git_dir,
object_git_dir,
target,
updated_paths=updated,
)
update_head_ref(fs, rfs, git_dir, target)
// Sparse: what the switch wrote outside the cone is removed again and
// gets the skip-worktree bit; a new entry whose file was already there
// is left alone (git).
if sparse {
let written : Map[String, Bool] = Map([])
for p in updated {
written[p] = true
}
let leave : Map[String, Bool] = Map([])
for e in read_index_entries(rfs, git_dir) {
if !before.contains(e.path) && !written.contains(e.path) {
leave[e.path] = true
}
}
sparse_checkout_reapply(fs, rfs, root, leave~)
}
}
///|
/// Outcome of a three-way merge of trees (files keyed by path).
priv struct MergeThreeWay {
merged : Map[String, TreeFileEntry]
conflicts : Array[String]
conflict_types : Map[String, String]
rename_conflict_stages : Map[String, (TreeFileEntry, TreeFileEntry)]
removed_paths : Array[String]
/// "distinct types" conflicts (a regular file on one side, a symlink on
/// the other): path -> (path the regular file is recorded at, its stage)
distinct_types : Map[String, (String, Int)]
/// rename/delete conflicts: new path -> base entry (index stage 1)
rename_delete_base : Map[String, TreeFileEntry]
/// "file location" conflicts: new path -> (stage, entry)
location_stages : Map[String, (Int, TreeFileEntry)]
/// content merges at a rename destination: the three sides
rename_sides : Map[String, RenameMergeSides]
}
///|
/// The sides of a content merge at a rename destination: each side's
/// entry and the path it had there (conflict labels and index stages).
priv struct RenameMergeSides {
base : TreeFileEntry?
ours_path : String
ours : TreeFileEntry
theirs_path : String
theirs : TreeFileEntry
}
///|
/// Three-way merge of `ours` and `theirs` against `base_files`: file-level
/// resolution, content merges (conflict markers are written to the
/// worktree), rename and file/directory conflicts. Shared by merge,
/// cherry-pick and revert, which differ only in which trees they pass.
fn merge_three_way(
db : ObjectDb,
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
git_dir : String,
base_files : Map[String, TreeFileEntry],
ours : Map[String, TreeFileEntry],
theirs : Map[String, TreeFileEntry],
ours_label~ : String,
theirs_label~ : String,
) -> MergeThreeWay raise @bit.GitError {
let file_result = merge_files(base_files, ours, theirs, db, rfs)
let merged = file_result.merged
let conflicts = file_result.conflicts
let all_conflict_types = file_result.conflict_types
let rename_conflict_stages : Map[String, (TreeFileEntry, TreeFileEntry)] = Map([],
)
// Try content-level merge for files modified on both sides
let distinct_types : Map[String, (String, Int)] = Map([])
for candidate in file_result.needs_content_merge {
// Distinct types (git merge-ort): a regular file on one side and a
// symlink on the other cannot be content-merged. The non-regular entry
// keeps the path, the regular file is recorded at `~`.
match (ours.get(candidate.path), theirs.get(candidate.path)) {
(Some(o), Some(t)) if (o.mode == 0o120000) != (t.mode == 0o120000) &&
!is_gitlink_mode_int(o.mode) &&
!is_gitlink_mode_int(t.mode) => {
let (label, stage) = if o.mode == 0o120000 {
(theirs_label, 3)
} else {
(ours_label, 2)
}
let renamed = candidate.path + "~" + label.replace_all(old="/", new="_")
distinct_types[candidate.path] = (renamed, stage)
conflicts.push(candidate.path)
all_conflict_types[candidate.path] = "distinct types"
continue
}
_ => ()
}
// Both sides changed the mode, differently (e.g. a symlink that became
// a 644 file on one side and a 755 file on the other), or a file added
// on both sides with different modes (add/add): a conflict even when
// the contents merge cleanly -- git still writes the merged content.
let mode_conflict = match
(
base_files.get(candidate.path),
ours.get(candidate.path),
theirs.get(candidate.path),
) {
(Some(b), Some(o), Some(t)) if o.mode != b.mode &&
t.mode != b.mode &&
o.mode != t.mode => Some("content")
(None, Some(o), Some(t)) if o.mode != t.mode => Some("add/add")
_ => None
}
if mode_conflict is Some(kind) {
conflicts.push(candidate.path)
if !all_conflict_types.contains(candidate.path) {
all_conflict_types[candidate.path] = kind
}
// Our content stays when it is what the merge gives.
let resolved : @bit.ObjectId? = if candidate.ours_id ==
candidate.theirs_id ||
candidate.base_id == Some(candidate.theirs_id) {
None
} else if candidate.base_id == Some(candidate.ours_id) {
Some(candidate.theirs_id)
} else {
let ours_data = merge_get_blob_data(db, rfs, candidate.ours_id)
let theirs_data = merge_get_blob_data(db, rfs, candidate.theirs_id)
let base_raw = match candidate.base_id {
Some(id) => merge_get_blob_data(db, rfs, id)
None => Bytes::new(0)
}
if !(@diff3.is_binary_content(base_raw) ||
@diff3.is_binary_content(ours_data) ||
@diff3.is_binary_content(theirs_data)) {
let utf8 = merge_is_valid_utf8(base_raw) &&
merge_is_valid_utf8(ours_data) &&
merge_is_valid_utf8(theirs_data)
let r = @diff3.content_merge(
merge_bytes_to_text(base_raw, utf8),
merge_bytes_to_text(ours_data, utf8),
merge_bytes_to_text(theirs_data, utf8),
@diff3.ContentMergeOptions::default().with_labels(
ours=ours_label,
base="",
theirs=theirs_label,
),
)
let full_path = join_path(root, candidate.path)
fs.mkdir_p(rebase_parent_dir(full_path))
fs.write_file(full_path, merge_text_to_bytes(r.content, utf8))
}
None
}
match resolved {
Some(id) => {
let full_path = join_path(root, candidate.path)
fs.mkdir_p(rebase_parent_dir(full_path))
fs.write_file(full_path, merge_get_blob_data(db, rfs, id))
}
None => ()
}
continue
}
// Trivial resolutions first, byte for byte (e.g. one side only
// renamed the file): no text round-trip at all.
// The exec bit merges separately: a side that changed it wins.
let trivial_mode = candidate.mode
if candidate.ours_id == candidate.theirs_id ||
candidate.base_id == Some(candidate.theirs_id) {
merged[candidate.path] = { id: candidate.ours_id, mode: trivial_mode }
continue
}
if candidate.base_id == Some(candidate.ours_id) {
merged[candidate.path] = { id: candidate.theirs_id, mode: trivial_mode }
continue
}
let base_bytes_raw = match candidate.base_id {
Some(id) => merge_get_blob_data(db, rfs, id)
None => Bytes::new(0)
}
// Skip binary files
let ours_data = merge_get_blob_data(db, rfs, candidate.ours_id)
let theirs_data = merge_get_blob_data(db, rfs, candidate.theirs_id)
// Content that is not valid UTF-8 cannot go through the text merge
// without being mangled: treat it like binary (a conflict).
let base_data = match candidate.base_id {
Some(id) => merge_get_blob_data(db, rfs, id)
None => Bytes::new(0)
}
// git (ll_merge) treats the merge as binary when any of the three
// sides is binary, the base included.
if @diff3.is_binary_content(base_data) ||
@diff3.is_binary_content(ours_data) ||
@diff3.is_binary_content(theirs_data) {
// Binary: our content stays, but the merged mode is applied (git).
let mm = candidate.mode
let full_path = join_path(root, candidate.path)
// Not on disk because the entry is skip-worktree: git drops the bit
// and writes our version there. A tracked file merely deleted from
// the worktree stays deleted (difffuzz core-4926).
if @bitio.worktree_entry_meta_sync(rfs, full_path) is None &&
read_skip_worktree_paths(rfs, git_dir).contains(candidate.path) {
fs.mkdir_p(rebase_parent_dir(full_path))
fs.write_file(full_path, ours_data)
}
if mm == 0o100755 {
ignore(@bitio.worktree_set_mode(full_path, 0o755))
} else if mm == 0o100644 {
ignore(@bitio.worktree_set_mode(full_path, 0o644))
}
conflicts.push(candidate.path)
if !all_conflict_types.contains(candidate.path) {
all_conflict_types[candidate.path] = "content"
}
continue
}
// Text merge of the raw bytes: UTF-8 when all three sides are valid
// UTF-8, otherwise byte-for-char (Latin-1) so nothing is mangled (git
// merges such content as text too; only NUL bytes make it binary).
let utf8 = merge_is_valid_utf8(base_bytes_raw) &&
merge_is_valid_utf8(ours_data) &&
merge_is_valid_utf8(theirs_data)
// A rename on one side: git labels each side with its path.
let (cm_ours_label, cm_theirs_label) = match
file_result.rename_sides.get(candidate.path) {
Some(sides) if sides.ours_path != sides.theirs_path =>
(
ours_label + ":" + sides.ours_path,
theirs_label + ":" + sides.theirs_path,
)
_ => (ours_label, theirs_label)
}
let result = @diff3.content_merge(
merge_bytes_to_text(base_bytes_raw, utf8),
merge_bytes_to_text(ours_data, utf8),
merge_bytes_to_text(theirs_data, utf8),
@diff3.ContentMergeOptions::default().with_labels(
ours=cm_ours_label,
base="",
theirs=cm_theirs_label,
),
)
ignore(base_data)
if result.has_conflicts {
// Write conflict markers to worktree
let full_path = join_path(root, candidate.path)
let dir = rebase_parent_dir(full_path)
fs.mkdir_p(dir)
fs.write_file(full_path, merge_text_to_bytes(result.content, utf8))
// The conflicted file carries the merged mode (git merges the exec
// bit separately: a side that changed it wins).
let mm = candidate.mode
if mm == 0o100755 {
ignore(@bitio.worktree_set_mode(full_path, 0o755))
} else if mm == 0o100644 {
ignore(@bitio.worktree_set_mode(full_path, 0o644))
}
conflicts.push(candidate.path)
if !all_conflict_types.contains(candidate.path) {
all_conflict_types[candidate.path] = "content"
}
} else {
// Clean merge - create new blob
let content_bytes = merge_text_to_bytes(result.content, utf8)
let (blob_id, compressed) = @bit.create_blob(content_bytes)
write_object_bytes(fs, git_dir, blob_id, compressed)
// If this path has a rename/add conflict, store resolved as stage 2
if all_conflict_types.get(candidate.path).unwrap_or("") == "rename/add" {
let resolved_entry : TreeFileEntry = {
id: blob_id,
mode: candidate.mode,
}
// Find theirs' independently added file for stage 3
let theirs_added = match theirs.get(candidate.path) {
Some(e) => e
None => resolved_entry
}
rename_conflict_stages[candidate.path] = (resolved_entry, theirs_added)
// Write conflict markers for worktree
let ours_text = merge_get_blob_text(db, rfs, blob_id)
let theirs_text = match theirs.get(candidate.path) {
Some(e) => merge_get_blob_text(db, rfs, e.id)
None => ""
}
let conflict_result = @diff3.content_merge(
"",
ours_text,
theirs_text,
@diff3.ContentMergeOptions::default().with_labels(
ours=ours_label,
base="",
theirs=theirs_label,
),
)
let full_path = join_path(root, candidate.path)
let dir = rebase_parent_dir(full_path)
fs.mkdir_p(dir)
fs.write_string(full_path, conflict_result.content)
} else {
merged[candidate.path] = {
id: blob_id,
mode: candidate.mode,
}
}
}
}
// Handle rename/rename(2to1) conflicts
for candidate in file_result.rename_2to1 {
// Resolve ours side: merge(base[ours_old], ours[path], theirs[ours_old])
let ours_base_id = base_files
.get(candidate.ours_old_path)
.map(fn(e) { e.id })
let ours_at_path = ours.get(candidate.path)
let theirs_at_ours_old = theirs.get(candidate.ours_old_path)
let ours_resolved = merge_resolve_rename_content(
db, rfs, fs, git_dir, ours_base_id, ours_at_path, theirs_at_ours_old,
)
// Resolve theirs side: merge(base[theirs_old], ours[theirs_old], theirs[path])
let theirs_base_id = base_files
.get(candidate.theirs_old_path)
.map(fn(e) { e.id })
let ours_at_theirs_old = ours.get(candidate.theirs_old_path)
let theirs_at_path = theirs.get(candidate.path)
let theirs_resolved = merge_resolve_rename_content(
db, rfs, fs, git_dir, theirs_base_id, ours_at_theirs_old, theirs_at_path,
)
// Now merge the two resolved versions
let ours_text = match ours_resolved {
Some((id, _)) => merge_get_blob_text(db, rfs, id)
None =>
match ours_at_path {
Some(e) => merge_get_blob_text(db, rfs, e.id)
None => ""
}
}
let theirs_text = match theirs_resolved {
Some((id, _)) => merge_get_blob_text(db, rfs, id)
None =>
match theirs_at_path {
Some(e) => merge_get_blob_text(db, rfs, e.id)
None => ""
}
}
let ours_blob_id = match ours_resolved {
Some((id, _)) => id
None =>
match ours_at_path {
Some(e) => e.id
None => @bit.ObjectId::zero()
}
}
let theirs_blob_id = match theirs_resolved {
Some((id, _)) => id
None =>
match theirs_at_path {
Some(e) => e.id
None => @bit.ObjectId::zero()
}
}
if ours_blob_id == theirs_blob_id {
// Same resolved content - no conflict
merged[candidate.path] = { id: ours_blob_id, mode: candidate.mode }
} else {
// Different content - final merge with conflict markers
// Use common prefix lines as base so shared content stays outside markers
let common_base = merge_common_line_prefix(ours_text, theirs_text)
let final_result = @diff3.content_merge(
common_base,
ours_text,
theirs_text,
@diff3.ContentMergeOptions::default().with_labels(
ours=ours_label,
base="",
theirs=theirs_label,
),
)
let full_path = join_path(root, candidate.path)
let dir = rebase_parent_dir(full_path)
fs.mkdir_p(dir)
fs.write_string(full_path, final_result.content)
conflicts.push(candidate.path)
all_conflict_types[candidate.path] = "rename/rename"
// Store stage entries for index
rename_conflict_stages[candidate.path] = (
{ id: ours_blob_id, mode: candidate.mode },
{ id: theirs_blob_id, mode: candidate.mode },
)
}
}
// Detect file/directory conflicts: a file path that collides with a directory
let file_dir_renames : Map[String, String] = Map([])
let merged_paths : Array[String] = []
for path, _ in merged {
merged_paths.push(path)
}
for path, _ in merged {
let prefix = path + "/"
for other_path in merged_paths {
if other_path.has_prefix(prefix) {
let new_path = path + "~HEAD"
file_dir_renames[path] = new_path
break
}
}
}
for old_path, new_path in file_dir_renames {
match merged.get(old_path) {
Some(entry) => {
merged.remove(old_path)
merged[new_path] = entry
conflicts.push(new_path)
all_conflict_types[new_path] = "file/directory"
}
None => ()
}
}
{
merged,
conflicts,
conflict_types: all_conflict_types,
rename_conflict_stages,
removed_paths: file_result.removed_paths,
distinct_types,
rename_delete_base: file_result.rename_delete_base,
location_stages: file_result.location_stages,
rename_sides: file_result.rename_sides,
}
}
///|
/// Write a conflicted three-way result: merged paths to the worktree (the
/// conflicting ones already hold markers), renamed-away paths removed, and
/// stages 1-3 in the index.
fn merge_write_conflicted(
db : ObjectDb,
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
git_dir : String,
base_files : Map[String, TreeFileEntry],
ours : Map[String, TreeFileEntry],
theirs : Map[String, TreeFileEntry],
tw : MergeThreeWay,
overwrite? : Map[String, Bool] = Map([]),
) -> Unit raise @bit.GitError {
// Only what the merge changes: unstaged edits elsewhere survive.
let changed : Map[String, TreeFileEntry] = Map([])
for path, f in tw.merged {
match ours.get(path) {
Some(o) if o.id == f.id && o.mode == f.mode => ()
_ =>
// Content conflicts already hold markers on disk; a conflicted
// path with nothing on disk (modify/delete: "left in tree") gets
// the surviving version written.
if !tw.conflicts.contains(path) ||
@bitio.worktree_entry_meta_sync(rfs, join_path(root, path)) is None {
changed[path] = f
}
}
}
// distinct types: the symlink side at the path, the regular file at its
// renamed path.
for path, item in tw.distinct_types {
let (renamed, stage) = item
match (ours.get(path), theirs.get(path)) {
(Some(o), Some(t)) => {
let (keeper, regular) = if stage == 2 { (t, o) } else { (o, t) }
changed[path] = keeper
changed[renamed] = regular
}
_ => ()
}
}
// modify/delete: the surviving side's version is left in the tree. Our
// own version is only written for a skip-worktree (sparse) entry; a
// tracked file deleted locally stays deleted (git writes nothing that
// matches our tree).
let md_skip = read_skip_worktree_paths(rfs, git_dir)
let md_sparse = is_sparse_checkout_enabled(rfs, git_dir)
let md_patterns = if md_sparse {
read_sparse_patterns(rfs, git_dir)
} else {
[]
}
for path in tw.conflicts {
if changed.contains(path) ||
(!overwrite.contains(path) &&
@bitio.worktree_entry_meta_sync(rfs, join_path(root, path)) is Some(_)) {
continue
}
match (ours.get(path), theirs.get(path)) {
(None, Some(t)) => changed[path] = t
(Some(o), None) =>
if overwrite.contains(path) ||
md_skip.contains(path) ||
(md_sparse && !matches_sparse_pattern(path, md_patterns)) {
changed[path] = o
}
_ => ()
}
}
// Sparse: a clean (not conflicted) path outside the cone, or one that
// already had the skip-worktree bit, is updated in the index only and
// keeps / gets the bit; conflicts are always written (git).
let skip = read_skip_worktree_paths(rfs, git_dir)
let sparse = is_sparse_checkout_enabled(rfs, git_dir)
let patterns = if sparse { read_sparse_patterns(rfs, git_dir) } else { [] }
let index_skip : Map[String, Bool] = Map([])
for path, f in tw.merged {
if tw.conflicts.contains(path) || is_gitlink_mode_int(f.mode) {
continue
}
if skip.contains(path) {
index_skip[path] = true
changed.remove(path)
} else if sparse &&
!matches_sparse_pattern(path, patterns) &&
(changed.contains(path) ||
@bitio.worktree_entry_meta_sync(rfs, join_path(root, path)) is None) {
index_skip[path] = true
changed.remove(path)
}
}
write_worktree_from_files(
db,
fs,
rfs,
root,
git_dir,
changed,
remove_missing=false,
)
// Paths the merge deletes cleanly go from the worktree too (git), also
// when other paths conflict.
let deleted_dirs : Array[String] = []
for path, o in ours {
if tw.merged.contains(path) ||
tw.conflicts.contains(path) ||
skip.contains(path) ||
is_gitlink_mode_int(o.mode) {
continue
}
let abs = join_path(root, path)
if @bitio.worktree_entry_meta_sync(rfs, abs) is Some(_) {
fs.remove_file(abs) catch {
_ => ()
}
}
deleted_dirs.push(parent_dir(abs))
}
tree_ops_prune_empty_dirs(fs, rfs, root, deleted_dirs)
for path in tw.removed_paths {
// A path not in our tree (our own rename source) is untracked there.
if !ours.contains(path) {
continue
}
let full_path = join_path(root, path)
if rfs.is_file(full_path) {
fs.remove_file(full_path) catch {
_ => ()
}
}
}
// rename/delete: the base version sits at the new path's stage 1.
let index_base = base_files.copy()
for path, b in tw.rename_delete_base {
index_base[path] = b
}
let entries = merge_conflicted_index_entries_with_renames(
db,
rfs,
index_base,
ours,
theirs,
tw.merged,
tw.conflicts,
tw.rename_conflict_stages,
distinct_types=tw.distinct_types,
location_stages=tw.location_stages,
rename_sides=tw.rename_sides,
)
write_index_stage_entries(fs, git_dir, entries, skip=index_skip)
}
///|
pub fn merge(
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
target : @bit.ObjectId,
message : String,
author : String,
timestamp : Int64,
ours_label? : String = "HEAD",
theirs_label? : String = "incoming",
) -> MergeResult raise @bit.GitError {
let git_marker = join_path(root, ".git")
let git_dir = if rfs.is_file(git_marker) {
resolve_gitdir(rfs, git_marker)
} else {
git_marker
}
let head = match resolve_head_commit(rfs, git_dir) {
None =>
match read_head_ref(rfs, git_dir) {
Branch(_) => {
merge_fast_forward(fs, rfs, root, git_dir, target)
return {
status: FastForward,
commit_id: Some(target),
conflicts: [],
conflict_types: Map([]),
}
}
Detached(_) => raise @bit.GitError::InvalidObject("HEAD not found")
}
Some(id) => id
}
if head == target {
return {
status: AlreadyUpToDate,
commit_id: Some(head),
conflicts: [],
conflict_types: Map([]),
}
}
let db = ObjectDb::load(rfs, git_dir)
if merge_is_ancestor(db, rfs, head, target) {
merge_fast_forward(fs, rfs, root, git_dir, target)
return {
status: FastForward,
commit_id: Some(target),
conflicts: [],
conflict_types: Map([]),
}
}
if merge_is_ancestor(db, rfs, target, head) {
return {
status: AlreadyUpToDate,
commit_id: Some(head),
conflicts: [],
conflict_types: Map([]),
}
}
let base = merge_find_base(db, rfs, head, target)
let base_files = match base {
None => Map([])
Some(id) => collect_tree_files_from_commit(db, rfs, id)
}
let ours = collect_tree_files_from_commit(db, rfs, head)
let theirs = collect_tree_files_from_commit(db, rfs, target)
merge_check_clean_index(rfs, git_dir, ours, restore=(db, fs, root))
let already_present = stash_check_local_changes(
rfs,
root,
ours,
base_files,
theirs,
read_skip_worktree_paths(rfs, git_dir),
stash_note=false,
// Sparse checkout: git only warns and writes over the file (5fabca56).
sparse=is_sparse_checkout_enabled(rfs, git_dir),
touched=Some(merge_touched_paths(base_files, ours, theirs, db, rfs)),
)
note_sparse_not_updated(rfs, git_dir, already_present.keys().to_array())
let tw = merge_three_way(
db,
fs,
rfs,
root,
git_dir,
base_files,
ours,
theirs,
ours_label~,
theirs_label~,
)
let merged = tw.merged
let conflicts = tw.conflicts
let all_conflict_types = tw.conflict_types
if conflicts.length() > 0 {
merge_write_conflicted(
db, fs, rfs, root, git_dir, base_files, ours, theirs, tw,
)
fs.write_string(git_dir + "/MERGE_HEAD", target.to_hex() + "\n")
fs.write_string(git_dir + "/ORIG_HEAD", head.to_hex() + "\n")
fs.write_string(
git_dir + "/MERGE_MSG",
merge_msg_with_conflicts(rfs, git_dir, message + "\n"),
)
conflicts.sort()
return {
status: Conflicted,
commit_id: None,
conflicts,
conflict_types: all_conflict_types,
}
}
merge_write_changed_paths(db, fs, rfs, root, git_dir, ours, merged)
let entries = tree_files_to_index(db, rfs, merged)
merge_write_index_keeping_skip(fs, rfs, root, git_dir, entries)
let tree_id = write_tree_from_index(fs, rfs, git_dir, entries)
let commit = @bit.Commit::new(
tree_id,
[head, target],
author,
timestamp,
"+0000",
author,
timestamp,
"+0000",
message,
)
let (commit_id, compressed) = @bit.create_commit(commit)
write_object_bytes(fs, git_dir, commit_id, compressed)
update_head_ref(fs, rfs, git_dir, commit_id)
{
status: Merged,
commit_id: Some(commit_id),
conflicts: [],
conflict_types: Map([]),
}
}
///|
fn merge_tree_file_to_index_entry(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
path : String,
info : TreeFileEntry,
) -> IndexEntry raise @bit.GitError {
let files : Map[String, TreeFileEntry] = Map([])
files[path] = info
let entries = tree_files_to_index(db, fs, files)
if entries.length() == 0 {
raise @bit.GitError::InvalidObject("Missing merge index entry: " + path)
}
entries[0]
}
///|
fn merge_is_ancestor(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
ancestor : @bit.ObjectId,
commit_id : @bit.ObjectId,
) -> Bool raise @bit.GitError {
merge_base_is_ancestor(db, fs, ancestor, commit_id)
}
///|
fn merge_find_base(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
a : @bit.ObjectId,
b : @bit.ObjectId,
) -> @bit.ObjectId? raise @bit.GitError {
let seen : Map[String, Bool] = Map([])
let stack_a : Array[@bit.ObjectId] = [a]
while stack_a.length() > 0 {
let id = match stack_a.pop() {
None => raise @bit.GitError::InvalidObject("Empty stack")
Some(v) => v
}
let hex = id.to_hex()
if seen.contains(hex) {
continue
}
seen[hex] = true
let parents = merge_commit_parents(db, fs, id)
for p in parents {
stack_a.push(p)
}
}
let stack_b : Array[@bit.ObjectId] = [b]
while stack_b.length() > 0 {
let id = match stack_b.pop() {
None => raise @bit.GitError::InvalidObject("Empty stack")
Some(v) => v
}
let hex = id.to_hex()
if seen.contains(hex) {
return Some(id)
}
let parents = merge_commit_parents(db, fs, id)
for p in parents {
stack_b.push(p)
}
}
None
}
///|
fn merge_commit_parents(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
commit_id : @bit.ObjectId,
) -> Array[@bit.ObjectId] raise @bit.GitError {
let obj = db.get(fs, commit_id)
match obj {
None => raise @bit.GitError::InvalidObject("Missing commit object")
Some(o) => {
if o.obj_type != @bit.ObjectType::Commit {
raise @bit.GitError::InvalidObject("Object is not a commit")
}
let info = @bit.parse_commit(o.data)
info.parents
}
}
}
///|
priv struct MergeFilesResult {
merged : Map[String, TreeFileEntry]
conflicts : Array[String]
needs_content_merge : Array[ContentMergeCandidate]
rename_2to1 : Array[Rename2to1Candidate]
/// Conflict type per path (e.g. "rename/delete", "rename/add")
conflict_types : Map[String, String]
/// Paths that were renamed away and should be removed from worktree
removed_paths : Array[String]
/// rename/delete conflicts: new path -> the base entry (index stage 1)
rename_delete_base : Map[String, TreeFileEntry]
/// "file location" conflicts (directory renames): new path -> (stage,
/// entry) of the file the other side added to the renamed directory
location_stages : Map[String, (Int, TreeFileEntry)]
/// content merges at a rename destination: the three sides
rename_sides : Map[String, RenameMergeSides]
}
///|
priv struct ContentMergeCandidate {
path : String
base_id : @bit.ObjectId?
ours_id : @bit.ObjectId
theirs_id : @bit.ObjectId
mode : Int
}
///|
/// Two different files both renamed to the same target path.
/// Requires resolving each side's rename/modify first, then merging results.
priv struct Rename2to1Candidate {
path : String
ours_old_path : String
theirs_old_path : String
mode : Int
}
///|
fn merge_files(
base : Map[String, TreeFileEntry],
ours : Map[String, TreeFileEntry],
theirs : Map[String, TreeFileEntry],
db : ObjectDb,
rfs : &@bit.RepoFileSystem,
) -> MergeFilesResult {
let merged : Map[String, TreeFileEntry] = Map([])
let conflicts : Array[String] = []
let needs_content_merge : Array[ContentMergeCandidate] = []
let rename_delete_base : Map[String, TreeFileEntry] = Map([])
let rename_2to1 : Array[Rename2to1Candidate] = []
let conflict_types : Map[String, String] = Map([])
let removed_paths : Array[String] = []
let rename_sides : Map[String, RenameMergeSides] = Map([])
// Step 1: Detect renames on each side
let ours_renames = merge_detect_renames(base, ours, db, rfs)
let theirs_renames = merge_detect_renames(base, theirs, db, rfs)
// Paths that are handled by rename logic (skip in normal processing)
let handled_paths : Map[String, Bool] = Map([])
// Step 1b: Detect rename/rename(2to1) - different files renamed to same target
let ours_new_to_old : Map[String, String] = Map([])
for old_path, new_path in ours_renames.old_to_new {
ours_new_to_old[new_path] = old_path
}
for theirs_old, theirs_new in theirs_renames.old_to_new {
match ours_new_to_old.get(theirs_new) {
Some(ours_old) =>
if ours_old != theirs_old {
// rename/rename(2to1): different files both renamed to same path
let mode = match ours.get(theirs_new) {
Some(e) => e.mode
None => 0o100644
}
rename_2to1.push({
path: theirs_new,
ours_old_path: ours_old,
theirs_old_path: theirs_old,
mode,
})
handled_paths[ours_old] = true
handled_paths[theirs_old] = true
handled_paths[theirs_new] = true
removed_paths.push(ours_old)
removed_paths.push(theirs_old)
}
None => ()
}
}
// Step 1c: directory renames (merge-ort, merge.directoryRenames=conflict).
// A file one side added inside a directory the other side renamed away
// entirely moves with it, as a "file location" conflict.
let location_stages : Map[String, (Int, TreeFileEntry)] = Map([])
let apply_dir_renames = fn(
renamed_by : Map[String, TreeFileEntry],
renames : SideRenames,
adder : Map[String, TreeFileEntry],
adder_renames : SideRenames,
stage : Int,
) {
let dir_renames = merge_dir_renames(base, renamed_by, renames)
if dir_renames.length() == 0 {
return
}
let adder_targets : Map[String, Bool] = Map([])
for _, n in adder_renames.old_to_new {
adder_targets[n] = true
}
for path, entry in adder {
if base.contains(path) || adder_targets.contains(path) || handled_paths.contains(path) {
continue
}
// The deepest renamed directory holding the path.
let mut best : (String, String)? = None
for old_dir, new_dir in dir_renames {
if path.has_prefix(old_dir + "/") {
match best {
Some((d, _)) if d.length() >= old_dir.length() => ()
_ => best = Some((old_dir, new_dir))
}
}
}
guard best is Some((old_dir, new_dir)) else { continue }
let rest = String::unsafe_substring(
path,
start=old_dir.length() + 1,
end=path.length(),
)
let new_path = if new_dir.length() == 0 { rest } else { new_dir + "/" + rest }
if base.contains(new_path) || ours.contains(new_path) || theirs.contains(new_path) {
continue
}
merged[new_path] = entry
conflicts.push(new_path)
conflict_types[new_path] = "file location"
location_stages[new_path] = (stage, entry)
handled_paths[path] = true
handled_paths[new_path] = true
removed_paths.push(path)
}
}
apply_dir_renames(theirs, theirs_renames, ours, ours_renames, 2)
apply_dir_renames(ours, ours_renames, theirs, theirs_renames, 3)
// Step 2: Process renames on ours side (skip already handled by Step 1b)
for old_path, new_path in ours_renames.old_to_new {
if handled_paths.contains(old_path) || handled_paths.contains(new_path) {
continue
}
let base_entry = base.get(old_path)
let ours_entry = ours.get(new_path)
// Check if theirs also renamed the same file
match theirs_renames.old_to_new.get(old_path) {
Some(theirs_new_path) =>
if theirs_new_path == new_path {
// Both sides renamed to same path - check content
let theirs_entry = theirs.get(theirs_new_path)
if merge_entry_eq(ours_entry, theirs_entry) {
// Same rename, same content - take it
match ours_entry {
Some(v) => merged[new_path] = v
None => ()
}
} else {
// Same target path, possibly different content - content merge
match (ours_entry, theirs_entry) {
(Some(o), Some(t)) => {
rename_sides[new_path] = {
base: base_entry,
ours_path: new_path,
ours: o,
theirs_path: new_path,
theirs: t,
}
needs_content_merge.push({
path: new_path,
base_id: base_entry.map(fn(e) { e.id }),
ours_id: o.id,
theirs_id: t.id,
mode: merge_three_way_mode(
base_entry.map(e => e.mode),
Some(o.mode),
Some(t.mode),
o.mode,
),
})
}
_ => ()
}
}
handled_paths[old_path] = true
handled_paths[new_path] = true
handled_paths[theirs_new_path] = true
} else {
// Renamed to different paths: rename/rename(1to2) conflict
// Put both versions in merged for worktree
match ours_entry {
Some(v) => merged[new_path] = v
None => ()
}
match theirs.get(theirs_new_path) {
Some(v) => merged[theirs_new_path] = v
None => ()
}
// git: stage 2 at ours' path, stage 3 at theirs', stage 1 at
// the original path ("both deleted").
conflicts.push(new_path)
conflict_types[new_path] = "rename/rename"
if theirs.contains(theirs_new_path) {
conflicts.push(theirs_new_path)
conflict_types[theirs_new_path] = "rename/rename"
}
if base_entry is Some(_) &&
!ours.contains(old_path) &&
!theirs.contains(old_path) {
conflicts.push(old_path)
conflict_types[old_path] = "rename/rename"
}
handled_paths[old_path] = true
handled_paths[new_path] = true
handled_paths[theirs_new_path] = true
}
None => {
// Only ours renamed. Check what theirs did with old_path
let is_add_source = ours_renames.add_source_paths.contains(old_path)
let theirs_entry = theirs.get(old_path)
match (base_entry, ours_entry, theirs_entry) {
(Some(b), Some(o), Some(t)) =>
if b.id == t.id {
// Theirs didn't modify the content - take ours rename, with
// a mode change theirs made (the exec bit merges apart).
merged[new_path] = {
id: o.id,
mode: merge_three_way_mode(Some(b.mode), Some(o.mode), Some(t.mode), o.mode),
}
} else if is_add_source &&
theirs_renames.add_source_paths.contains(old_path) {
// Both sides replaced old_path with new content; the original
// was renamed. Handle renamed content at new_path, and the
// new files at old_path will be merged in Step 4.
merged[new_path] = o
} else if (b.mode == 0o120000) != (t.mode == 0o120000) {
// Theirs changed the type (symlink <-> file): git does not
// pair that with the path, it is a delete plus an add. So:
// rename/delete at new_path, theirs' new file at old_path.
merged[new_path] = o
conflicts.push(new_path)
conflict_types[new_path] = "rename/delete"
rename_delete_base[new_path] = b
merged[old_path] = t
} else {
// Theirs modified at old_path, ours renamed to new_path
// -> content merge at new_path
rename_sides[new_path] = {
base: Some(b),
ours_path: new_path,
ours: o,
theirs_path: old_path,
theirs: t,
}
needs_content_merge.push({
path: new_path,
base_id: Some(b.id),
ours_id: o.id,
theirs_id: t.id,
mode: merge_three_way_mode(
Some(b.mode),
Some(o.mode),
Some(t.mode),
o.mode,
),
})
}
(b, Some(o), None) => {
// Theirs deleted old_path, ours renamed: rename/delete conflict
// (the base version sits at the new path's stage 1).
merged[new_path] = o
conflicts.push(new_path)
conflict_types[new_path] = "rename/delete"
match b {
Some(be) => rename_delete_base[new_path] = be
None => ()
}
}
_ =>
match ours_entry {
Some(v) => merged[new_path] = v
None => ()
}
}
// For add-source: include the new file at old_path
if is_add_source {
match ours.get(old_path) {
Some(new_file) => merged[old_path] = new_file
None => ()
}
}
// Check for rename/add-dest: theirs independently added a file at new_path
if !base.contains(new_path) {
match theirs.get(new_path) {
Some(_) => {
// Theirs added a file at same path as our rename target
conflicts.push(new_path)
conflict_types[new_path] = "rename/add"
}
None => ()
}
}
handled_paths[old_path] = true
handled_paths[new_path] = true
// Only mark old_path for removal if it's a clean rename (no conflict, no add-source)
if !is_add_source && !conflict_types.contains(new_path) {
removed_paths.push(old_path)
}
}
}
}
// Step 3: Process renames on theirs side (skip already handled)
for old_path, new_path in theirs_renames.old_to_new {
if handled_paths.contains(old_path) || handled_paths.contains(new_path) {
continue
}
let base_entry = base.get(old_path)
let theirs_entry = theirs.get(new_path)
let is_add_source = theirs_renames.add_source_paths.contains(old_path)
// ours didn't rename (already checked above)
let ours_entry = ours.get(old_path)
match (base_entry, ours_entry, theirs_entry) {
(Some(b), Some(o), Some(t)) =>
if b.id == o.id {
// Ours didn't modify the content - take theirs rename, with a
// mode change ours made.
merged[new_path] = {
id: t.id,
mode: merge_three_way_mode(Some(b.mode), Some(o.mode), Some(t.mode), t.mode),
}
} else if is_add_source &&
ours_renames.add_source_paths.contains(old_path) {
// Both sides replaced; handled in Step 2
merged[new_path] = t
} else {
// Ours modified at old_path, theirs renamed to new_path
// -> content merge at new_path
rename_sides[new_path] = {
base: Some(b),
ours_path: old_path,
ours: o,
theirs_path: new_path,
theirs: t,
}
needs_content_merge.push({
path: new_path,
base_id: Some(b.id),
ours_id: o.id,
theirs_id: t.id,
mode: merge_three_way_mode(
Some(b.mode),
Some(o.mode),
Some(t.mode),
t.mode,
),
})
}
(b, None, Some(t)) => {
// Ours deleted old_path, theirs renamed: rename/delete conflict
// (the base version sits at the new path's stage 1).
merged[new_path] = t
conflicts.push(new_path)
conflict_types[new_path] = "rename/delete"
match b {
Some(be) => rename_delete_base[new_path] = be
None => ()
}
}
_ =>
match theirs_entry {
Some(v) => merged[new_path] = v
None => ()
}
}
// For add-source: include the new file at old_path
if is_add_source {
match theirs.get(old_path) {
Some(new_file) => merged[old_path] = new_file
None => ()
}
}
// Check for rename/add-dest: ours independently added a file at new_path
if !base.contains(new_path) {
match ours.get(new_path) {
Some(_) => {
conflicts.push(new_path)
conflict_types[new_path] = "rename/add"
}
None => ()
}
}
handled_paths[old_path] = true
handled_paths[new_path] = true
if !is_add_source && !conflict_types.contains(new_path) {
removed_paths.push(old_path)
}
}
// Step 4: Process remaining paths with standard logic
let all_paths : Map[String, Bool] = Map([])
for path, _ in base {
if !handled_paths.contains(path) {
all_paths[path] = true
}
}
for path, _ in ours {
if !handled_paths.contains(path) {
all_paths[path] = true
}
}
for path, _ in theirs {
if !handled_paths.contains(path) {
all_paths[path] = true
}
}
for path, _ in all_paths {
let b = base.get(path)
let o = ours.get(path)
let t = theirs.get(path)
if merge_entry_eq(o, t) {
match o {
None => ()
Some(v) => merged[path] = v
}
} else if merge_entry_eq(o, b) {
match t {
None => ()
Some(v) => merged[path] = v
}
} else if merge_entry_eq(t, b) {
match o {
None => ()
Some(v) => merged[path] = v
}
} else {
// Both sides modified - try content merge if both have the file
match (o, t) {
(Some(ours_entry), Some(theirs_entry)) => {
let base_id = match b {
Some(base_entry) => Some(base_entry.id)
None => None
}
needs_content_merge.push({
path,
base_id,
ours_id: ours_entry.id,
theirs_id: theirs_entry.id,
mode: merge_three_way_mode(
b.map(e => e.mode),
Some(ours_entry.mode),
Some(theirs_entry.mode),
ours_entry.mode,
),
})
}
_ => {
// One side deleted, other modified - file-level conflict
conflicts.push(path)
conflict_types[path] = "modify/delete"
}
}
}
}
{
merged,
conflicts,
needs_content_merge,
rename_2to1,
conflict_types,
removed_paths,
rename_delete_base,
location_stages,
rename_sides,
}
}
///|
fn merge_get_blob_text(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
id : @bit.ObjectId,
) -> String {
get_blob_content(db, fs, id)
}
///|
fn merge_get_blob_data(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
id : @bit.ObjectId,
) -> Bytes {
let obj = db.get(fs, id) catch { _ => return Default::default() }
match obj {
Some(o) =>
if o.obj_type == @bit.ObjectType::Blob {
o.data
} else {
Default::default()
}
None => Default::default()
}
}
///|
fn merge_entry_eq(a : TreeFileEntry?, b : TreeFileEntry?) -> Bool {
match (a, b) {
(None, None) => true
(Some(x), Some(y)) => x.id == y.id && x.mode == y.mode
_ => false
}
}
///|
/// Extract common prefix lines from two texts for use as merge base.
fn merge_common_line_prefix(a : String, b : String) -> String {
let a_arr : Array[String] = []
for part in a.split("\n") {
a_arr.push(part.to_owned())
}
let b_arr : Array[String] = []
for part in b.split("\n") {
b_arr.push(part.to_owned())
}
let result = StringBuilder()
let limit = if a_arr.length() < b_arr.length() {
a_arr.length()
} else {
b_arr.length()
}
let mut count = 0
for i in 0.. (@bit.ObjectId, Int)? raise @bit.GitError {
let ours_id = match ours_entry {
Some(e) => e.id
None => return None
}
let theirs_id = match theirs_entry {
Some(e) => e.id
None => return None
}
match base_id {
Some(b_id) =>
if b_id == theirs_id {
// Theirs didn't modify, take ours
return Some((ours_id, ours_entry.unwrap().mode))
} else if b_id == ours_id {
// Ours didn't modify, take theirs
return Some((theirs_id, theirs_entry.unwrap().mode))
} else if ours_id == theirs_id {
return Some((ours_id, ours_entry.unwrap().mode))
}
None =>
if ours_id == theirs_id {
return Some((ours_id, ours_entry.unwrap().mode))
}
}
// Both modified - content merge of the raw bytes (UTF-8, or one char per
// byte when any side is not valid UTF-8, so nothing is mangled).
let base_bytes = match base_id {
Some(id) => merge_get_blob_data(db, rfs, id)
None => Bytes::new(0)
}
let ours_bytes = merge_get_blob_data(db, rfs, ours_id)
let theirs_bytes = merge_get_blob_data(db, rfs, theirs_id)
let utf8 = merge_is_valid_utf8(base_bytes) &&
merge_is_valid_utf8(ours_bytes) &&
merge_is_valid_utf8(theirs_bytes)
let result = @diff3.content_merge(
merge_bytes_to_text(base_bytes, utf8),
merge_bytes_to_text(ours_bytes, utf8),
merge_bytes_to_text(theirs_bytes, utf8),
@diff3.ContentMergeOptions::default(),
)
let content_bytes = merge_text_to_bytes(result.content, utf8)
let (blob_id, compressed) = @bit.create_blob(content_bytes)
write_object_bytes(fs, git_dir, blob_id, compressed)
Some((blob_id, ours_entry.unwrap().mode))
}
///|
/// Create index stage entries for conflicts, including rename/rename(2to1) stages.
fn merge_conflicted_index_entries_with_renames(
db : ObjectDb,
fs : &@bit.RepoFileSystem,
base : Map[String, TreeFileEntry],
ours : Map[String, TreeFileEntry],
theirs : Map[String, TreeFileEntry],
merged : Map[String, TreeFileEntry],
conflicts : Array[String],
rename_conflict_stages : Map[String, (TreeFileEntry, TreeFileEntry)],
distinct_types? : Map[String, (String, Int)] = Map([]),
location_stages? : Map[String, (Int, TreeFileEntry)] = Map([]),
rename_sides? : Map[String, RenameMergeSides] = Map([]),
) -> Array[IndexStageEntry] raise @bit.GitError {
let out : Array[IndexStageEntry] = []
let conflict_set : Map[String, Bool] = Map([])
for path in conflicts {
conflict_set[path] = true
}
let merged_entries = tree_files_to_index(db, fs, merged)
for entry in merged_entries {
if !conflict_set.contains(entry.path) {
out.push({ entry, stage: 0 })
}
}
for path in conflicts {
// file location (directory rename): only the adding side's stage.
match location_stages.get(path) {
Some((stage, f)) => {
out.push({ entry: merge_tree_file_to_index_entry(db, fs, path, f), stage })
continue
}
None => ()
}
// distinct types: each side at its own path (keeper at `path`).
match (distinct_types.get(path), ours.get(path), theirs.get(path)) {
(Some((renamed, stage)), Some(o), Some(t)) => {
let (keeper, keeper_stage, regular) = if stage == 2 {
(t, 3, o)
} else {
(o, 2, t)
}
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, keeper),
stage: keeper_stage,
})
out.push({
entry: merge_tree_file_to_index_entry(db, fs, renamed, regular),
stage,
})
continue
}
_ => ()
}
// content conflict at a rename destination: the three sides' entries.
match rename_sides.get(path) {
Some(sides) if !rename_conflict_stages.contains(path) => {
match sides.base {
Some(b) =>
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, b),
stage: 1,
})
None => ()
}
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, sides.ours),
stage: 2,
})
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, sides.theirs),
stage: 3,
})
continue
}
_ => ()
}
match rename_conflict_stages.get(path) {
Some(stages) => {
// rename/rename(2to1): stage 2 = resolved ours, stage 3 = resolved theirs
let (ours_stage, theirs_stage) = stages
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, ours_stage),
stage: 2,
})
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, theirs_stage),
stage: 3,
})
}
None => {
// Standard conflict: base/ours/theirs at same path
match base.get(path) {
Some(info) =>
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, info),
stage: 1,
})
None => ()
}
match ours.get(path) {
Some(info) =>
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, info),
stage: 2,
})
None => ()
}
match theirs.get(path) {
Some(info) =>
out.push({
entry: merge_tree_file_to_index_entry(db, fs, path, info),
stage: 3,
})
None => ()
}
}
}
}
out
}
///|
/// Write a clean merge result over the worktree like git: only paths whose
/// content changes from `ours` are written, and paths `merged` drops are
/// removed (lstat); unstaged edits on untouched paths survive.
fn merge_write_changed_paths(
db : ObjectDb,
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
git_dir : String,
ours : Map[String, TreeFileEntry],
merged : Map[String, TreeFileEntry],
leave? : Map[String, Bool] = Map([]),
) -> Unit raise @bit.GitError {
// Sparse: skip-worktree and out-of-cone paths (and files `leave` names)
// are updated in the index only -- git does not write outside the cone.
let skip = read_skip_worktree_paths(rfs, git_dir)
for p, _ in leave {
skip[p] = true
}
if is_sparse_checkout_enabled(rfs, git_dir) {
let patterns = read_sparse_patterns(rfs, git_dir)
for path, _ in merged {
if !matches_sparse_pattern(path, patterns) {
skip[path] = true
}
}
for path, _ in ours {
if !matches_sparse_pattern(path, patterns) {
skip[path] = true
}
}
}
let emptied : Array[String] = []
for path, o in ours {
if merged.contains(path) ||
is_gitlink_mode_int(o.mode) ||
skip.contains(path) {
continue
}
let abs = join_path(root, path)
if @bitio.worktree_entry_meta_sync(rfs, abs) is Some(_) {
fs.remove_file(abs) catch {
_ => ()
}
}
// A file already gone still lets git prune its empty parents.
emptied.push(parent_dir(abs))
}
tree_ops_prune_empty_dirs(fs, rfs, root, emptied)
let changed : Map[String, TreeFileEntry] = Map([])
for path, f in merged {
if skip.contains(path) {
continue
}
match ours.get(path) {
Some(o) if o.id == f.id && o.mode == f.mode => ()
_ => changed[path] = f
}
}
write_worktree_from_files(db, fs, rfs, root, git_dir, changed)
}
///|
/// Write a merge-family result index, keeping the skip-worktree bit of
/// every entry that is still there (sparse checkouts).
fn merge_write_index_keeping_skip(
fs : &@bit.FileSystem,
rfs : &@bit.RepoFileSystem,
root : String,
git_dir : String,
entries : Array[IndexEntry],
) -> Unit raise @bit.GitError {
let skip = read_skip_worktree_paths(rfs, git_dir)
let sparse = is_sparse_checkout_enabled(rfs, git_dir)
if skip.length() == 0 && !sparse {
write_index_entries(fs, git_dir, entries)
return
}
let patterns = if sparse { read_sparse_patterns(rfs, git_dir) } else { [] }
let keep : Map[String, Bool] = Map([])
for e in entries {
if skip.contains(e.path) {
keep[e.path] = true
} else if sparse &&
!is_gitlink_mode_int(e.mode) &&
!matches_sparse_pattern(e.path, patterns) &&
@bitio.worktree_entry_meta_sync(rfs, join_path(root, e.path)) is None {
// An out-of-cone entry the merge did not write (a path it brings
// back or adds) is skip-worktree, as git's sparse checkout makes it.
keep[e.path] = true
}
}
write_index_entries_with_skip_worktree(fs, git_dir, entries, keep)
}
///|
/// merge-ort refuses to run when the index differs from HEAD at all.
fn merge_check_clean_index(
rfs : &@bit.RepoFileSystem,
git_dir : String,
ours : Map[String, TreeFileEntry],
restore? : (ObjectDb, &@bit.FileSystem, String),
) -> Unit raise @bit.GitError {
let changed : Map[String, Bool] = Map([])
let seen : Map[String, Bool] = Map([])
for e in read_index_entries(rfs, git_dir) {
seen[e.path] = true
match ours.get(e.path) {
Some(o) if o.id == e.id && o.mode == e.mode => ()
_ => changed[e.path] = true
}
}
for path, _ in ours {
if !seen.contains(path) {
changed[path] = true
}
}
if changed.length() > 0 {
// git still writes out staged files HEAD does not have that are missing
// from the worktree, even though it refuses the merge.
if restore is Some((db, fs, root)) {
let skip = read_skip_worktree_paths(rfs, git_dir)
let missing : Map[String, TreeFileEntry] = Map([])
for e in read_index_entries(rfs, git_dir) {
if !ours.contains(e.path) &&
!skip.contains(e.path) &&
!is_gitlink_mode_int(e.mode) &&
@bitio.worktree_entry_meta_sync(rfs, join_path(root, e.path)) is None {
missing[e.path] = { id: e.id, mode: e.mode }
}
}
if missing.length() > 0 {
write_worktree_from_files(db, fs, rfs, root, git_dir, missing) catch {
_ => ()
}
}
}
let paths = changed.keys().to_array()
paths.sort()
raise @bit.GitError::InvalidObject(
"Your local changes to the following files would be overwritten by merge:\n " +
paths.join(" ") +
"\nMerge with strategy ort failed.",
)
}
}
///|
/// Raise git's merge-ort error when the index differs from `head`'s tree.
pub fn merge_require_clean_index(
rfs : &@bit.RepoFileSystem,
git_dir : String,
head : @bit.ObjectId,
fs? : &@bit.FileSystem,
root? : String,
) -> Unit raise @bit.GitError {
let db = ObjectDb::load_lazy(rfs, resolve_common_git_dir(rfs, git_dir))
let restore = match (fs, root) {
(Some(f), Some(r)) => Some((db, f, r))
_ => None
}
merge_check_clean_index(
rfs,
git_dir,
collect_tree_files_from_commit(db, rfs, head),
restore?,
)
}
///|
/// Whether `data` is valid UTF-8 (so the text merge round-trips it).
fn merge_is_valid_utf8(data : Bytes) -> Bool {
let text = @utf8.decode(data[:]) catch { _ => return false }
@utf8.encode(text) == data
}
///|
/// Blob bytes as merge text: UTF-8 decoding, or one char per byte.
fn merge_bytes_to_text(data : Bytes, utf8 : Bool) -> String {
if utf8 {
return @utf8.decode_lossy(data[:])
}
let sb = StringBuilder()
for b in data {
sb.write_char(Int::unsafe_to_char(b.to_int()))
}
sb.to_string()
}
///|
/// Inverse of `merge_bytes_to_text`.
fn merge_text_to_bytes(text : String, utf8 : Bool) -> Bytes {
if utf8 {
return @utf8.encode(text)
}
let out : Array[Byte] = []
for c in text {
let code = c.to_int()
if code < 256 {
out.push(code.to_byte())
} else {
// Only marker text / labels can be outside Latin-1: keep them UTF-8.
for b in @utf8.encode(c.to_string()) {
out.push(b)
}
}
}
Bytes::from_array(out)
}
///|
/// Three-way merge of a file mode: a side that changed it from the base
/// wins (ours if both did).
fn merge_three_way_mode(
base : Int?,
ours : Int?,
theirs : Int?,
fallback : Int,
) -> Int {
match (base, ours, theirs) {
(Some(b), Some(o), Some(t)) => if o == b { t } else { o }
(_, Some(o), _) => o
(_, _, Some(t)) => t
_ => fallback
}
}
///|
/// The MERGE_MSG git writes after a conflicted merge / cherry-pick /
/// revert: the message, then a "# Conflicts:" list of the unmerged paths
/// in index order (`commit --no-edit` keeps it, an editor strips it).
fn merge_msg_with_conflicts(
rfs : &@bit.RepoFileSystem,
git_dir : String,
message : String,
) -> String {
let paths = read_unmerged_paths(rfs, git_dir).keys().collect()
if paths.length() == 0 {
return message
}
paths.sort_by(index_path_compare_git_order)
let sb = StringBuilder::new()
sb.write_string(message)
if !message.has_suffix("\n") {
sb.write_string("\n")
}
sb.write_string("\n# Conflicts:\n")
for p in paths {
sb.write_string("#\t" + p + "\n")
}
sb.to_string()
}