navid/veins / commit
f23cf6101027
Navid M <navidmomtahen@gmail.com> · 2026-11-26
parents: 769f9e10aacf
Browse files at this commit · Download source
--- a/veins/src/cli/help_cmd.sx+++ b/veins/src/cli/help_cmd.sx@@ -21,9 +21,14 @@ stdio.puts(" log show commit history") stdio.puts(" show show a commit and its diff") stdio.puts(" diff show a unified diff")+ stdio.puts(" merge create a merge commit; never fails")+ stdio.puts(" rebase rewrite changes onto a new parent")+ stdio.puts(" conflicts list conflicted paths")+ stdio.puts(" resolve resolve a conflicted path") stdio.puts(" new start a new change") stdio.puts(" bmk manage named branch pointers") stdio.puts(" rm untrack paths, keeping files on disk by default")+ stdio.puts(" mv move a tracked file and record the rename") stdio.puts(" ex add paths or globs to .vnexclude") stdio.puts(" desc set the working-copy commit message; alias: describe") stdio.puts(" go describe and start a new change; alias: commit")@@ -113,6 +118,41 @@ stdio.puts("usage: vn version") stdio.puts("") stdio.puts("print version information")+}++fn show_merge() void = trust {+ stdio.puts("usage: vn merge <rev>...")+ stdio.puts("")+ stdio.puts("create a merge commit from the working-copy commit and the revisions")+ stdio.puts("the merge never fails; conflicts are stored as conflict values")+}++fn show_rebase() void = trust {+ stdio.puts("usage: vn rebase -s <rev> -d <rev>")+ stdio.puts("")+ stdio.puts("rewrite the source change and its descendants onto the destination")+ stdio.puts("")+ stdio.puts("options:")+ stdio.puts(" -s, -source <rev> first change to rewrite")+ stdio.puts(" -d, -destination <rev> new parent")+}++fn show_conflicts() void = trust {+ stdio.puts("usage: vn conflicts [-porcelain]")+ stdio.puts("")+ stdio.puts("list conflicted paths and, for text conflicts, conflicting line ranges")+ stdio.puts("")+ stdio.puts("porcelain columns (tab-separated):")+ stdio.puts(" path, kind, base-ranges, ours-ranges, theirs-ranges")+}++fn show_resolve() void = trust {+ stdio.puts("usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...")+ stdio.puts(" vn resolve -list")+ stdio.puts("")+ stdio.puts("resolve conflicted paths. Without -take, the current file content is")+ stdio.puts("recorded as the resolution. -tool substitutes $BASE, $OURS, $THEIRS,")+ stdio.puts("and $OUTPUT in the command.") } fn show_status() void = trust {@@ -192,6 +232,12 @@ stdio.puts("usage: vn new [<rev>...]") stdio.puts("") stdio.puts("start a new empty change on top of the working copy or a revision")+}++fn show_mv() void = trust {+ stdio.puts("usage: vn mv <from> <to>")+ stdio.puts("")+ stdio.puts("move a tracked file; the following snapshot records the rename") } fn show_rm() void = trust {@@ -305,6 +351,22 @@ } if cmd_is(cmd, c"diff", 4) { show_diff()+ return 0+ }+ if cmd_is(cmd, c"merge", 5) {+ show_merge()+ return 0+ }+ if cmd_is(cmd, c"rebase", 6) {+ show_rebase()+ return 0+ }+ if cmd_is(cmd, c"conflicts", 9) {+ show_conflicts()+ return 0+ }+ if cmd_is(cmd, c"resolve", 7) {+ show_resolve() return 0 } if cmd_is(cmd, c"bmk", 3) {@@ -317,6 +379,10 @@ } if cmd_is(cmd, c"rm", 2) { show_rm()+ return 0+ }+ if cmd_is(cmd, c"mv", 2) {+ show_mv() return 0 } if cmd_is(cmd, c"ex", 2) {--- /dev/null+++ b/veins/src/cli/merge_cmd.sx@@ -0,0 +1,700 @@+/// `vn merge` and `vn rebase`.+///+/// A merge never fails: it records a commit whose tree may contain conflict+/// entries. Rebase rewrites the source and all descendants in one operation.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val random = use("std/crypto/random")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val commit = use("../object/commit.sx")+val graph = use("../object/graph.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val txnmod = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val view = use("../object/view.sx")+val identity = use("../core/identity.sx")+val repoconfig = use("../core/repoconfig.sx")+val snapshot = use("../worktree/snapshot.sx")+val checkout = use("../worktree/checkout.sx")+val gitmap = use("../git/map.sx")+val object = use("../git/object.sx")+val files = use("../io/files.sx")+val rename = use("../merge/rename.sx")+val engine = use("../merge/engine.sx")+val treemerge = use("../merge/treemerge.sx")++type GitSource = {+ repo: mut object.GitRepo+ open: mut bool+}++fn open_git(repo: layout.Repo) GitSource = trust {+ val p: str.StringView = layout.git_dir(repo)+ val r = object.open(p)+ val g: mut GitSource = GitSource{repo: @zeroed, open: false}+ match r {+ ok x => {+ g.repo = x+ g.open = true+ }+ err _ => {+ files.free_path(p)+ }+ }+ return g+}++fn close_git(g: mut GitSource) void = trust {+ if g.open {+ object.free(g.repo)+ g.open = false+ }+}++fn adjacent_config(repo: layout.Repo) bool = trust {+ val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))+ if v is some value {+ val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))+ files.free_buffer(value)+ return on+ }+ return false+}++fn copy_id(id: objid.Id) objid.Id = trust {+ if id.ptr == none {+ return objid.id(none)+ }+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn free_id(id: objid.Id) void = trust {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+}++fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {+ for x in ids {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++fn mapped(+ old_ids: list[objid.Id],+ new_ids: list[objid.Id],+ id: objid.Id+) option[objid.Id] = trust {+ val i: mut usize = 0+ for i < @len(old_ids) {+ val o = @get(old_ids, i)+ if o is some old {+ if objid.Id.eql(old, id) {+ val n = @get(new_ids, i)+ if n is some nid {+ return some nid+ }+ }+ }+ i+++ }+ return none+}++fn mapped_tree(+ old_ids: list[objid.Id],+ new_trees: list[objid.Id],+ id: objid.Id+) option[objid.Id] = trust {+ val i: mut usize = 0+ for i < @len(old_ids) {+ val o = @get(old_ids, i)+ if o is some old {+ if objid.Id.eql(old, id) {+ val t = @get(new_trees, i)+ if t is some tid {+ return some tid+ }+ }+ }+ i+++ }+ return none+}++fn append_tree(out: mut list[objid.Id], t: option[objid.Id]) void = trust {+ if t is some tid {+ @append(out, copy_id(tid))+ } else {+ @append(out, objid.id(none))+ }+}++fn text_args(revs: list[bytes.Bytes]) bytes.Bytes = trust {+ val b: mut buf.Buf = buf.new(64)+ val i: mut usize = 0+ for i < @len(revs) {+ if i > 0 {+ buf.Buf.put_u8(b, 32)+ }+ val o = @get(revs, i)+ if o is some v {+ buf.Buf.put_bytes(b, v)+ }+ i+++ }+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn desc_with_rerere(prefix: bytes.Bytes, rerere: usize) bytes.Bytes = trust {+ if rerere == 0 {+ return bytes.Bytes.dup(prefix)+ }+ val b: mut buf.Buf = buf.new(prefix.len + 32)+ buf.Buf.put_bytes(b, prefix)+ buf.Buf.put_bytes(b, bytes.from_cstr(c" (rerere"))+ // A decimal via formatting keeps the description textual.+ val tmp: ref u8 = @fmtalloc(" {d})", {rerere})+ buf.Buf.put_bytes(b, bytes.from_cstr(tmp))+ @free(tmp as ref void)+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}++fn exact_renames_for_parents(+ tx: ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ parents: list[objid.Id],+ merged_tree: objid.Id+) list[ref commit.Rename] = trust {+ val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val i: mut usize = 0+ for i < @len(parents) {+ val p = @get(parents, i)+ if p is some pid {+ val pt = engine.tree_of(handles, pid)+ val rs = rename.detect_tx(+ handles,+ git,+ has_git,+ pt,+ some merged_tree,+ 0,+ i as u64,+ tx+ )+ for r in rs {+ @append(out, r)+ }+ @listfree(rs)+ if pt is some tid {+ free_id(tid)+ }+ }+ i+++ }+ return out+}++fn make_commit(+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ repo: layout.Repo,+ parents: list[objid.Id],+ root: objid.Id,+ change: objid.ChangeId,+ author: prim.Sig,+ message: bytes.Bytes,+ renames_state: u8,+ extra: list[ref prim.KeyValue]+) objid.Id = trust {+ val sig: prim.Sig = identity.signature(repo)+ val parents_copy: mut list[objid.Id] = lists.new[objid.Id]()+ for p in parents {+ @append(parents_copy, copy_id(p))+ }+ val renames: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ if renames_state == commit.RENAMES_RECORDED {+ val detected: list[ref commit.Rename] = exact_renames_for_parents(+ tx,+ handles,+ git,+ has_git,+ parents,+ root+ )+ for r in detected {+ @append(renames, r)+ }+ @listfree(detected)+ }+ val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ nc.version = 1+ nc.parents = parents_copy+ nc.root_tree = copy_id(root)+ nc.change_id = change+ nc.author = author+ nc.committer = sig+ nc.message = message+ nc.renames_state = renames_state+ nc.renames = renames+ nc.extra = extra+ val body: bytes.Bytes = commit.encode(nc)+ val id: objid.Id = txnmod.add_object(tx, types.COMMIT, body)+ @listfree(parents_copy)+ for e in renames {+ if e.from_path.ptr != none {+ val fp: mut ref void = e.from_path.ptr as ref void+ @free(fp)+ }+ if e.to_path.ptr != none {+ val tp: mut ref void = e.to_path.ptr as ref void+ @free(tp)+ }+ val rp: mut ref void = e as ref void+ @free(rp)+ }+ @listfree(renames)+ free_id(nc.root_tree)+ @free(nc as ref void)+ identity.free_sig(sig)+ return id+}++pub fn merge(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {+ if @len(revs) == 0 {+ msg.error_prefix()+ stdio.eprint("merge requires at least one revision\n", {})+ return 1+ }+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val tx_opt = txnmod.begin(repo)+ val tx: mut ref txnmod.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ }+ txnmod.enable_chunk_cache(tx)+ val st: store.Store = store.open_all(repo)+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ if wc_opt is some id {+ wc = id+ }+ if objid.Id.is_none(wc) {+ msg.error_prefix()+ stdio.eprint("no working-copy commit to merge into\n", {})+ store.close(st)+ txnmod.abort(tx)+ return 1+ }+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ @append(parents, copy_id(wc))+ val i: mut usize = 0+ val failed: mut bool = false+ for i < @len(revs) {+ val o = @get(revs, i)+ val rev: mut bytes.Bytes = bytes.empty()+ if o is some v {+ rev = v+ }+ val resolved = graph.resolve(st.handles, tx.view, rev)+ if resolved is some rid {+ if objid.Id.eql(rid, wc) {+ msg.error_prefix()+ stdio.eprint("cannot merge a commit with itself\n", {})+ failed = true+ } else {+ @append(parents, copy_id(rid))+ }+ } else {+ failed = true+ }+ i+++ }+ if failed {+ msg.error_prefix()+ stdio.eprint("unknown revision\n", {})+ graph.free_ids(parents)+ store.close(st)+ txnmod.abort(tx)+ return 1+ }+ val old_root: option[objid.Id] = engine.tree_of(st.handles, wc)+ val git: mut GitSource = open_git(repo)+ val outcome: treemerge.Outcome = engine.merge_many(+ repo,+ tx,+ st.handles,+ git.repo,+ git.open,+ parents,+ adjacent_config(repo)+ )+ val cid: ref u8 = @alloc(16) as ref u8+ random.random_bytes(cid as ref void, 16)+ val author: prim.Sig = identity.signature(repo)+ val renames_state: u8 = commit.RENAMES_RECORDED+ val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val new_id: objid.Id = make_commit(+ tx,+ st.handles,+ git.repo,+ git.open,+ repo,+ parents,+ outcome.tree,+ objid.change_id(cid),+ author,+ bytes.empty(),+ renames_state,+ extra+ )+ viewops.remove_head(tx.view, wc)+ viewops.move_bookmarks(tx.view, wc, new_id)+ viewops.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ val desc_text: bytes.Bytes = text_args(revs)+ val b: mut buf.Buf = buf.new(32)+ buf.Buf.put_raw(b, c"merge", 5)+ if desc_text.len > 0 {+ buf.Buf.put_u8(b, 32)+ buf.Buf.put_bytes(b, desc_text)+ }+ val desc: bytes.Bytes = desc_with_rerere(buf.Buf.view(b), outcome.rerere)+ val status: i32 = txnmod.finish(tx, desc)+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_id)+ if old_root is some oroot {+ val st2: store.Store = store.open_all(repo)+ val ms: i32 = checkout.materialize_commit(repo, st2.handles, some oroot, outcome.tree)+ store.close(st2)+ if ms != 0 {+ store.close(st)+ close_git(git)+ @listfree(parents)+ @listfree(extra)+ free_id(new_id)+ free_id(outcome.tree)+ free_id(wc)+ free_id(oroot)+ @free(cid as ref void)+ identity.free_sig(author)+ buf.Buf.free(b)+ return ms+ }+ }+ }+ store.close(st)+ close_git(git)+ @listfree(parents)+ @listfree(extra)+ free_id(new_id)+ free_id(outcome.tree)+ free_id(wc)+ if old_root is some oroot2 {+ free_id(oroot2)+ }+ @free(cid as ref void)+ identity.free_sig(author)+ buf.Buf.free(b)+ return status+}++fn map_list(+ old_ids: list[objid.Id],+ new_ids: list[objid.Id],+ ids: mut list[objid.Id]+) void = trust {+ val i: mut usize = 0+ for i < @len(ids) {+ val o = @get(ids, i)+ if o is some id {+ val m = mapped(old_ids, new_ids, id)+ if m is some nid {+ @set(ids, i, copy_id(nid))+ }+ }+ i+++ }+}++fn remap_view(+ v: ref view.View,+ old_ids: list[objid.Id],+ new_ids: list[objid.Id]+) void = trust {+ for bm in v.bookmarks {+ val bmm: mut ref view.Bookmark = bm+ map_list(old_ids, new_ids, bmm.targets.adds)+ map_list(old_ids, new_ids, bmm.targets.removes)+ }+ for t in v.tags {+ val tm: mut ref view.TagRef = t+ val m = mapped(old_ids, new_ids, tm.target)+ if m is some nid {+ tm.target = copy_id(nid)+ }+ }+ val i: mut usize = 0+ for i < @len(v.working_copies) {+ val o = @get(v.working_copies, i)+ if o is some w {+ val m2 = mapped(old_ids, new_ids, w.target)+ if m2 is some nid2 {+ w.target = copy_id(nid2)+ }+ }+ i+++ }+}++pub fn rebase(repo: layout.Repo, source: bytes.Bytes, dest: bytes.Bytes) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val tx_opt = txnmod.begin(repo)+ val tx: mut ref txnmod.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ }+ txnmod.enable_chunk_cache(tx)+ val st: store.Store = store.open_all(repo)+ val src_opt = graph.resolve(st.handles, tx.view, source)+ val dst_opt = graph.resolve(st.handles, tx.view, dest)+ val src: mut objid.Id = objid.id_none()+ val dst: mut objid.Id = objid.id_none()+ if src_opt is some s {+ src = copy_id(s)+ }+ if dst_opt is some d {+ dst = copy_id(d)+ }+ if objid.Id.is_none(src) || objid.Id.is_none(dst) {+ msg.error_prefix()+ stdio.eprint("unknown revision\n", {})+ store.close(st)+ txnmod.abort(tx)+ return 1+ }+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ if wc_opt is some wid {+ wc = wid+ }+ val old_wc_root: mut option[objid.Id] = none+ if !objid.Id.is_none(wc) {+ old_wc_root = engine.tree_of(st.handles, wc)+ }++ val all: list[objid.Id] = graph.all(st.handles, tx.view)+ val set: mut list[objid.Id] = lists.new[objid.Id]()+ for c in all {+ if engine.is_ancestor(st.handles, src, c) {+ @append(set, copy_id(c))+ }+ }+ val git: mut GitSource = open_git(repo)+ val old_ids: mut list[objid.Id] = lists.new[objid.Id]()+ val new_ids: mut list[objid.Id] = lists.new[objid.Id]()+ val new_tree_ids: mut list[objid.Id] = lists.new[objid.Id]()+ val remaining: mut list[objid.Id] = lists.new[objid.Id]()+ for c in set {+ @append(remaining, copy_id(c))+ }+ val rerere_total: mut usize = 0+ for @len(remaining) > 0 {+ val ready_idx: mut i32 = -1+ val ri: mut usize = 0+ for ri < @len(remaining) {+ val ro = @get(remaining, ri)+ if ro is some cid {+ val parents = engine.parents_of(st.handles, cid)+ val ready: mut bool = true+ for p in parents {+ if contains(set, p) && !contains(old_ids, p) && !objid.Id.eql(cid, src) {+ ready = false+ }+ }+ graph.free_ids(parents)+ if ready {+ ready_idx = ri as i32+ break+ }+ }+ ri+++ }+ if ready_idx < 0 {+ msg.error_prefix()+ stdio.eprint("rebase could not order commits\n", {})+ break+ }+ val chosen_o = @get(remaining, ready_idx as usize)+ val chosen: mut objid.Id = objid.id_none()+ if chosen_o is some c {+ chosen = c+ }+ // Rewrite one commit.+ val lc_opt = graph.load_commit(st.handles, chosen)+ if lc_opt is none {+ break+ }+ val lc: mut ref graph.LoadedCommit = none+ if lc_opt is some l {+ lc = l+ }+ val new_parents: mut list[objid.Id] = lists.new[objid.Id]()+ val new_parent_trees: mut list[objid.Id] = lists.new[objid.Id]()+ val pi: mut usize = 0+ for pi < @len(lc.c.parents) {+ val po = @get(lc.c.parents, pi)+ if po is some p {+ if pi == 0 && objid.Id.eql(chosen, src) {+ @append(new_parents, copy_id(dst))+ append_tree(new_parent_trees, engine.tree_of(st.handles, dst))+ } else {+ val m = mapped(old_ids, new_ids, p)+ if m is some nid {+ @append(new_parents, copy_id(nid))+ val mt = mapped_tree(old_ids, new_tree_ids, p)+ if mt is some tid {+ @append(new_parent_trees, copy_id(tid))+ } else {+ append_tree(new_parent_trees, engine.tree_of(st.handles, p))+ }+ } else {+ @append(new_parents, copy_id(p))+ append_tree(new_parent_trees, engine.tree_of(st.handles, p))+ }+ }+ }+ pi+++ }+ if @len(lc.c.parents) == 0 {+ @append(new_parents, copy_id(dst))+ append_tree(new_parent_trees, engine.tree_of(st.handles, dst))+ }+ val outcome = engine.rewrite_tree(+ repo,+ tx,+ st.handles,+ git.repo,+ git.open,+ chosen,+ lc.c.root_tree,+ lc.c.parents,+ new_parents,+ new_parent_trees,+ adjacent_config(repo)+ )+ rerere_total = rerere_total + outcome.rerere+ val new_id: objid.Id = make_commit(+ tx,+ st.handles,+ git.repo,+ git.open,+ repo,+ new_parents,+ outcome.tree,+ lc.c.change_id,+ lc.c.author,+ lc.c.message,+ lc.c.renames_state,+ lc.c.extra+ )+ @append(old_ids, copy_id(chosen))+ @append(new_ids, copy_id(new_id))+ @append(new_tree_ids, copy_id(outcome.tree))+ graph.free_loaded(lc)+ graph.free_ids(new_parent_trees)+ @listfree(new_parents)+ free_id(outcome.tree)+ free_id(new_id)+ // Remove the processed commit.+ val removed = @remove(remaining, ready_idx as usize)+ if removed is some rid {+ val _ = rid+ }+ }+ remap_view(tx.view, old_ids, new_ids)+ viewops.rebuild_heads(tx.view)+ val prefix: mut buf.Buf = buf.new(64)+ buf.Buf.put_raw(prefix, c"rebase ", 7)+ buf.Buf.put_bytes(prefix, source)+ buf.Buf.put_raw(prefix, c" onto ", 6)+ buf.Buf.put_bytes(prefix, dest)+ val desc: bytes.Bytes = desc_with_rerere(buf.Buf.view(prefix), rerere_total)+ val status: mut i32 = txnmod.finish(tx, desc)+ if status == 0 {+ for nid in new_ids {+ val _ = gitmap.mark_native(repo, nid)+ }+ val mapped_wc = mapped(old_ids, new_ids, wc)+ if mapped_wc is some nwc {+ val st2: store.Store = store.open_all(repo)+ val nr = engine.tree_of(st2.handles, nwc)+ if nr is some new_root {+ val ms: i32 = checkout.materialize_commit(repo, st2.handles, old_wc_root, new_root)+ if ms != 0 {+ status = ms+ }+ free_id(new_root)+ }+ store.close(st2)+ }+ }+ store.close(st)+ close_git(git)+ graph.free_ids(all)+ graph.free_ids(set)+ graph.free_ids(old_ids)+ graph.free_ids(new_ids)+ graph.free_ids(new_tree_ids)+ graph.free_ids(remaining)+ free_id(src)+ free_id(dst)+ free_id(wc)+ if old_wc_root is some owr {+ free_id(owr)+ }+ buf.Buf.free(prefix)+ return status+}--- /dev/null+++ b/veins/src/cli/mv_cmd.sx@@ -0,0 +1,136 @@+/// `vn mv`: move a tracked file. The following snapshot records the rename.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val stat = use("../io/stat.sx")+val pathspec = use("../worktree/pathspec.sx")+val snapshot = use("../worktree/snapshot.sx")++fn normalize(repo: layout.Repo, arg: bytes.Bytes) option[bytes.Bytes] = trust {+ val cwd_opt = pathspec.cwd_relative(repo.root)+ val cwd: mut bytes.Bytes = bytes.empty()+ if cwd_opt is some c {+ cwd = c+ }+ val norm = pathspec.normalize(repo.root, cwd, arg)+ if cwd_opt is some c2 {+ files.free_buffer(c2)+ }+ return norm+}++fn parent_of(path: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = path.len+ for i > 0 {+ if bytes.Bytes.at(path, i - 1) == 47 {+ return bytes.Bytes.slice(path, 0, i - 1)+ }+ i--+ }+ return bytes.empty()+}++pub fn run(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ if @len(args) != 2 {+ msg.error_prefix()+ stdio.eprint("mv requires a source and a destination\n", {})+ return 1+ }+ val src_o = @get(args, 0)+ val dst_o = @get(args, 1)+ val src_arg: mut bytes.Bytes = bytes.empty()+ val dst_arg: mut bytes.Bytes = bytes.empty()+ if src_o is some s {+ src_arg = s+ }+ if dst_o is some d {+ dst_arg = d+ }+ val src_n = normalize(repo, src_arg)+ val dst_n = normalize(repo, dst_arg)+ if src_n is none {+ msg.error_prefix()+ stdio.eprint("invalid path\n", {})+ return 1+ }+ if dst_n is none {+ msg.error_prefix()+ stdio.eprint("invalid path\n", {})+ return 1+ }+ val src: mut bytes.Bytes = bytes.empty()+ val dst: mut bytes.Bytes = bytes.empty()+ if src_n is some s2 {+ src = s2+ }+ if dst_n is some d2 {+ dst = d2+ }+ val src_abs: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(src)+ )+ val dst_abs: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(dst)+ )+ val src_info = stat.read(src_abs)+ if src_info is none {+ msg.error_prefix()+ stdio.eprint(+ "not a tracked path: {s}\n",+ {str.view(src.ptr, src.len as i64)}+ )+ files.free_path(src_abs)+ files.free_path(dst_abs)+ files.free_buffer(src)+ files.free_buffer(dst)+ return 1+ }+ val dst_info = stat.read(dst_abs)+ if dst_info is some di {+ if di.kind != stat.KIND_MISSING {+ msg.error_prefix()+ stdio.eprint(+ "destination already exists: {s}\n",+ {str.view(dst.ptr, dst.len as i64)}+ )+ files.free_path(src_abs)+ files.free_path(dst_abs)+ files.free_buffer(src)+ files.free_buffer(dst)+ return 1+ }+ }+ val parent: bytes.Bytes = parent_of(dst)+ if parent.len > 0 {+ val parent_abs: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(parent)+ )+ val _ = files.mkdir_all(parent_abs)+ files.free_path(parent_abs)+ }+ val moved: bool = files.rename_path(src_abs, dst_abs)+ files.free_path(src_abs)+ files.free_path(dst_abs)+ files.free_buffer(src)+ files.free_buffer(dst)+ if !moved {+ msg.error_prefix()+ stdio.eprint("cannot move path\n", {})+ return 1+ }+ return snapshot.run(repo)+}--- /dev/null+++ b/veins/src/cli/resolve_cmd.sx@@ -0,0 +1,784 @@+/// `vn conflicts` and `vn resolve`.++val str = use("std/string")+val stdio = use("std/stdio")+val msg = use("../core/msg.sx")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val prim = use("../core/primitives.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val conflict = use("../object/conflict.sx")+val blob = use("../object/blob.sx")+val graph = use("../object/graph.sx")+val treewalk = use("../object/treewalk.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val layout = use("../store/layout.sx")+val txnmod = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val view = use("../object/view.sx")+val identity = use("../core/identity.sx")+val repoconfig = use("../core/repoconfig.sx")+val files = use("../io/files.sx")+val stat = use("../io/stat.sx")+val pathspec = use("../worktree/pathspec.sx")+val snapshot = use("../worktree/snapshot.sx")+val checkout = use("../worktree/checkout.sx")+val treeedit = use("../worktree/treeedit.sx")+val object = use("../git/object.sx")+val raw = use("../object/raw.sx")+val filemerge = use("../merge/filemerge.sx")+val resolutions = use("../merge/resolutions.sx")++extern (C) fn system(command: ref u8) i32 = "system"++type GitSource = {+ repo: mut object.GitRepo+ open: mut bool+}++fn open_git(repo: layout.Repo) GitSource = trust {+ val p: str.StringView = layout.git_dir(repo)+ val r = object.open(p)+ val g: mut GitSource = GitSource{repo: @zeroed, open: false}+ match r {+ ok x => {+ g.repo = x+ g.open = true+ }+ err _ => {+ files.free_path(p)+ }+ }+ return g+}++fn close_git(g: mut GitSource) void = trust {+ if g.open {+ object.free(g.repo)+ g.open = false+ }+}++fn adjacent_config(repo: layout.Repo) bool = trust {+ val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))+ if v is some value {+ val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))+ files.free_buffer(value)+ return on+ }+ return false+}++fn copy_id(id: objid.Id) objid.Id = trust {+ if id.ptr == none {+ return objid.id(none)+ }+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn free_id(id: objid.Id) void = trust {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+}++fn wc_tree(+ handles: list[ref store.Handle],+ v: ref view.View+) option[objid.Id] = trust {+ val wc_opt = viewops.working_copy(v)+ val out: mut option[objid.Id] = none+ if wc_opt is some wc {+ val lc_opt = graph.load_commit(handles, wc)+ if lc_opt is some lc {+ out = some(graph.copy_id(lc.c.root_tree))+ graph.free_loaded(lc)+ }+ free_id(wc)+ }+ return out+}++fn load_conflict(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref conflict.Conflict] = trust {+ val body_opt = state.read_body(handles, id, types.CONFLICT)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = conflict.decode(body)+ val out: mut option[ref conflict.Conflict] = none+ match decoded {+ ok c => {+ out = some c+ }+ err _ => {+ }+ }+ if out is none {+ files.free_buffer(body)+ }+ return out+}++fn kind_label(c: ref conflict.Conflict) str.StringView = trust {+ for v in c.adds {+ if v.kind == tree.KIND_SUBTREE {+ return str.from_cstr(c"tree")+ }+ }+ for v in c.removes {+ if v.kind == tree.KIND_SUBTREE {+ return str.from_cstr(c"tree")+ }+ }+ for v in c.adds {+ if v.kind == 0 {+ return str.from_cstr(c"delete/modify")+ }+ }+ for v in c.removes {+ if v.kind == 0 {+ return str.from_cstr(c"delete/modify")+ }+ }+ return str.from_cstr(c"text")+}++type ConflictItem = {+ path: mut bytes.Bytes+ target: mut objid.Id+}++fn collect(+ handles: list[ref store.Handle],+ tree_id: objid.Id+) list[ref ConflictItem] = trust {+ val out: mut list[ref ConflictItem] = lists.new[ref ConflictItem]()+ val flat: list[ref treewalk.FlatEntry] = treewalk.flatten(handles, tree_id)+ for e in flat {+ if e.kind == tree.KIND_CONFLICT {+ val ci: mut ref ConflictItem = @alloc(@sizeof(ConflictItem)) as ref ConflictItem+ ci.path = bytes.Bytes.dup(e.path)+ ci.target = copy_id(e.target)+ @append(out, ci)+ }+ }+ treewalk.free_flat(flat)+ return out+}++fn free_items(xs: list[ref ConflictItem]) void = trust {+ for x in xs {+ if x.path.ptr != none {+ val pp: mut ref void = x.path.ptr as ref void+ @free(pp)+ }+ free_id(x.target)+ val xp: mut ref void = x as ref void+ @free(xp)+ }+ @listfree(xs)+}++fn print_range(a: usize, b: usize) void = trust {+ if a == b {+ stdio.print("{d}", {a + 1})+ } else {+ stdio.print("{d}-{d}", {a + 1, b})+ }+}++fn ranges_of(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ c: ref conflict.Conflict,+ adjacent: bool+) option[filemerge.EditResult] = trust {+ if @len(c.adds) != 2 || @len(c.removes) != 1 {+ return none+ }+ val a0 = @get(c.adds, 0)+ val a1 = @get(c.adds, 1)+ val r0 = @get(c.removes, 0)+ if a0 is some ours {+ if a1 is some theirs {+ if r0 is some base {+ if ours.kind == 0 || theirs.kind == 0 || base.kind == 0 {+ return none+ }+ if ours.kind == tree.KIND_SUBTREE+ || theirs.kind == tree.KIND_SUBTREE+ || base.kind == tree.KIND_SUBTREE {+ return none+ }+ return filemerge.merge_blobs(+ handles,+ git,+ has_git,+ base.target,+ ours.target,+ theirs.target,+ adjacent+ )+ }+ }+ }+ return none+}++pub fn conflicts(repo: layout.Repo, porcelain: bool) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val st: store.Store = store.open_all(repo)+ val v_opt = state.current_view(repo, st.handles)+ val v: mut ref view.View = none+ if v_opt is some x {+ v = x+ } else {+ msg.error_prefix()+ stdio.eprint("no operation state\n", {})+ store.close(st)+ return 1+ }+ val tree_opt = wc_tree(st.handles, v)+ val items: mut list[ref ConflictItem] = lists.new[ref ConflictItem]()+ if tree_opt is some tid {+ items = collect(st.handles, tid)+ free_id(tid)+ }+ val git: mut GitSource = open_git(repo)+ val adjacent: bool = adjacent_config(repo)+ val first: mut bool = true+ for it in items {+ val c_opt = load_conflict(st.handles, it.target)+ if c_opt is some c {+ if porcelain {+ stdio.print("{s}\t", {str.view(it.path.ptr, it.path.len as i64)})+ stdio.print("{s}\t", {kind_label(c)})+ val rr = ranges_of(st.handles, git.repo, git.open, c, adjacent)+ if rr is some r {+ val i: mut usize = 0+ for i < @len(r.ranges) {+ val x = @get(r.ranges, i)+ if x is some range {+ if i > 0 {+ stdio.print(",", {})+ }+ print_range(range.base_start, range.base_end)+ }+ i+++ }+ stdio.print("\t", {})+ val j: mut usize = 0+ for j < @len(r.ranges) {+ val x2 = @get(r.ranges, j)+ if x2 is some range2 {+ if j > 0 {+ stdio.print(",", {})+ }+ print_range(range2.ours_start, range2.ours_end)+ }+ j+++ }+ stdio.print("\t", {})+ val k: mut usize = 0+ for k < @len(r.ranges) {+ val x3 = @get(r.ranges, k)+ if x3 is some range3 {+ if k > 0 {+ stdio.print(",", {})+ }+ print_range(range3.theirs_start, range3.theirs_end)+ }+ k+++ }+ filemerge.free_edit(r)+ } else {+ stdio.print("\t\t", {})+ }+ stdio.print("\n", {})+ } else {+ stdio.print(+ "{s}: {s} conflict",+ {str.view(it.path.ptr, it.path.len as i64), kind_label(c)}+ )+ val rr2 = ranges_of(st.handles, git.repo, git.open, c, adjacent)+ if rr2 is some r2 {+ if @len(r2.ranges) > 0 {+ stdio.print(" (", {})+ val i2: mut usize = 0+ for i2 < @len(r2.ranges) {+ val x4 = @get(r2.ranges, i2)+ if x4 is some range4 {+ if i2 > 0 {+ stdio.print(", ", {})+ }+ stdio.print("base ", {})+ print_range(range4.base_start, range4.base_end)+ stdio.print(", ours ", {})+ print_range(range4.ours_start, range4.ours_end)+ stdio.print(", theirs ", {})+ print_range(range4.theirs_start, range4.theirs_end)+ }+ i2+++ }+ stdio.print(")", {})+ }+ filemerge.free_edit(r2)+ }+ stdio.print("\n", {})+ }+ conflict.free_conflict(c)+ first = false+ }+ }+ if first {+ msg.info_prefix()+ stdio.print("no conflicts\n", {})+ }+ close_git(git)+ free_items(items)+ view.free_view(v)+ store.close(st)+ return 0+}++fn normalize(+ repo: layout.Repo,+ arg: bytes.Bytes+) option[bytes.Bytes] = trust {+ val cwd_opt = pathspec.cwd_relative(repo.root)+ val cwd: mut bytes.Bytes = bytes.empty()+ if cwd_opt is some c {+ cwd = c+ }+ val norm = pathspec.normalize(repo.root, cwd, arg)+ if cwd_opt is some c2 {+ files.free_buffer(c2)+ }+ return norm+}++fn delete_sidecar(repo: layout.Repo, base_path: bytes.Bytes, suffix: bytes.Bytes) void = trust {+ val full: mut buf.Buf = buf.new(base_path.len + suffix.len + 1)+ buf.Buf.put_bytes(full, base_path)+ buf.Buf.put_bytes(full, suffix)+ val rel: bytes.Bytes = buf.Buf.view(full)+ val abs: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(rel)+ )+ val _ = files.delete(abs)+ files.free_path(abs)+ buf.Buf.free(full)+}++fn delete_sidecars(repo: layout.Repo, path: bytes.Bytes) void = trust {+ delete_sidecar(repo, path, bytes.bytes(c".base", 5))+ delete_sidecar(repo, path, bytes.bytes(c".ours", 5))+ delete_sidecar(repo, path, bytes.bytes(c".theirs", 7))+ val n: mut usize = 2+ for n <= 64 {+ val suffix: ref u8 = @fmtalloc(".base{d}", {n})+ delete_sidecar(repo, path, bytes.from_cstr(suffix))+ val sp: mut ref void = suffix as ref void+ @free(sp)+ val suffix2: ref u8 = @fmtalloc(".theirs{d}", {n})+ delete_sidecar(repo, path, bytes.from_cstr(suffix2))+ val sp2: mut ref void = suffix2 as ref void+ @free(sp2)+ n+++ }+}++fn read_file(repo: layout.Repo, path: bytes.Bytes) option[bytes.Bytes] = trust {+ val abs: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(path)+ )+ val out = files.read_all(abs)+ files.free_path(abs)+ return out+}++fn add_blob(tx: mut ref txnmod.Txn, data: ref u8, len: usize) objid.Id = trust {+ val built: ref blob.BlobBuild = blob.build(data, len)+ val id: objid.Id = copy_id(blob.root_id(built))+ val ri: mut usize = 0+ for ri < @len(built.objects) {+ val ro = @get(built.objects, ri)+ if ro is some obj {+ val orf: mut ref raw.RawObject = obj+ val oid: objid.Id = objid.id(orf.id)+ val _ = txnmod.add_known(tx, orf.type_byte, oid, orf.body)+ orf.body = bytes.empty()+ }+ ri+++ }+ blob.free_build(built)+ return id+}++fn replace_placeholder(+ out: mut buf.Buf,+ cmd: bytes.Bytes,+ key: bytes.Bytes,+ value: bytes.Bytes+) void = trust {+ val i: mut usize = 0+ for i < cmd.len {+ if i + key.len <= cmd.len && bytes.Bytes.starts_with(+ bytes.Bytes.slice(cmd, i, cmd.len),+ key+ ) {+ buf.Buf.put_u8(out, 39)+ buf.Buf.put_bytes(out, value)+ buf.Buf.put_u8(out, 39)+ i = i + key.len+ } else {+ buf.Buf.put_u8(out, bytes.Bytes.at(cmd, i))+ i+++ }+ }+}++fn run_tool(+ repo: layout.Repo,+ cmd: bytes.Bytes,+ path: bytes.Bytes+) bool = trust {+ val abs_base: str.StringView = files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(path)+ )+ val abs_base_b: bytes.Bytes = bytes.bytes(abs_base.ptr, abs_base.len as usize)+ val base: mut buf.Buf = buf.new(64)+ val ours: mut buf.Buf = buf.new(64)+ val theirs: mut buf.Buf = buf.new(64)+ buf.Buf.put_bytes(base, abs_base_b)+ buf.Buf.put_bytes(base, bytes.bytes(c".base", 5))+ buf.Buf.put_bytes(ours, abs_base_b)+ buf.Buf.put_bytes(ours, bytes.bytes(c".ours", 5))+ buf.Buf.put_bytes(theirs, abs_base_b)+ buf.Buf.put_bytes(theirs, bytes.bytes(c".theirs", 7))+ val expanded: mut buf.Buf = buf.new(cmd.len + 128)+ // Four passes are enough because placeholders do not nest.+ replace_placeholder(expanded, cmd, bytes.bytes(c"$BASE", 5), buf.Buf.view(base))+ val pass2: mut buf.Buf = buf.new(expanded.len + 128)+ replace_placeholder(pass2, buf.Buf.view(expanded), bytes.bytes(c"$OURS", 5), buf.Buf.view(ours))+ val pass3: mut buf.Buf = buf.new(pass2.len + 128)+ replace_placeholder(+ pass3,+ buf.Buf.view(pass2),+ bytes.bytes(c"$THEIRS", 7),+ buf.Buf.view(theirs)+ )+ val pass4: mut buf.Buf = buf.new(pass3.len + 128)+ replace_placeholder(+ pass4,+ buf.Buf.view(pass3),+ bytes.bytes(c"$OUTPUT", 7),+ abs_base_b+ )+ val cstr: ref u8 = bytes.Bytes.to_cstr(buf.Buf.view(pass4))+ val rc: i32 = system(cstr)+ val cp: mut ref void = cstr as ref void+ @free(cp)+ buf.Buf.free(base)+ buf.Buf.free(ours)+ buf.Buf.free(theirs)+ buf.Buf.free(expanded)+ buf.Buf.free(pass2)+ buf.Buf.free(pass3)+ buf.Buf.free(pass4)+ files.free_path(abs_base)+ return rc == 0+}++fn choose(+ c: ref conflict.Conflict,+ take: bytes.Bytes+) option[ref conflict.ConflictValue] = trust {+ if bytes.Bytes.eql(take, bytes.bytes(c"ours", 4)) && @len(c.adds) > 0 {+ val o = @get(c.adds, 0)+ if o is some v {+ return some v+ }+ }+ if bytes.Bytes.eql(take, bytes.bytes(c"theirs", 6)) && @len(c.adds) > 1 {+ val o = @get(c.adds, 1)+ if o is some v {+ return some v+ }+ }+ if bytes.Bytes.eql(take, bytes.bytes(c"base", 4)) && @len(c.removes) > 0 {+ val o = @get(c.removes, 0)+ if o is some v {+ return some v+ }+ }+ return none+}++pub fn resolve(+ repo: layout.Repo,+ take: bytes.Bytes,+ tool: bytes.Bytes,+ paths: list[bytes.Bytes]+) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val tx_opt = txnmod.begin(repo)+ val tx: mut ref txnmod.Txn = none+ if tx_opt is some t {+ tx = t+ } else {+ msg.error_prefix()+ stdio.eprint("cannot load repository state\n", {})+ return 1+ }+ val st: store.Store = store.open_all(repo)+ val wc_opt = viewops.working_copy(tx.view)+ val wc: mut objid.Id = objid.id_none()+ if wc_opt is some id {+ wc = id+ }+ if objid.Id.is_none(wc) {+ msg.error_prefix()+ stdio.eprint("no working-copy commit\n", {})+ store.close(st)+ txnmod.abort(tx)+ return 1+ }+ val lc_opt = graph.load_commit(st.handles, wc)+ if lc_opt is none {+ msg.error_prefix()+ stdio.eprint("cannot read working-copy commit\n", {})+ store.close(st)+ txnmod.abort(tx)+ return 1+ }+ val lc: mut ref graph.LoadedCommit = none+ if lc_opt is some l {+ lc = l+ }+ val old_root: objid.Id = copy_id(lc.c.root_tree)+ val mut_root: mut objid.Id = copy_id(lc.c.root_tree)+ val resolved_any: mut bool = false+ val i: mut usize = 0+ for i < @len(paths) {+ val arg = @get(paths, i)+ val path: mut bytes.Bytes = bytes.empty()+ if arg is some a {+ val norm = normalize(repo, a)+ if norm is some n {+ path = n+ }+ }+ if path.len == 0 {+ msg.error_prefix()+ stdio.eprint("invalid path\n", {})+ continue+ }+ val flat: list[ref treewalk.FlatEntry] = treewalk.flatten(st.handles, mut_root)+ val entry = treewalk.lookup(flat, path)+ if entry is none {+ msg.error_prefix()+ stdio.eprint(+ "not a conflicted path: {s}\n",+ {str.view(path.ptr, path.len as i64)}+ )+ treewalk.free_flat(flat)+ files.free_buffer(path)+ i+++ continue+ }+ val e: mut ref treewalk.FlatEntry = none+ if entry is some ee {+ e = ee+ }+ if e.kind != tree.KIND_CONFLICT {+ msg.error_prefix()+ stdio.eprint(+ "not a conflicted path: {s}\n",+ {str.view(path.ptr, path.len as i64)}+ )+ treewalk.free_flat(flat)+ files.free_buffer(path)+ i+++ continue+ }+ val c_opt = load_conflict(st.handles, e.target)+ if c_opt is none {+ treewalk.free_flat(flat)+ files.free_buffer(path)+ i+++ continue+ }+ val c: mut ref conflict.Conflict = none+ if c_opt is some cc {+ c = cc+ }+ val present: mut bool = false+ val new_kind: mut u8 = tree.KIND_FILE+ val new_target: mut objid.Id = objid.id_none()+ val took = choose(c, take)+ if took is some v {+ if v.kind != 0 {+ present = true+ new_kind = v.kind+ new_target = copy_id(v.target)+ }+ } elif tool.len > 0 {+ val tool_ok: bool = run_tool(repo, tool, path)+ if tool_ok {+ val data_opt = read_file(repo, path)+ if data_opt is some data {+ new_target = add_blob(tx, data.ptr, data.len)+ present = true+ new_kind = tree.KIND_FILE+ files.free_buffer(data)+ }+ }+ } else {+ val data_opt2 = read_file(repo, path)+ if data_opt2 is some data2 {+ new_target = add_blob(tx, data2.ptr, data2.len)+ present = true+ new_kind = tree.KIND_FILE+ files.free_buffer(data2)+ }+ }+ if present {+ val info_opt = stat.read(+ files.join3(+ layout.root_view(repo),+ str.from_cstr(c""),+ files.to_view(path)+ )+ )+ if info_opt is some info {+ if info.executable {+ new_kind = tree.KIND_EXECUTABLE+ }+ }+ // Remember the resolution when it is a plain file.+ if new_kind == tree.KIND_FILE || new_kind == tree.KIND_EXECUTABLE {+ val body_opt = state.read_body(st.handles, e.target, types.CONFLICT)+ if body_opt is some body {+ val _ = resolutions.record(repo, body, new_target)+ files.free_buffer(body)+ }+ }+ }+ val replaced = treeedit.replace(+ tx,+ st.handles,+ mut_root,+ path,+ present,+ new_kind,+ new_target+ )+ if replaced is some nr {+ free_id(mut_root)+ mut_root = copy_id(nr)+ free_id(nr)+ resolved_any = true+ }+ free_id(new_target)+ conflict.free_conflict(c)+ treewalk.free_flat(flat)+ files.free_buffer(path)+ i+++ }+ val status: mut i32 = 1+ if resolved_any {+ val sig: prim.Sig = identity.signature(repo)+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ for p in lc.c.parents {+ @append(parents, copy_id(p))+ }+ val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+ nc.version = 1+ nc.parents = parents+ nc.root_tree = copy_id(mut_root)+ nc.change_id = lc.c.change_id+ nc.author = lc.c.author+ nc.committer = sig+ nc.message = lc.c.message+ nc.renames_state = lc.c.renames_state+ nc.renames = lc.c.renames+ nc.extra = lc.c.extra+ val body: bytes.Bytes = commit.encode(nc)+ val new_id: objid.Id = txnmod.add_object(tx, types.COMMIT, body)+ viewops.remove_head(tx.view, wc)+ viewops.move_bookmarks(tx.view, wc, new_id)+ viewops.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ status = txnmod.finish(tx, bytes.bytes(c"resolve", 7))+ if status == 0 {+ val st2: store.Store = store.open_all(repo)+ val ms: i32 = checkout.materialize_commit(+ repo,+ st2.handles,+ some old_root,+ mut_root+ )+ store.close(st2)+ if ms != 0 {+ status = ms+ }+ val j: mut usize = 0+ for j < @len(paths) {+ val arg2 = @get(paths, j)+ if arg2 is some a2 {+ val norm2 = normalize(repo, a2)+ if norm2 is some n2 {+ delete_sidecars(repo, n2)+ files.free_buffer(n2)+ }+ }+ j+++ }+ }+ val nrp: mut ref void = nc.root_tree.ptr as ref void+ @free(nrp)+ @listfree(parents)+ @free(nc as ref void)+ identity.free_sig(sig)+ free_id(new_id)+ } else {+ txnmod.abort(tx)+ }+ free_id(old_root)+ free_id(mut_root)+ free_id(wc)+ graph.free_loaded(lc)+ store.close(st)+ return status+}--- a/veins/src/cli/selftest_cmd.sx+++ b/veins/src/cli/selftest_cmd.sx@@ -28,6 +28,8 @@ val index = use("../store/index.sx") val fsck = use("../store/fsck.sx") val files = use("../io/files.sx")+val algebra = use("../merge/algebra.sx")+val filemerge = use("../merge/filemerge.sx") fn fill_pattern(p: ref u8, n: usize, seed: usize) void = trust { val i: mut usize = 0@@ -150,7 +152,95 @@ if x is err _ { break }+ }+}++fn mkid(seed: u8) objid.Id = trust {+ val p: ref u8 = @alloc(32) as ref u8+ val i: mut usize = 0+ for i < 32 {+ @store8(@ptradd(p, i as i64), (seed + i) as u8)+ i+++ }+ return objid.id(p)+}++fn test_algebra() void = trust {+ val handles: list[ref store.Handle] = lists.new[ref store.Handle]()+ val a: objid.Id = mkid(1)+ val b: objid.Id = mkid(2)+ val c: objid.Id = mkid(3)++ val adds: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ val rems: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ @append(adds, conflict.value(tree.KIND_FILE, a))+ @append(adds, conflict.value(tree.KIND_FILE, b))+ @append(rems, conflict.value(tree.KIND_FILE, a))+ val s1: algebra.Sum = algebra.simplify(handles, adds, rems)+ assert @len(s1.adds) == 1+ assert @len(s1.removes) == 0+ algebra.free_sum(s1)++ val adds2: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ val rems2: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ @append(adds2, conflict.value(tree.KIND_FILE, a))+ @append(adds2, conflict.value(tree.KIND_FILE, a))+ @append(rems2, conflict.value(tree.KIND_FILE, b))+ val s2: algebra.Sum = algebra.simplify(handles, adds2, rems2)+ val got = algebra.resolved(s2)+ if got is some g {+ assert objid.Id.eql(g.target, a)+ } else {+ assert false }+ algebra.free_sum(s2)++ // Repeated cancellation and idempotence on a fixed shape.+ val adds3: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ val rems3: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ @append(adds3, conflict.value(tree.KIND_FILE, a))+ @append(adds3, conflict.value(tree.KIND_FILE, b))+ @append(adds3, conflict.value(tree.KIND_FILE, c))+ @append(adds3, conflict.value(tree.KIND_FILE, a))+ @append(rems3, conflict.value(tree.KIND_FILE, b))+ @append(rems3, conflict.value(tree.KIND_FILE, c))+ @append(rems3, conflict.value(tree.KIND_FILE, a))+ val sm: algebra.Sum = algebra.simplify(handles, adds3, rems3)+ assert @len(sm.adds) == 1+ assert @len(sm.removes) == 0+ algebra.free_sum(sm)+ @listfree(handles)++ val ap: mut ref void = a.ptr as ref void+ @free(ap)+ val bp: mut ref void = b.ptr as ref void+ @free(bp)+ val cp: mut ref void = c.ptr as ref void+ @free(cp)+}++fn test_file_merge() void = trust {+ val base = filemerge.split_lines(bytes.bytes(c"a\nb\nc\n", 6))+ val ours = filemerge.split_lines(bytes.bytes(c"A\nb\nc\n", 6))+ val theirs = filemerge.split_lines(bytes.bytes(c"a\nb\nC\n", 6))+ val r = filemerge.merge_lines(base, ours, theirs, false)+ assert !r.conflicted+ assert bytes.Bytes.eql(r.data, bytes.bytes(c"A\nb\nC\n", 6))+ filemerge.free_edit(r)+ @listfree(base)+ @listfree(ours)+ @listfree(theirs)++ val base2 = filemerge.split_lines(bytes.bytes(c"a\nb\n", 4))+ val ours2 = filemerge.split_lines(bytes.bytes(c"A\nb\n", 4))+ val theirs2 = filemerge.split_lines(bytes.bytes(c"X\nb\n", 4))+ val r2 = filemerge.merge_lines(base2, ours2, theirs2, false)+ assert r2.conflicted+ assert bytes.Bytes.eql(r2.data, bytes.bytes(c"A\nb\n", 4))+ filemerge.free_edit(r2)+ @listfree(base2)+ @listfree(ours2)+ @listfree(theirs2) } fn test_fuzz() void = trust {@@ -523,6 +613,8 @@ test_pack_layout() test_chunker() test_fuzz()+ test_algebra()+ test_file_merge() val path: ref u8 = @fmtalloc("/tmp/veins-selftest-{d}", {time.unix_now_micros()}) val repo_r = layout.init(str.from_cstr(path))--- a/veins/src/cli/status_cmd.sx+++ b/veins/src/cli/status_cmd.sx@@ -5,6 +5,7 @@ val msg = use("../core/msg.sx") val terminal = use("std/terminal") val str = use("std/string")+val lists = use("../core/lists.sx") val objid = use("../object/id.sx") val tree = use("../object/tree.sx") val graph = use("../object/graph.sx")@@ -106,7 +107,25 @@ } if conflicted_count > 0 { stdio.print("{d} conflict(s)\n", {conflicted_count})+ }+ val start: mut list[objid.Id] = lists.new[objid.Id]()+ @append(start, graph.copy_id(wc))+ val ancestry: list[objid.Id] = graph.collect(st.handles, start)+ val conflicted_commits: mut usize = 0+ for cid in ancestry {+ val lc_opt = graph.load_commit(st.handles, cid)+ if lc_opt is some lc {+ if treewalk.conflicted(st.handles, lc.c.root_tree) {+ conflicted_commits+++ }+ graph.free_loaded(lc)+ }+ }+ if conflicted_commits > 0 {+ stdio.print("{d} conflicted commit(s) in ancestry\n", {conflicted_commits}) }+ graph.free_ids(ancestry)+ @listfree(start) treediff.free(changes) view.free_view(v) if wc.ptr != none {--- /dev/null+++ b/veins/src/core/repoconfig.sx@@ -0,0 +1,121 @@+/// Repository-local configuration (`key = value` lines in `.veins/config`).+///+/// The file is intentionally simple so that local configuration can be read by+/// every command without a dependency on a TOML parser. Values are returned as+/// owned byte spans; callers release them with `bytes.free`-style helpers.++val bytes = use("bytes.sx")+val str = use("std/string")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")++fn trim(b: bytes.Bytes) bytes.Bytes = trust {+ val start: mut usize = 0+ val end: mut usize = b.len+ for start < end {+ val c: u8 = bytes.Bytes.at(b, start)+ if c != 32 && c != 9 && c != 13 && c != 10 {+ break+ }+ start+++ }+ for end > start {+ val c2: u8 = bytes.Bytes.at(b, end - 1)+ if c2 != 32 && c2 != 9 && c2 != 13 && c2 != 10 {+ break+ }+ end--+ }+ return bytes.Bytes.slice(b, start, end)+}++fn strip_comment(b: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = 0+ for i < b.len {+ if bytes.Bytes.at(b, i) == 35 {+ return trim(bytes.Bytes.slice(b, 0, i))+ }+ i+++ }+ return trim(b)+}++/// Look up one key. The result is owned by the caller.+pub fn get(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {+ val path: str.StringView = layout.config_path(repo)+ val data_opt = files.read_all(path)+ files.free_path(path)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return none+ }+ }+ val pos: mut usize = 0+ val start: mut usize = 0+ for pos <= data.len {+ val at_end: bool = pos == data.len+ if at_end || bytes.Bytes.at(data, pos) == 10 {+ val line: bytes.Bytes = trim(bytes.Bytes.slice(data, start, pos))+ if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {+ val eq: mut i64 = -1+ val i: mut usize = 0+ for i < line.len {+ if bytes.Bytes.at(line, i) == 61 && eq < 0 {+ eq = i as i64+ }+ i+++ }+ if eq >= 0 {+ val k: bytes.Bytes = trim(bytes.Bytes.slice(line, 0, eq as usize))+ if bytes.Bytes.eql(k, key) {+ val v: bytes.Bytes = strip_comment(+ bytes.Bytes.slice(line, eq as usize + 1, line.len)+ )+ val out: bytes.Bytes = bytes.Bytes.dup(v)+ files.free_buffer(data)+ return some out+ }+ }+ }+ start = pos + 1+ }+ pos+++ }+ files.free_buffer(data)+ return none+}++pub fn free_value(v: bytes.Bytes) void = trust {+ files.free_buffer(v)+}++fn is_true(v: bytes.Bytes) bool = trust {+ return bytes.Bytes.eql(v, bytes.bytes(c"true", 4))+ || bytes.Bytes.eql(v, bytes.bytes(c"1", 1))+ || bytes.Bytes.eql(v, bytes.bytes(c"yes", 3))+ || bytes.Bytes.eql(v, bytes.bytes(c"on", 2))+}++/// Read a boolean key. Missing values use `default`.+pub fn get_bool(repo: layout.Repo, key: bytes.Bytes, default: bool) bool = trust {+ val v = get(repo, key)+ match v {+ some value => {+ val out: bool = is_true(value)+ files.free_buffer(value)+ return out+ }+ none => {+ return default+ }+ }+}++/// Read a text key. The result is owned by the caller.+pub fn get_text(repo: layout.Repo, key: bytes.Bytes) option[bytes.Bytes] = trust {+ return get(repo, key)+}--- a/veins/src/main.sx+++ b/veins/src/main.sx@@ -17,11 +17,14 @@ val log_cmd = use("cli/log_cmd.sx") val show_cmd = use("cli/show_cmd.sx") val diff_cmd = use("cli/diff_cmd.sx")+val merge_cmd = use("cli/merge_cmd.sx")+val resolve_cmd = use("cli/resolve_cmd.sx") val new_cmd = use("cli/new_cmd.sx") val bookmark_cmd = use("cli/bookmark_cmd.sx") val op_cmd = use("cli/op_cmd.sx") val inf_cmd = use("cli/inf_cmd.sx") val rm_cmd = use("cli/rm_cmd.sx")+val mv_cmd = use("cli/mv_cmd.sx") val ex_cmd = use("cli/ex_cmd.sx") val lists = use("core/lists.sx") val layout = use("store/layout.sx")@@ -274,6 +277,41 @@ match repo_opt { some repo => { val status: i32 = diff_cmd.run(repo, revs)+ layout.free_repo(repo)+ @listfree(revs)+ return status+ }+ none => {+ @listfree(revs)+ return 1+ }+ }+}++fn run_merge(args: list[ref u8], start: usize) i32 = trust {+ val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(revs)+ return 1+ } else {+ @append(revs, bytes.from_cstr(a))+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = merge_cmd.merge(repo, revs) layout.free_repo(repo) @listfree(revs) return status@@ -280,6 +318,215 @@ } none => { @listfree(revs)+ return 1+ }+ }+}++fn run_rebase(args: list[ref u8], start: usize) i32 = trust {+ val source: mut bytes.Bytes = bytes.empty()+ val dest: mut bytes.Bytes = bytes.empty()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-s", 2) || cmd_is(a, c"-source", 7)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ source = bytes.from_cstr(rv)+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})+ return 1+ }+ } elif !end_flags && (cmd_is(a, c"-d", 2) || cmd_is(a, c"-destination", 12)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ dest = bytes.from_cstr(rv)+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a revision\n", {str.from_cstr(a)})+ return 1+ }+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ msg.error_prefix()+ stdio.eprint("unexpected argument: {s}\n", {str.from_cstr(a)})+ return 1+ }+ }+ i+++ }+ if source.len == 0 || dest.len == 0 {+ msg.error_prefix()+ stdio.eprint("rebase requires -s <rev> and -d <rev>\n", {})+ return 1+ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = merge_cmd.rebase(repo, source, dest)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_conflicts(args: list[ref u8], start: usize) i32 = trust {+ val porcelain: mut bool = false+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-porcelain", 10) || cmd_is(a, c"-p", 2)) {+ porcelain = true+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ } else {+ msg.error_prefix()+ stdio.eprint("unexpected argument: {s}\n", {str.from_cstr(a)})+ return 1+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = resolve_cmd.conflicts(repo, porcelain)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_resolve(args: list[ref u8], start: usize) i32 = trust {+ val take: mut bytes.Bytes = bytes.empty()+ val tool: mut bytes.Bytes = bytes.empty()+ val list_only: mut bool = false+ val paths: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && (cmd_is(a, c"-list", 5) || cmd_is(a, c"-l", 2)) {+ list_only = true+ } elif !end_flags && (cmd_is(a, c"-take", 5) || cmd_is(a, c"-t", 2)) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ take = bytes.from_cstr(rv)+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires ours, theirs, or base\n", {str.from_cstr(a)})+ @listfree(paths)+ return 1+ }+ } elif !end_flags && cmd_is(a, c"-tool", 5) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ tool = bytes.from_cstr(rv)+ i+++ }+ } else {+ msg.error_prefix()+ stdio.eprint("{s} requires a command\n", {str.from_cstr(a)})+ @listfree(paths)+ return 1+ }+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(paths)+ return 1+ } else {+ @append(paths, bytes.from_cstr(a))+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: mut i32 = 1+ if list_only {+ status = resolve_cmd.conflicts(repo, false)+ } elif @len(paths) == 0 {+ msg.error_prefix()+ stdio.eprint("resolve requires at least one path\n", {})+ } else {+ status = resolve_cmd.resolve(repo, take, tool, paths)+ }+ layout.free_repo(repo)+ @listfree(paths)+ return status+ }+ none => {+ @listfree(paths)+ return 1+ }+ }+}++fn run_mv(args: list[ref u8], start: usize) i32 = trust {+ val paths: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val end_flags: mut bool = false+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !end_flags && cmd_is(a, c"--", 2) {+ end_flags = true+ } elif !end_flags && is_flag(a) {+ msg.error_prefix()+ stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+ @listfree(paths)+ return 1+ } else {+ @append(paths, bytes.from_cstr(a))+ }+ }+ i+++ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = mv_cmd.run(repo, paths)+ layout.free_repo(repo)+ @listfree(paths)+ return status+ }+ none => {+ @listfree(paths) return 1 } }@@ -536,6 +783,18 @@ } if cmd_is(cmd, c"diff", 4) { return run_diff(args, 2)+ }+ if cmd_is(cmd, c"merge", 5) {+ return run_merge(args, 2)+ }+ if cmd_is(cmd, c"rebase", 6) {+ return run_rebase(args, 2)+ }+ if cmd_is(cmd, c"conflicts", 9) {+ return run_conflicts(args, 2)+ }+ if cmd_is(cmd, c"resolve", 7) {+ return run_resolve(args, 2) } if cmd_is(cmd, c"new", 3) { return run_new(args, 2)@@ -542,6 +801,9 @@ } if cmd_is(cmd, c"rm", 2) { return rm_cmd.run(args, 2)+ }+ if cmd_is(cmd, c"mv", 2) {+ return run_mv(args, 2) } if cmd_is(cmd, c"bmk", 3) { return bookmark_cmd.run(args, 2)--- /dev/null+++ b/veins/src/merge/algebra.sx@@ -0,0 +1,259 @@+/// Conflict algebra: flattening, cancellation, and resolution of signed terms.+///+/// A sum is represented as an `adds` list of `n+1` terms and a `removes` list+/// of `n` terms. `simplify` consumes its inputs and returns a simplified sum.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val conflict = use("../object/conflict.sx")+val tree = use("../object/tree.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")+val txnmod = use("../store/txn.sx")++pub type Sum = {+ adds: mut list[ref conflict.ConflictValue]+ removes: mut list[ref conflict.ConflictValue]+}++pub fn empty() Sum = {+ return Sum{+ adds: lists.new[ref conflict.ConflictValue](),+ removes: lists.new[ref conflict.ConflictValue]()+ }+}++pub fn free_value(v: ref conflict.ConflictValue) void = trust {+ @free(v as ref void)+}++pub fn free_values(xs: list[ref conflict.ConflictValue]) void = trust {+ for v in xs {+ free_value(v)+ }+ @listfree(xs)+}++pub fn free_sum(s: Sum) void = trust {+ free_values(s.adds)+ free_values(s.removes)+}++pub fn sum_is_unresolved(s: Sum) bool = {+ if @len(s.removes) == 0 {+ return false+ }+ if @len(s.adds) <= 1 {+ return false+ }+ val first = @get(s.adds, 0)+ if first is some f {+ for x in s.adds {+ if !conflict.ConflictValue.eql(f, x) {+ return true+ }+ }+ }+ return false+}++/// The resolved value when the sum has one distinct add. Borrows the term.+pub fn resolved(s: Sum) option[ref conflict.ConflictValue] = {+ if @len(s.adds) == 0 {+ return none+ }+ val first = @get(s.adds, 0)+ if first is some f {+ for x in s.adds {+ if !conflict.ConflictValue.eql(f, x) {+ return none+ }+ }+ return some f+ }+ return none+}++fn load_conflict(+ handles: list[ref store.Handle],+ id: objid.Id,+ use_cache: bool,+ tx: ref txnmod.Txn+) option[ref conflict.Conflict] = trust {+ val body: mut bytes.Bytes = bytes.empty()+ if use_cache {+ val cached = txnmod.find_cached(tx, types.CONFLICT, id)+ if cached is some cb {+ body = bytes.Bytes.dup(cb)+ }+ }+ if body.ptr == none {+ val body_opt = state.read_body(handles, id, types.CONFLICT)+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ }+ val decoded = conflict.decode(body)+ val out: mut option[ref conflict.Conflict] = none+ match decoded {+ ok c => {+ out = some c+ }+ err _ => {+ }+ }+ if out is none {+ files.free_buffer(body)+ }+ return out+}++fn flatten_into(+ handles: list[ref store.Handle],+ vals: list[ref conflict.ConflictValue],+ positive: bool,+ adds: mut list[ref conflict.ConflictValue],+ removes: mut list[ref conflict.ConflictValue],+ depth: usize,+ use_cache: bool,+ tx: ref txnmod.Txn+) void = trust {+ for v in vals {+ if v.kind == tree.KIND_CONFLICT && depth < 64 {+ val c_opt = load_conflict(handles, v.target, use_cache, tx)+ if c_opt is some c {+ flatten_into(handles, c.adds, positive, adds, removes, depth + 1, use_cache, tx)+ flatten_into(handles, c.removes, !positive, adds, removes, depth + 1, use_cache, tx)+ // The child lists were consumed by flatten_into; only the+ // conflict struct itself remains owned here.+ @free(c as ref void)+ free_value(v)+ continue+ }+ }+ if positive {+ @append(adds, v)+ } else {+ @append(removes, v)+ }+ }+ @listfree(vals)+}++fn find_cancel(adds: list[ref conflict.ConflictValue], used: ref u8, v: ref conflict.ConflictValue) i32 = trust {+ val i: mut usize = 0+ for i < @len(adds) {+ val used_flag: u8 = @load8(@ptradd(used, i as i64))+ if used_flag == 0 {+ val a = @get(adds, i)+ if a is some av {+ if conflict.ConflictValue.eql(av, v) {+ return i as i32+ }+ }+ }+ i+++ }+ return -1+}++fn used_at(used: ref u8, i: usize) bool = trust {+ return @load8(@ptradd(used, i as i64)) != 0+}++fn set_used(used: ref u8, i: usize) void = trust {+ @store8(@ptradd(used, i as i64), 1)+}++/// Flatten, cancel, and compact. The input lists and terms are consumed.+fn simplify_inner(+ handles: list[ref store.Handle],+ adds_in: list[ref conflict.ConflictValue],+ removes_in: list[ref conflict.ConflictValue],+ use_cache: bool,+ tx: ref txnmod.Txn+) Sum = trust {+ val flat: mut Sum = empty()+ flatten_into(handles, adds_in, true, flat.adds, flat.removes, 0, use_cache, tx)+ flatten_into(handles, removes_in, false, flat.adds, flat.removes, 0, use_cache, tx)++ val n_adds: usize = @len(flat.adds)+ val used: ref u8 = @alloc(n_adds + 1) as ref u8+ @memset(used as ref void, 0, n_adds + 1)+ val rem_used: ref u8 = @alloc(@len(flat.removes) + 1) as ref u8+ @memset(rem_used as ref void, 0, @len(flat.removes) + 1)++ val r: mut usize = 0+ for r < @len(flat.removes) {+ val rv = @get(flat.removes, r)+ if rv is some value {+ val idx: i32 = find_cancel(flat.adds, used, value)+ if idx >= 0 {+ set_used(used, idx as usize)+ @store8(@ptradd(rem_used, r as i64), 1)+ }+ }+ r+++ }++ val out: mut Sum = empty()+ val a: mut usize = 0+ for a < @len(flat.adds) {+ val av = @get(flat.adds, a)+ if av is some value {+ if used_at(used, a) {+ free_value(value)+ } else {+ @append(out.adds, value)+ }+ }+ a+++ }+ val rr: mut usize = 0+ for rr < @len(flat.removes) {+ val rv = @get(flat.removes, rr)+ if rv is some value {+ if used_at(rem_used, rr) {+ free_value(value)+ } else {+ @append(out.removes, value)+ }+ }+ rr+++ }+ @free(used as ref void)+ @free(rem_used as ref void)+ @listfree(flat.adds)+ @listfree(flat.removes)+ return out+}++pub fn simplify(+ handles: list[ref store.Handle],+ adds_in: list[ref conflict.ConflictValue],+ removes_in: list[ref conflict.ConflictValue]+) Sum = trust {+ return simplify_inner(handles, adds_in, removes_in, false, none)+}++pub fn simplify_tx(+ handles: list[ref store.Handle],+ adds_in: list[ref conflict.ConflictValue],+ removes_in: list[ref conflict.ConflictValue],+ tx: ref txnmod.Txn+) Sum = trust {+ return simplify_inner(handles, adds_in, removes_in, true, tx)+}++/// Encode a simplified, unresolved sum as a conflict object body.+pub fn conflict_body(s: Sum) bytes.Bytes = {+ return conflict.encode(s.adds, s.removes)+}--- /dev/null+++ b/veins/src/merge/attributes.sx@@ -0,0 +1,158 @@+/// Tracked `.veinsattributes` rules that affect merging.+///+/// Rules are one per line: `glob attr=value ...`. Later matching rules override+/// earlier ones. Only `merge=text|binary` is interpreted here; other attributes+/// are accepted and ignored.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val ignore = use("../worktree/ignore.sx")+val files = use("../io/files.sx")+val layout = use("../store/layout.sx")++fn trim(b: bytes.Bytes) bytes.Bytes = trust {+ val start: mut usize = 0+ val end: mut usize = b.len+ for start < end {+ val c: u8 = bytes.Bytes.at(b, start)+ if c != 32 && c != 9 && c != 13 && c != 10 {+ break+ }+ start+++ }+ for end > start {+ val c2: u8 = bytes.Bytes.at(b, end - 1)+ if c2 != 32 && c2 != 9 && c2 != 13 && c2 != 10 {+ break+ }+ end--+ }+ return bytes.Bytes.slice(b, start, end)+}++fn token_at(b: bytes.Bytes, start: usize) bytes.Bytes = trust {+ val i: mut usize = start+ for i < b.len {+ val c: u8 = bytes.Bytes.at(b, i)+ if c == 32 || c == 9 {+ break+ }+ i+++ }+ return bytes.Bytes.slice(b, start, i)+}++fn skip_ws(b: bytes.Bytes, start: usize) usize = trust {+ val i: mut usize = start+ for i < b.len {+ val c: u8 = bytes.Bytes.at(b, i)+ if c != 32 && c != 9 {+ break+ }+ i+++ }+ return i+}++fn has_slash(b: bytes.Bytes) bool = trust {+ val i: mut usize = 0+ for i < b.len {+ if bytes.Bytes.at(b, i) == 47 {+ return true+ }+ i+++ }+ return false+}++fn basename(b: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = b.len+ for i > 0 {+ if bytes.Bytes.at(b, i - 1) == 47 {+ return bytes.Bytes.slice(b, i, b.len)+ }+ i--+ }+ return b+}++fn matches(pattern: bytes.Bytes, path: bytes.Bytes) bool = trust {+ if ignore.glob_match(pattern, path) {+ return true+ }+ if !has_slash(pattern) {+ return ignore.glob_match(pattern, basename(path))+ }+ return false+}++fn value_is(v: bytes.Bytes, text: ref u8, len: usize) bool = trust {+ return bytes.Bytes.eql(v, bytes.bytes(text, len))+}++/// True when the path's effective `merge` attribute is `binary`.+pub fn merge_binary(repo: layout.Repo, path: bytes.Bytes) bool = trust {+ val root: str.StringView = layout.root_view(repo)+ val p: str.StringView = files.join(root, str.from_cstr(c".veinsattributes"))+ val data_opt = files.read_all(p)+ files.free_path(p)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return false+ }+ }+ val result: mut bool = false+ val pos: mut usize = 0+ val start: mut usize = 0+ for pos <= data.len {+ val at_end: bool = pos == data.len+ if at_end || bytes.Bytes.at(data, pos) == 10 {+ val line: bytes.Bytes = trim(bytes.Bytes.slice(data, start, pos))+ if line.len > 0 && bytes.Bytes.at(line, 0) != 35 {+ val glob: bytes.Bytes = token_at(line, 0)+ if glob.len > 0 && matches(glob, path) {+ val t: mut usize = skip_ws(line, glob.len)+ for t < line.len {+ val tok_start: usize = t+ val tok: bytes.Bytes = token_at(line, tok_start)+ if tok.len == 0 {+ break+ }+ val eq: mut i64 = -1+ val k: mut usize = 0+ for k < tok.len {+ if bytes.Bytes.at(tok, k) == 61 && eq < 0 {+ eq = k as i64+ }+ k+++ }+ if eq >= 0 {+ val key: bytes.Bytes = bytes.Bytes.slice(tok, 0, eq as usize)+ val valb: bytes.Bytes = bytes.Bytes.slice(+ tok,+ eq as usize + 1,+ tok.len+ )+ if value_is(key, c"merge", 5) {+ if value_is(valb, c"binary", 6) {+ result = true+ } elif value_is(valb, c"text", 4) {+ result = false+ }+ }+ }+ t = skip_ws(line, tok_start + tok.len)+ }+ }+ }+ start = pos + 1+ }+ pos+++ }+ files.free_buffer(data)+ return result+}--- /dev/null+++ b/veins/src/merge/engine.sx@@ -0,0 +1,482 @@+/// Merge-base selection and helpers that turn commit-level merges into the+/// signed tree terms consumed by `treemerge`.++val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val graph = use("../object/graph.sx")+val store = use("../store/store.sx")+val txnmod = use("../store/txn.sx")+val layout = use("../store/layout.sx")+val object = use("../git/object.sx")+val rename = use("rename.sx")+val treemerge = use("treemerge.sx")++pub fn tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ out = some graph.copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ return out+}++pub fn parents_of(handles: list[ref store.Handle], id: objid.Id) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val lc_opt = graph.load_commit(handles, id)+ if lc_opt is some lc {+ for p in lc.c.parents {+ @append(out, graph.copy_id(p))+ }+ graph.free_loaded(lc)+ }+ return out+}++fn contains(ids: list[objid.Id], id: objid.Id) bool = trust {+ for x in ids {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false+}++pub fn single(id: objid.Id) list[objid.Id] = trust {+ val xs: mut list[objid.Id] = lists.new[objid.Id]()+ @append(xs, graph.copy_id(id))+ return xs+}++/// Common ancestors that are not ancestors of another common ancestor.+pub fn merge_bases(handles: list[ref store.Handle], a: objid.Id, b: objid.Id) list[objid.Id] = trust {+ val aa: list[objid.Id] = graph.collect(handles, single(a))+ val bb: list[objid.Id] = graph.collect(handles, single(b))+ val common: mut list[objid.Id] = lists.new[objid.Id]()+ for x in aa {+ if contains(bb, x) {+ @append(common, graph.copy_id(x))+ }+ }+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ for c in common {+ val dominated: mut bool = false+ for d in common {+ if !objid.Id.eql(c, d) {+ val desc: list[objid.Id] = graph.collect(handles, single(c))+ if contains(desc, d) {+ dominated = true+ }+ graph.free_ids(desc)+ if dominated {+ break+ }+ }+ }+ if !dominated {+ @append(out, graph.copy_id(c))+ }+ }+ graph.free_ids(aa)+ graph.free_ids(bb)+ graph.free_ids(common)+ return out+}++pub fn is_ancestor(+ handles: list[ref store.Handle],+ ancestor: objid.Id,+ descendant: objid.Id+) bool = trust {+ if objid.Id.eql(ancestor, descendant) {+ return true+ }+ val ids: list[objid.Id] = graph.collect(handles, single(descendant))+ val found: bool = contains(ids, ancestor)+ graph.free_ids(ids)+ return found+}++fn graph_single(id: objid.Id) list[objid.Id] = trust {+ val xs: mut list[objid.Id] = lists.new[objid.Id]()+ @append(xs, id)+ return xs+}++fn new_term(positive: bool, present: bool, id: objid.Id) ref treemerge.TreeTerm = trust {+ val t: mut ref treemerge.TreeTerm = @alloc(@sizeof(treemerge.TreeTerm)) as ref treemerge.TreeTerm+ t.positive = positive+ t.present = present+ t.id = graph.copy_id(id)+ return t+}++fn free_terms(ts: list[ref treemerge.TreeTerm]) void = trust {+ for t in ts {+ val tp: mut ref void = t.id.ptr as ref void+ @free(tp)+ val ep: mut ref void = t as ref void+ @free(ep)+ }+ @listfree(ts)+}++fn free_maps(ms: list[ref rename.RenameMap]) void = trust {+ for m in ms {+ if m is some mm {+ if mm != none {+ rename.free_map(mm)+ @free(mm as ref void)+ }+ }+ }+ @listfree(ms)+}++fn empty_map() ref rename.RenameMap = trust {+ val m: rename.RenameMap = rename.empty()+ val out: mut ref rename.RenameMap = @alloc(@sizeof(rename.RenameMap)) as ref rename.RenameMap+ out.entries = m.entries+ return out+}++fn new_map(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ base: objid.Id,+ side: objid.Id+) ref rename.RenameMap = trust {+ val m: rename.RenameMap = rename.map_from(handles, git, has_git, base, side)+ val out: mut ref rename.RenameMap = @alloc(@sizeof(rename.RenameMap)) as ref rename.RenameMap+ out.entries = m.entries+ return out+}++fn base_tree(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ bases: list[objid.Id],+ adjacent_merge: bool+) option[objid.Id] = trust {+ if @len(bases) == 0 {+ return none+ }+ if @len(bases) == 1 {+ val o = @get(bases, 0)+ if o is some b {+ return tree_of(handles, b)+ }+ return none+ }+ // Criss-cross: fold a virtual base from the first two commits. Deeper+ // histories use the first LCA, which is conservative and deterministic.+ val b0 = @get(bases, 0)+ val b1 = @get(bases, 1)+ if b0 is some first {+ if b1 is some second {+ val t0 = tree_of(handles, first)+ val t1 = tree_of(handles, second)+ val lcas: list[objid.Id] = merge_bases(handles, first, second)+ val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()+ val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()+ @append(terms, new_term(true, has_opt(t0), option_id(t0)))+ @append(terms, new_term(true, has_opt(t1), option_id(t1)))+ @append(maps, empty_map())+ @append(maps, empty_map())+ if @len(lcas) > 0 {+ val l0 = @get(lcas, 0)+ if l0 is some lc {+ val lt = tree_of(handles, lc)+ @append(terms, new_term(false, has_opt(lt), option_id(lt)))+ @append(maps, empty_map())+ free_opt(lt)+ }+ } else {+ @append(terms, new_term(false, false, objid.id(none)))+ @append(maps, empty_map())+ }+ val out = treemerge.merge(+ repo,+ tx,+ handles,+ git,+ has_git,+ terms,+ maps,+ adjacent_merge+ )+ free_terms(terms)+ free_maps(maps)+ graph.free_ids(lcas)+ free_opt(t0)+ free_opt(t1)+ return some out.tree+ }+ }+ return none+}++fn option_id(o: option[objid.Id]) objid.Id = trust {+ if o is some id {+ return id+ }+ return objid.id(none)+}++fn has_opt(o: option[objid.Id]) bool = trust {+ if o is some _ {+ return true+ }+ return false+}++fn free_opt(o: option[objid.Id]) void = trust {+ if o is some id {+ @free(id.ptr as ref void)+ }+}++/// Merge two commit ids, writing objects through `tx`.+pub fn merge_two(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ a: objid.Id,+ b: objid.Id,+ adjacent_merge: bool+) treemerge.Outcome = trust {+ val ta = tree_of(handles, a)+ val tb = tree_of(handles, b)+ val bases: list[objid.Id] = merge_bases(handles, a, b)+ val bt: option[objid.Id] = base_tree(repo, tx, handles, git, has_git, bases, adjacent_merge)+ val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()+ @append(terms, new_term(true, has_opt(ta), option_id(ta)))+ @append(terms, new_term(true, has_opt(tb), option_id(tb)))+ val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()+ val base_id: mut objid.Id = objid.id(none)+ if @len(bases) > 0 {+ val o = @get(bases, 0)+ if o is some first {+ base_id = first+ }+ }+ if objid.Id.is_none(base_id) {+ @append(maps, empty_map())+ @append(maps, empty_map())+ } else {+ @append(maps, new_map(handles, git, has_git, base_id, a))+ @append(maps, new_map(handles, git, has_git, base_id, b))+ }+ if bt is some btree {+ @append(terms, new_term(false, true, btree))+ } else {+ @append(terms, new_term(false, false, objid.id(none)))+ }+ @append(maps, empty_map())+ val out = treemerge.merge(+ repo,+ tx,+ handles,+ git,+ has_git,+ terms,+ maps,+ adjacent_merge+ )+ free_terms(terms)+ free_maps(maps)+ graph.free_ids(bases)+ free_opt(ta)+ free_opt(tb)+ free_opt(bt)+ return out+}++/// Merge more than two heads by accumulating `S + R_i - B_i` terms.+pub fn merge_many(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ heads: list[objid.Id],+ adjacent_merge: bool+) treemerge.Outcome = trust {+ if @len(heads) == 1 {+ val o = @get(heads, 0)+ val t: mut option[objid.Id] = none+ if o is some id {+ t = tree_of(handles, id)+ }+ val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()+ @append(terms, new_term(true, has_opt(t), option_id(t)))+ val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()+ @append(maps, empty_map())+ val out = treemerge.merge(+ repo,+ tx,+ handles,+ git,+ has_git,+ terms,+ maps,+ adjacent_merge+ )+ free_terms(terms)+ free_maps(maps)+ free_opt(t)+ return out+ }+ val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()+ val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()+ val first = @get(heads, 0)+ val first_id: mut objid.Id = objid.id(none)+ if first is some f {+ first_id = f+ }+ val map_base: mut objid.Id = objid.id(none)+ if @len(heads) > 1 {+ val second = @get(heads, 1)+ if second is some sh {+ val bs: list[objid.Id] = merge_bases(handles, first_id, sh)+ if @len(bs) > 0 {+ val b0 = @get(bs, 0)+ if b0 is some bid {+ map_base = graph.copy_id(bid)+ }+ }+ graph.free_ids(bs)+ }+ }+ for h in heads {+ val t = tree_of(handles, h)+ @append(terms, new_term(true, has_opt(t), option_id(t)))+ if objid.Id.is_none(map_base) {+ @append(maps, empty_map())+ } else {+ @append(maps, new_map(handles, git, has_git, map_base, h))+ }+ free_opt(t)+ }+ val hi: mut usize = 1+ for hi < @len(heads) {+ val o = @get(heads, hi)+ if o is some h {+ val bases: list[objid.Id] = merge_bases(handles, first_id, h)+ val bt = base_tree(repo, tx, handles, git, has_git, bases, adjacent_merge)+ if bt is some btree {+ @append(terms, new_term(false, true, btree))+ } else {+ @append(terms, new_term(false, false, objid.id(none)))+ }+ @append(maps, empty_map())+ graph.free_ids(bases)+ free_opt(bt)+ }+ hi+++ }+ val out = treemerge.merge(+ repo,+ tx,+ handles,+ git,+ has_git,+ terms,+ maps,+ adjacent_merge+ )+ free_terms(terms)+ free_maps(maps)+ if map_base.ptr != none {+ graph.free_ids(graph_single(map_base))+ }+ return out+}++/// Compute a rebased tree: `tree(C) + Σ(tree(P'_i) - tree(P_i))`.+pub fn rewrite_tree(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ old_commit: objid.Id,+ commit_tree: objid.Id,+ old_parents: list[objid.Id],+ new_parents: list[objid.Id],+ new_parent_trees: list[objid.Id],+ adjacent_merge: bool+) treemerge.Outcome = trust {+ val terms: mut list[ref treemerge.TreeTerm] = lists.new[ref treemerge.TreeTerm]()+ val maps: mut list[ref rename.RenameMap] = lists.new[ref rename.RenameMap]()+ @append(terms, new_term(true, true, commit_tree))+ // The commit may have renamed paths relative to its first old parent.+ if @len(old_parents) > 0 {+ val p0 = @get(old_parents, 0)+ if p0 is some oldp {+ @append(maps, new_map(handles, git, has_git, oldp, old_commit))+ } else {+ @append(maps, empty_map())+ }+ } else {+ @append(maps, empty_map())+ }+ if @len(old_parents) == 0 {+ // Root commit onto a new parent: treat the base as absent.+ for ntid in new_parent_trees {+ @append(terms, new_term(true, !objid.Id.is_none(ntid), ntid))+ @append(maps, empty_map())+ }+ @append(terms, new_term(false, false, objid.id(none)))+ @append(maps, empty_map())+ } else {+ val n: usize = @len(old_parents)+ val i: mut usize = 0+ for i < n {+ val op = @get(old_parents, i)+ val np = @get(new_parents, i)+ val ot: mut option[objid.Id] = none+ if op is some oid {+ ot = tree_of(handles, oid)+ }+ val ntid_o = @get(new_parent_trees, i)+ val ntid: mut objid.Id = objid.id(none)+ if ntid_o is some tv {+ ntid = tv+ }+ @append(terms, new_term(true, !objid.Id.is_none(ntid), ntid))+ @append(terms, new_term(false, has_opt(ot), option_id(ot)))+ if op is some ob {+ if np is some nb {+ @append(maps, new_map(handles, git, has_git, ob, nb))+ } else {+ @append(maps, empty_map())+ }+ } else {+ @append(maps, empty_map())+ }+ @append(maps, empty_map())+ free_opt(ot)+ i+++ }+ }+ val out = treemerge.merge(+ repo,+ tx,+ handles,+ git,+ has_git,+ terms,+ maps,+ adjacent_merge+ )+ free_terms(terms)+ free_maps(maps)+ return out+}--- /dev/null+++ b/veins/src/merge/filemerge.sx@@ -0,0 +1,686 @@+/// Line-based three-way file merge.+///+/// The implementation uses a bounded LCS diff and a diff3-style hunk merge.+/// Binary detection is performed by the caller; this module only deals with+/// text. Line buffers are borrowed from the caller's blob data.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val blob = use("../object/blob.sx")+val content = use("../object/content.sx")+val store = use("../store/store.sx")+val raw = use("../object/raw.sx")+val txnmod = use("../store/txn.sx")+val object = use("../git/object.sx")++pub val OP_CONTEXT: u8 = 32+pub val OP_ADD: u8 = 43+pub val OP_DEL: u8 = 45++pub type Op = {+ tag: mut u8+ ai: mut usize+ bi: mut usize+}++pub type Hunk = {+ start: mut usize+ end: mut usize+ lines: mut list[bytes.Bytes]+}++pub type Range = {+ base_start: mut usize+ base_end: mut usize+ ours_start: mut usize+ ours_end: mut usize+ theirs_start: mut usize+ theirs_end: mut usize+}++pub type EditResult = {+ conflicted: mut bool+ data: mut bytes.Bytes+ ranges: mut list[ref Range]+}++fn line_at(ls: list[bytes.Bytes], i: usize) bytes.Bytes = {+ val o = @get(ls, i)+ if o is some l {+ return l+ }+ return bytes.empty()+}++/// Split into lines that retain their trailing newline (except a final line+/// without one). Empty input yields no lines.+pub fn split_lines(data: bytes.Bytes) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ if data.len == 0 {+ return out+ }+ val start: mut usize = 0+ val i: mut usize = 0+ for i < data.len {+ if bytes.Bytes.at(data, i) == 10 {+ @append(out, bytes.Bytes.slice(data, start, i + 1))+ start = i + 1+ }+ i+++ }+ if start < data.len {+ @append(out, bytes.Bytes.slice(data, start, data.len))+ }+ return out+}++pub fn contains_nul(data: bytes.Bytes) bool = trust {+ val limit: usize = 8192+ val n: usize = data.len+ val i: mut usize = 0+ for i < n && i < limit {+ if bytes.Bytes.at(data, i) == 0 {+ return true+ }+ i+++ }+ return false+}++fn new_op(tag: u8, ai: usize, bi: usize) ref Op = trust {+ val op: mut ref Op = @alloc(@sizeof(Op)) as ref Op+ op.tag = tag+ op.ai = ai+ op.bi = bi+ return op+}++fn free_ops(ops: list[ref Op]) void = trust {+ for op in ops {+ val p: mut ref void = op as ref void+ @free(p)+ }+ @listfree(ops)+}++fn op_at(ops: list[ref Op], i: usize) ref Op = trust {+ val o = @get(ops, i)+ if o is some op {+ return op+ }+ assert false+ return none+}++fn reverse_ops(ops: mut list[ref Op]) void = trust {+ val n: usize = @len(ops)+ val i: mut usize = 0+ for i < n / 2 {+ val a: ref Op = op_at(ops, i)+ val b: ref Op = op_at(ops, n - 1 - i)+ @set(ops, i, b)+ @set(ops, n - 1 - i, a)+ i+++ }+}++fn lcs_get(dp: ref u32, idx: usize) u32 = trust {+ val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32+ return @load32(p) as u32+}++fn lcs_set(dp: ref u32, idx: usize, value: u32) void = trust {+ val p: ref u32 = @ptradd(dp as ref void, (idx * 4) as i64) as ref u32+ @store32(p, value as i32)+}++/// A bounded LCS diff. If the matrix would exceed the budget, fall back to a+/// common-prefix/suffix replacement, which is conservative but never allocates+/// memory proportional to the product of the file lengths.+fn build_ops(a: list[bytes.Bytes], b: list[bytes.Bytes]) list[ref Op] = trust {+ val n: usize = @len(a)+ val m: usize = @len(b)+ val cells: u64 = ((n as u64) + 1) * ((m as u64) + 1)+ if cells > 8000000 {+ return fallback_ops(a, b)+ }+ val cols: usize = m + 1+ val dp: ref u32 = @alloc((cells as usize) * 4) as ref u32+ @memset(dp as ref void, 0, (cells as usize) * 4)+ val i: mut usize = 1+ for i <= n {+ val j: mut usize = 1+ for j <= m {+ if bytes.Bytes.eql(line_at(a, i - 1), line_at(b, j - 1)) {+ lcs_set(dp, i * cols + j, lcs_get(dp, (i - 1) * cols + (j - 1)) + 1)+ } else {+ val up: u32 = lcs_get(dp, (i - 1) * cols + j)+ val left: u32 = lcs_get(dp, i * cols + (j - 1))+ val best: mut u32 = left+ if up > best {+ best = up+ }+ lcs_set(dp, i * cols + j, best)+ }+ j+++ }+ i+++ }+ val ops: mut list[ref Op] = lists.new[ref Op]()+ val oi: mut usize = n+ val oj: mut usize = m+ for oi > 0 || oj > 0 {+ if oi > 0 && oj > 0 && bytes.Bytes.eql(line_at(a, oi - 1), line_at(b, oj - 1)) {+ @append(ops, new_op(OP_CONTEXT, oi - 1, oj - 1))+ oi--+ oj--+ } elif oj > 0+ && (oi == 0 || lcs_get(dp, oi * cols + (oj - 1)) >= lcs_get(dp, (oi - 1) * cols + oj)) {+ @append(ops, new_op(OP_ADD, 0, oj - 1))+ oj--+ } else {+ @append(ops, new_op(OP_DEL, oi - 1, 0))+ oi--+ }+ }+ reverse_ops(ops)+ @free(dp as ref void)+ return ops+}++fn fallback_ops(a: list[bytes.Bytes], b: list[bytes.Bytes]) list[ref Op] = trust {+ val n: usize = @len(a)+ val m: usize = @len(b)+ val ops: mut list[ref Op] = lists.new[ref Op]()+ val prefix: mut usize = 0+ for prefix < n && prefix < m {+ if !bytes.Bytes.eql(line_at(a, prefix), line_at(b, prefix)) {+ break+ }+ prefix+++ }+ val suffix: mut usize = 0+ for suffix < n - prefix && suffix < m - prefix {+ if !bytes.Bytes.eql(+ line_at(a, n - 1 - suffix),+ line_at(b, m - 1 - suffix)+ ) {+ break+ }+ suffix+++ }+ val i: mut usize = 0+ for i < prefix {+ @append(ops, new_op(OP_CONTEXT, i, i))+ i+++ }+ val di: mut usize = prefix+ for di < n - suffix {+ @append(ops, new_op(OP_DEL, di, 0))+ di+++ }+ val ai: mut usize = prefix+ for ai < m - suffix {+ @append(ops, new_op(OP_ADD, 0, ai))+ ai+++ }+ val s: mut usize = 0+ for s < suffix {+ @append(ops, new_op(OP_CONTEXT, n - suffix + s, m - suffix + s))+ s+++ }+ return ops+}++fn new_hunk(start: usize, end: usize, lines: list[bytes.Bytes]) ref Hunk = trust {+ val h: mut ref Hunk = @alloc(@sizeof(Hunk)) as ref Hunk+ h.start = start+ h.end = end+ h.lines = lines+ return h+}++fn free_hunks(hs: list[ref Hunk]) void = trust {+ for h in hs {+ @listfree(h.lines)+ val p: mut ref void = h as ref void+ @free(p)+ }+ @listfree(hs)+}++fn hunk_at(hs: list[ref Hunk], i: usize) ref Hunk = trust {+ val o = @get(hs, i)+ if o is some h {+ return h+ }+ assert false+ return none+}++fn hunks_from_ops(side: list[bytes.Bytes], ops: list[ref Op]) list[ref Hunk] = trust {+ val out: mut list[ref Hunk] = lists.new[ref Hunk]()+ val nops: usize = @len(ops)+ val i: mut usize = 0+ val base_pos: mut usize = 0+ for i < nops {+ val op: ref Op = op_at(ops, i)+ if op.tag == OP_CONTEXT {+ base_pos+++ i+++ } else {+ val start: usize = base_pos+ val lines: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for i < nops {+ val inner: ref Op = op_at(ops, i)+ if inner.tag == OP_CONTEXT {+ break+ }+ if inner.tag == OP_DEL {+ base_pos+++ } else {+ @append(lines, line_at(side, inner.bi))+ }+ i+++ }+ @append(out, new_hunk(start, base_pos, lines))+ }+ }+ return out+}++fn diff_hunks(base: list[bytes.Bytes], side: list[bytes.Bytes]) list[ref Hunk] = trust {+ val ops: list[ref Op] = build_ops(base, side)+ val hs: list[ref Hunk] = hunks_from_ops(side, ops)+ free_ops(ops)+ return hs+}++pub fn free_edit(r: EditResult) void = trust {+ if r.data.ptr != none {+ val dp: mut ref void = r.data.ptr as ref void+ @free(dp)+ }+ for x in r.ranges {+ val xp: mut ref void = x as ref void+ @free(xp)+ }+ @listfree(r.ranges)+}++fn append_range(+ out: mut buf.Buf,+ lines: list[bytes.Bytes],+ start: usize,+ end: usize+) void = trust {+ val i: mut usize = start+ for i < end && i < @len(lines) {+ buf.Buf.put_bytes(out, line_at(lines, i))+ i+++ }+}++fn apply_hunks(+ out: mut buf.Buf,+ base: list[bytes.Bytes],+ from: usize,+ to: usize,+ hs: list[ref Hunk],+ first: usize,+ last: usize+) void = trust {+ val pos: mut usize = from+ val k: mut usize = first+ for k < last {+ val h: ref Hunk = hunk_at(hs, k)+ if h.start > pos && h.start <= to {+ append_range(out, base, pos, h.start)+ }+ for l in h.lines {+ buf.Buf.put_bytes(out, l)+ }+ if h.end > pos {+ pos = h.end+ }+ k+++ }+ if pos < to {+ append_range(out, base, pos, to)+ }+}++fn map_pos(hs: list[ref Hunk], pos: usize) usize = trust {+ val out: mut usize = pos+ for h in hs {+ if h.end <= pos {+ val old: usize = h.end - h.start+ val new: usize = @len(h.lines)+ if new >= old {+ out = out + (new - old)+ } else {+ out = out - (old - new)+ }+ } elif h.start < pos {+ val old: usize = pos - h.start+ val new: usize = @len(h.lines)+ if new >= old {+ out = out + (new - old)+ } else {+ out = out - (old - new)+ }+ break+ } else {+ break+ }+ }+ return out+}++fn same_hunks(+ ours: list[ref Hunk],+ of: usize,+ ol: usize,+ theirs: list[ref Hunk],+ tf: usize,+ tl: usize+) bool = trust {+ val a_buf: mut buf.Buf = buf.new(64)+ val b_buf: mut buf.Buf = buf.new(64)+ val k: mut usize = of+ for k < ol {+ val h = hunk_at(ours, k)+ for l in h.lines {+ buf.Buf.put_bytes(a_buf, l)+ }+ k+++ }+ val j: mut usize = tf+ for j < tl {+ val h2 = hunk_at(theirs, j)+ for l2 in h2.lines {+ buf.Buf.put_bytes(b_buf, l2)+ }+ j+++ }+ val same: bool = bytes.Bytes.eql(buf.Buf.view(a_buf), buf.Buf.view(b_buf))+ buf.Buf.free(a_buf)+ buf.Buf.free(b_buf)+ return same+}++/// Merge three line lists. The returned data is owned by the caller.+pub fn merge_lines(+ base: list[bytes.Bytes],+ ours: list[bytes.Bytes],+ theirs: list[bytes.Bytes],+ adjacent_merge: bool+) EditResult = trust {+ val ours_h: list[ref Hunk] = diff_hunks(base, ours)+ val theirs_h: list[ref Hunk] = diff_hunks(base, theirs)+ val out: mut buf.Buf = buf.new(4096)+ val ranges: mut list[ref Range] = lists.new[ref Range]()+ val conflicted: mut bool = false++ val oi: mut usize = 0+ val ti: mut usize = 0+ val pos: mut usize = 0+ for oi < @len(ours_h) || ti < @len(theirs_h) {+ val o_start: mut usize = 0+ val t_start: mut usize = 0+ val have_o: mut bool = false+ val have_t: mut bool = false+ if oi < @len(ours_h) {+ o_start = hunk_at(ours_h, oi).start+ have_o = true+ }+ if ti < @len(theirs_h) {+ t_start = hunk_at(theirs_h, ti).start+ have_t = true+ }+ val take_ours_cluster: mut bool = false+ if have_o && (!have_t || o_start <= t_start) {+ take_ours_cluster = true+ }+ val cluster_start: mut usize = t_start+ if take_ours_cluster {+ cluster_start = o_start+ }+ val of: usize = oi+ val tf: usize = ti+ val mut_o_last: mut usize = of+ val mut_t_last: mut usize = tf+ val mut_end: mut usize = cluster_start+ val mut_seen_o: mut bool = false+ val mut_seen_t: mut bool = false+ for {+ val mut_progress: mut bool = false+ if mut_o_last < @len(ours_h) {+ val h: ref Hunk = hunk_at(ours_h, mut_o_last)+ val include: mut bool = h.start <= mut_end+ if mut_o_last == of {+ include = h.start <= mut_end+ } elif adjacent_merge {+ include = h.start < mut_end+ } else {+ include = h.start <= mut_end+ }+ if include {+ mut_seen_o = true+ mut_o_last+++ if h.end > mut_end {+ mut_end = h.end+ }+ mut_progress = true+ }+ }+ if mut_t_last < @len(theirs_h) {+ val h2: ref Hunk = hunk_at(theirs_h, mut_t_last)+ val include2: mut bool = h2.start <= mut_end+ if mut_t_last == tf {+ include2 = h2.start <= mut_end+ } elif adjacent_merge {+ include2 = h2.start < mut_end+ } else {+ include2 = h2.start <= mut_end+ }+ if include2 {+ mut_seen_t = true+ mut_t_last+++ if h2.end > mut_end {+ mut_end = h2.end+ }+ mut_progress = true+ }+ }+ if !mut_progress {+ break+ }+ }+ if mut_end < cluster_start {+ mut_end = cluster_start+ }+ if mut_seen_o && !mut_seen_t {+ apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)+ pos = mut_end+ oi = mut_o_last+ ti = mut_t_last+ } elif mut_seen_t && !mut_seen_o {+ apply_hunks(out, base, pos, mut_end, theirs_h, tf, mut_t_last)+ pos = mut_end+ oi = mut_o_last+ ti = mut_t_last+ } else {+ if same_hunks(ours_h, of, mut_o_last, theirs_h, tf, mut_t_last) {+ apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)+ pos = mut_end+ } else {+ conflicted = true+ apply_hunks(out, base, pos, mut_end, ours_h, of, mut_o_last)+ val r: mut ref Range = @alloc(@sizeof(Range)) as ref Range+ r.base_start = cluster_start+ r.base_end = mut_end+ r.ours_start = map_pos(ours_h, cluster_start)+ r.ours_end = map_pos(ours_h, mut_end)+ r.theirs_start = map_pos(theirs_h, cluster_start)+ r.theirs_end = map_pos(theirs_h, mut_end)+ @append(ranges, r)+ pos = mut_end+ }+ oi = mut_o_last+ ti = mut_t_last+ }+ }+ if pos < @len(base) {+ append_range(out, base, pos, @len(base))+ }+ val data: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(out))+ buf.Buf.free(out)+ free_hunks(ours_h)+ free_hunks(theirs_h)+ return EditResult{conflicted: conflicted, data: data, ranges: ranges}+}++/// Merge three blob contents. Returns the merged text (owned) and ranges.+fn merge_blobs_inner(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ base_id: objid.Id,+ ours_id: objid.Id,+ theirs_id: objid.Id,+ adjacent_merge: bool,+ use_cache: bool,+ tx: ref txnmod.Txn+) option[EditResult] = trust {+ val b_opt: mut option[bytes.Bytes] = none+ val o_opt: mut option[bytes.Bytes] = none+ val t_opt: mut option[bytes.Bytes] = none+ if use_cache {+ b_opt = content.read_blob_tx(handles, base_id, git, has_git, tx)+ o_opt = content.read_blob_tx(handles, ours_id, git, has_git, tx)+ t_opt = content.read_blob_tx(handles, theirs_id, git, has_git, tx)+ } else {+ b_opt = content.read_blob(handles, base_id, git, has_git)+ o_opt = content.read_blob(handles, ours_id, git, has_git)+ t_opt = content.read_blob(handles, theirs_id, git, has_git)+ }+ if !has_read(b_opt) || !has_read(o_opt) || !has_read(t_opt) {+ free_read(b_opt)+ free_read(o_opt)+ free_read(t_opt)+ return none+ }+ val b = lines_of(b_opt)+ val o = lines_of(o_opt)+ val t = lines_of(t_opt)+ val result: EditResult = merge_lines(b, o, t, adjacent_merge)+ @listfree(b)+ @listfree(o)+ @listfree(t)+ free_read(b_opt)+ free_read(o_opt)+ free_read(t_opt)+ return some result+}++pub fn merge_blobs(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ base_id: objid.Id,+ ours_id: objid.Id,+ theirs_id: objid.Id,+ adjacent_merge: bool+) option[EditResult] = trust {+ return merge_blobs_inner(+ handles,+ git,+ has_git,+ base_id,+ ours_id,+ theirs_id,+ adjacent_merge,+ false,+ none+ )+}++pub fn merge_blobs_tx(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ base_id: objid.Id,+ ours_id: objid.Id,+ theirs_id: objid.Id,+ adjacent_merge: bool,+ tx: ref txnmod.Txn+) option[EditResult] = trust {+ return merge_blobs_inner(+ handles,+ git,+ has_git,+ base_id,+ ours_id,+ theirs_id,+ adjacent_merge,+ true,+ tx+ )+}++fn lines_of(d: option[bytes.Bytes]) list[bytes.Bytes] = trust {+ if d is some data {+ return split_lines(data)+ }+ return lists.new[bytes.Bytes]()+}++fn has_read(d: option[bytes.Bytes]) bool = trust {+ if d is some _ {+ return true+ }+ return false+}++fn free_read(d: option[bytes.Bytes]) void = trust {+ if d is some data {+ @free(data.ptr as ref void)+ }+}++/// Build a blob object for `lines` and add it to the transaction.+pub fn add_blob(+ tx: mut ref txnmod.Txn,+ lines: list[bytes.Bytes]+) objid.Id = trust {+ val b: mut buf.Buf = buf.new(4096)+ for l in lines {+ buf.Buf.put_bytes(b, l)+ }+ val built: ref blob.BlobBuild = blob.build(b.ptr, b.len)+ val id: objid.Id = copy_root(built)+ val i: mut usize = 0+ for i < @len(built.objects) {+ val ro = @get(built.objects, i)+ if ro is some obj {+ val orf: mut ref raw.RawObject = obj+ val oid: objid.Id = objid.id(orf.id)+ val _ = txnmod.add_known(tx, orf.type_byte, oid, orf.body)+ orf.body = bytes.empty()+ }+ i+++ }+ blob.free_build(built)+ buf.Buf.free(b)+ return id+}++fn copy_root(built: ref blob.BlobBuild) objid.Id = trust {+ val id: objid.Id = blob.root_id(built)+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}--- /dev/null+++ b/veins/src/merge/rename.sx@@ -0,0 +1,735 @@+/// Rename detection and rename maps used by the merge engine.+///+/// Recorded renames (`renames_state = 1`) are authoritative. Imported commits+/// use heuristics: exact content matches first, then a similarity score based+/// on chunk IDs for large blobs and lines for small ones.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val commit = use("../object/commit.sx")+val tree = use("../object/tree.sx")+val treewalk = use("../object/treewalk.sx")+val blob = use("../object/blob.sx")+val content = use("../object/content.sx")+val graph = use("../object/graph.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val object = use("../git/object.sx")+val files = use("../io/files.sx")+val txnmod = use("../store/txn.sx")++pub type Entry = {+ from: mut bytes.Bytes+ to: mut bytes.Bytes+}++pub type RenameMap = {+ entries: mut list[ref Entry]+}++pub fn empty() RenameMap = {+ return RenameMap{entries: lists.new[ref Entry]()}+}++fn new_entry(from: bytes.Bytes, to: bytes.Bytes) ref Entry = {+ val e: mut ref Entry = @alloc(@sizeof(Entry)) as ref Entry+ e.from = bytes.Bytes.dup(from)+ e.to = bytes.Bytes.dup(to)+ return e+}++pub fn free_map(m: RenameMap) void = trust {+ for e in m.entries {+ if e.from.ptr != none {+ val fp: mut ref void = e.from.ptr as ref void+ @free(fp)+ }+ if e.to.ptr != none {+ val tp: mut ref void = e.to.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(m.entries)+}++/// Look up the destination of a base path. The result is borrowed.+pub fn lookup(m: RenameMap, path: bytes.Bytes) option[bytes.Bytes] = trust {+ for e in m.entries {+ if bytes.Bytes.eql(e.from, path) {+ return some e.to+ }+ }+ return none+}++fn apply(m: mut RenameMap, from: bytes.Bytes, to: bytes.Bytes) void = trust {+ // Compose a -> b followed by b -> c into a -> c.+ val composed: mut bool = false+ for e in m.entries {+ val em: mut ref Entry = e+ if bytes.Bytes.eql(em.to, from) {+ if em.to.ptr != none {+ val tp: mut ref void = em.to.ptr as ref void+ @free(tp)+ }+ em.to = bytes.Bytes.dup(to)+ composed = true+ }+ }+ if composed {+ return+ }+ for e in m.entries {+ val em: mut ref Entry = e+ if bytes.Bytes.eql(em.from, from) {+ if em.to.ptr != none {+ val tp: mut ref void = em.to.ptr as ref void+ @free(tp)+ }+ em.to = bytes.Bytes.dup(to)+ return+ }+ }+ @append(m.entries, new_entry(from, to))+}++fn first_parent(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ out = some graph.copy_id(pid)+ }+ }+ graph.free_loaded(lc)+ }+ return out+}++fn tree_of(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val lc_opt = graph.load_commit(handles, id)+ val out: mut option[objid.Id] = none+ if lc_opt is some lc {+ out = some graph.copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ return out+}++fn hash_line(line: bytes.Bytes) u64 = {+ val h: mut u64 = 1469598103934665603+ val i: mut usize = 0+ for i < line.len {+ h = (h ^ (bytes.Bytes.at(line, i) as u64)) * 1099511628211+ i+++ }+ return h+}++fn sort_u64(xs: mut list[u64]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut u64 = 0+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(xs, j - 1)+ val prev: mut u64 = 0+ if prev_o is some vv {+ prev = vv+ }+ if prev <= c {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn line_similarity(a: bytes.Bytes, b: bytes.Bytes) i32 = trust {+ val la: mut list[u64] = lists.new[u64]()+ val lb: mut list[u64] = lists.new[u64]()+ val start_a: mut usize = 0+ val i: mut usize = 0+ for i <= a.len {+ if i == a.len || bytes.Bytes.at(a, i) == 10 {+ @append(la, hash_line(bytes.Bytes.slice(a, start_a, i)))+ start_a = i + 1+ }+ i+++ }+ val start_b: mut usize = 0+ val j: mut usize = 0+ for j <= b.len {+ if j == b.len || bytes.Bytes.at(b, j) == 10 {+ @append(lb, hash_line(bytes.Bytes.slice(b, start_b, j)))+ start_b = j + 1+ }+ j+++ }+ sort_u64(la)+ sort_u64(lb)+ val ia: mut usize = 0+ val ib: mut usize = 0+ val inter: mut usize = 0+ for ia < @len(la) && ib < @len(lb) {+ val va = @get(la, ia)+ val vb = @get(lb, ib)+ val a_val: mut u64 = 0+ val b_val: mut u64 = 0+ if va is some x {+ a_val = x+ }+ if vb is some y {+ b_val = y+ }+ if a_val == b_val {+ inter+++ ia+++ ib+++ } elif a_val < b_val {+ ia+++ } else {+ ib+++ }+ }+ val total_union: usize = @len(la) + @len(lb) - inter+ @listfree(la)+ @listfree(lb)+ if total_union == 0 {+ return 100+ }+ return ((inter * 100) / total_union) as i32+}++fn read_body_any(+ handles: list[ref store.Handle],+ id: objid.Id,+ expected: u8,+ use_cache: bool,+ tx: ref txnmod.Txn+) option[bytes.Bytes] = trust {+ if use_cache {+ val cached = txnmod.find_cached(tx, expected, id)+ if cached is some b {+ return some bytes.Bytes.dup(b)+ }+ }+ return state.read_body(handles, id, expected)+}++fn chunk_ids(+ handles: list[ref store.Handle],+ id: objid.Id,+ out: mut list[objid.Id],+ depth: usize,+ use_cache: bool,+ tx: ref txnmod.Txn+) bool = trust {+ if depth > 64 {+ return false+ }+ val body_opt = read_body_any(handles, id, types.BLOB, use_cache, tx)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return false+ }+ }+ val decoded = blob.decode(body)+ val b: mut ref blob.Blob = none+ match decoded {+ ok x => {+ b = x+ }+ err _ => {+ files.free_buffer(body)+ return false+ }+ }+ val good: mut bool = true+ if b.form == blob.FORM_LEAF {+ for e in b.entries {+ val cp: ref u8 = @alloc(32) as ref u8+ @memcpy(cp as ref void, e.id.ptr as ref void, 32)+ @append(out, objid.id(cp))+ }+ } elif b.form == blob.FORM_INTERIOR {+ for e in b.entries {+ if !chunk_ids(handles, e.id, out, depth + 1, use_cache, tx) {+ good = false+ break+ }+ }+ }+ blob.free_blob(b)+ files.free_buffer(body)+ return good+}++fn chunk_similarity(+ handles: list[ref store.Handle],+ a: objid.Id,+ b: objid.Id,+ use_cache: bool,+ tx: ref txnmod.Txn+) i32 = trust {+ val ca: mut list[objid.Id] = lists.new[objid.Id]()+ val cb: mut list[objid.Id] = lists.new[objid.Id]()+ val oka: bool = chunk_ids(handles, a, ca, 0, use_cache, tx)+ val okb: bool = chunk_ids(handles, b, cb, 0, use_cache, tx)+ val result: mut i32 = 0+ if oka && okb {+ val inter: mut usize = 0+ for x in ca {+ for y in cb {+ if objid.Id.eql(x, y) {+ inter+++ break+ }+ }+ }+ val total_union: usize = @len(ca) + @len(cb) - inter+ if total_union > 0 {+ result = ((inter * 100) / total_union) as i32+ }+ }+ graph.free_ids(ca)+ graph.free_ids(cb)+ return result+}++/// Similarity in percent. Uses chunk IDs for large blobs and line overlap for+/// small ones. Returns 0 when either blob cannot be read.+pub fn similarity(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ a: objid.Id,+ b: objid.Id,+ use_cache: bool,+ tx: ref txnmod.Txn+) i32 = trust {+ if objid.Id.eql(a, b) {+ return 100+ }+ val ca = content.read_blob_tx(handles, a, git, has_git, tx)+ val cb = content.read_blob_tx(handles, b, git, has_git, tx)+ if ca is some da {+ if cb is some db {+ val res: mut i32 = 0+ if da.len >= 131072 && db.len >= 131072 {+ res = chunk_similarity(handles, a, b, use_cache, tx)+ }+ if res == 0 {+ res = line_similarity(da, db)+ }+ files.free_buffer(da)+ files.free_buffer(db)+ return res+ }+ files.free_buffer(da)+ return 0+ }+ if cb is some db2 {+ files.free_buffer(db2)+ }+ return 0+}++type Pair = {+ old_path: mut bytes.Bytes+ new_path: mut bytes.Bytes+ old_id: mut objid.Id+ new_id: mut objid.Id+ score: mut i32+ old_used: mut bool+ new_used: mut bool+}++fn new_pair(+ old_path: bytes.Bytes,+ new_path: bytes.Bytes,+ old_id: objid.Id,+ new_id: objid.Id,+ score: i32+) ref Pair = trust {+ val p: mut ref Pair = @alloc(@sizeof(Pair)) as ref Pair+ p.old_path = old_path+ p.new_path = new_path+ p.old_id = graph.copy_id(old_id)+ p.new_id = graph.copy_id(new_id)+ p.score = score+ p.old_used = false+ p.new_used = false+ return p+}++fn free_pairs(ps: list[ref Pair]) void = trust {+ for p in ps {+ val op: mut ref void = p.old_id.ptr as ref void+ @free(op)+ val np: mut ref void = p.new_id.ptr as ref void+ @free(np)+ val pp: mut ref void = p as ref void+ @free(pp)+ }+ @listfree(ps)+}++pub fn sort_renames(rs: mut list[ref commit.Rename]) void = trust {+ val i: mut usize = 1+ for i < @len(rs) {+ val cur = @get(rs, i)+ val c: mut ref commit.Rename = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(rs, j - 1)+ val prev: mut ref commit.Rename = none+ if prev_o is some vv {+ prev = vv+ }+ val cmp: mut i64 = bytes.Bytes.cmp(prev.to_path, c.to_path)+ if prev.parent_index < c.parent_index {+ cmp = -1+ } elif prev.parent_index > c.parent_index {+ cmp = 1+ }+ if cmp <= 0 {+ break+ }+ @set(rs, j, prev)+ j--+ }+ @set(rs, j, c)+ i+++ }+}++/// Detect renames between two trees. `similar_pct` is 0 to disable similarity+/// matching. Returned renames are sorted by `(parent_index, to_path)`.+fn detect_inner(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ old_tree: option[objid.Id],+ new_tree: option[objid.Id],+ similar_pct: i32,+ parent_index: u64,+ use_cache: bool,+ tx: ref txnmod.Txn+) list[ref commit.Rename] = trust {+ val old: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()+ val new: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()+ if use_cache {+ old = treewalk.flatten_or_empty_tx(handles, old_tree, tx)+ new = treewalk.flatten_or_empty_tx(handles, new_tree, tx)+ } else {+ old = treewalk.flatten_or_empty(handles, old_tree)+ new = treewalk.flatten_or_empty(handles, new_tree)+ }+ val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val deleted: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()+ val added: mut list[ref treewalk.FlatEntry] = lists.new[ref treewalk.FlatEntry]()+ for e in old {+ if treewalk.lookup(new, e.path) is none {+ @append(deleted, e)+ }+ }+ for n in new {+ if treewalk.lookup(old, n.path) is none {+ @append(added, n)+ }+ }+ val used_old: ref u8 = @alloc(@len(deleted) + 1) as ref u8+ @memset(used_old as ref void, 0, @len(deleted) + 1)+ val used_new: ref u8 = @alloc(@len(added) + 1) as ref u8+ @memset(used_new as ref void, 0, @len(added) + 1)++ // Exact content matches first.+ val di: mut usize = 0+ for di < @len(deleted) {+ val d = @get(deleted, di)+ if d is some de {+ if @load8(@ptradd(used_old, di as i64)) == 0 {+ val ai: mut usize = 0+ for ai < @len(added) {+ val a = @get(added, ai)+ if a is some ae {+ if @load8(@ptradd(used_new, ai as i64)) == 0+ && objid.Id.eql(de.target, ae.target) {+ @append(+ out,+ commit.new_rename(+ parent_index,+ 0,+ bytes.Bytes.dup(de.path),+ bytes.Bytes.dup(ae.path)+ )+ )+ @store8(@ptradd(used_old, di as i64), 1)+ @store8(@ptradd(used_new, ai as i64), 1)+ break+ }+ }+ ai+++ }+ }+ }+ di+++ }++ if similar_pct > 0 {+ val pairs: mut list[ref Pair] = lists.new[ref Pair]()+ val candidate_limit: usize = 5000+ val di2: mut usize = 0+ for di2 < @len(deleted) {+ val d = @get(deleted, di2)+ if d is some de {+ if @load8(@ptradd(used_old, di2 as i64)) == 0+ && (de.kind == tree.KIND_FILE || de.kind == tree.KIND_EXECUTABLE) {+ val ai2: mut usize = 0+ for ai2 < @len(added) && @len(pairs) < candidate_limit {+ val a = @get(added, ai2)+ if a is some ae {+ if @load8(@ptradd(used_new, ai2 as i64)) == 0+ && (ae.kind == tree.KIND_FILE || ae.kind == tree.KIND_EXECUTABLE) {+ @append(+ pairs,+ new_pair(+ de.path,+ ae.path,+ de.target,+ ae.target,+ similarity(handles, git, has_git, de.target, ae.target, use_cache, tx)+ )+ )+ }+ }+ ai2+++ }+ }+ }+ di2+++ }+ // Greedy best-score assignment.+ for {+ val best: mut i32 = -1+ val best_i: mut i32 = -1+ val pi: mut usize = 0+ for pi < @len(pairs) {+ val p = @get(pairs, pi)+ if p is some pp {+ if !pp.old_used && !pp.new_used && pp.score > best {+ best = pp.score+ best_i = pi as i32+ }+ }+ pi+++ }+ if best_i < 0 || best < similar_pct {+ break+ }+ val chosen = @get(pairs, best_i as usize)+ if chosen is some cp {+ cp.old_used = true+ cp.new_used = true+ @append(+ out,+ commit.new_rename(+ parent_index,+ 0,+ bytes.Bytes.dup(cp.old_path),+ bytes.Bytes.dup(cp.new_path)+ )+ )+ }+ }+ free_pairs(pairs)+ }++ @free(used_old as ref void)+ @free(used_new as ref void)+ // `deleted` and `added` hold borrowed pointers into `old` and `new`.+ @listfree(deleted)+ @listfree(added)+ treewalk.free_flat(old)+ treewalk.free_flat(new)+ sort_renames(out)+ return out+}++pub fn detect(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ old_tree: option[objid.Id],+ new_tree: option[objid.Id],+ similar_pct: i32,+ parent_index: u64+) list[ref commit.Rename] = trust {+ return detect_inner(+ handles,+ git,+ has_git,+ old_tree,+ new_tree,+ similar_pct,+ parent_index,+ false,+ none+ )+}++pub fn detect_tx(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ old_tree: option[objid.Id],+ new_tree: option[objid.Id],+ similar_pct: i32,+ parent_index: u64,+ tx: ref txnmod.Txn+) list[ref commit.Rename] = trust {+ return detect_inner(+ handles,+ git,+ has_git,+ old_tree,+ new_tree,+ similar_pct,+ parent_index,+ true,+ tx+ )+}++fn apply_commit(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ cid: objid.Id,+ m: mut RenameMap+) void = trust {+ val lc_opt = graph.load_commit(handles, cid)+ val lc: mut ref graph.LoadedCommit = none+ match lc_opt {+ some lc0 => {+ lc = lc0+ }+ none => {+ return+ }+ }+ if lc.c.renames_state == commit.RENAMES_RECORDED {+ for r in lc.c.renames {+ if r.parent_index == 0 {+ apply(m, r.from_path, r.to_path)+ }+ }+ } else {+ val parent_opt = first_parent(handles, cid)+ if parent_opt is some pid {+ val pt = tree_of(handles, pid)+ val ct = tree_of(handles, cid)+ val rs = detect(handles, git, has_git, pt, ct, 50, 0)+ for r in rs {+ apply(m, r.from_path, r.to_path)+ if r.from_path.ptr != none {+ val fp: mut ref void = r.from_path.ptr as ref void+ @free(fp)+ }+ if r.to_path.ptr != none {+ val tp: mut ref void = r.to_path.ptr as ref void+ @free(tp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rs)+ free_tree_opt(pt)+ free_tree_opt(ct)+ }+ }+ graph.free_loaded(lc)+}++fn free_tree_opt(t: option[objid.Id]) void = trust {+ if t is some id {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+}++/// Compute the rename map from `base` to `side`.+pub fn map_from(+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ base: objid.Id,+ side: objid.Id+) RenameMap = trust {+ val m: mut RenameMap = empty()+ if objid.Id.eql(base, side) {+ return m+ }+ // Follow the first-parent chain from the side back to the base.+ val chain: mut list[objid.Id] = lists.new[objid.Id]()+ val cur: mut objid.Id = graph.copy_id(side)+ val reached: mut bool = false+ val depth: mut usize = 0+ for depth < 100000 {+ if objid.Id.eql(cur, base) {+ reached = true+ @free(cur.ptr as ref void)+ cur = objid.Id{ptr: none}+ break+ }+ @append(chain, cur)+ val p = first_parent(handles, cur)+ if p is some pid {+ cur = pid+ } else {+ cur = objid.Id{ptr: none}+ break+ }+ depth+++ }+ if cur.ptr != none {+ @free(cur.ptr as ref void)+ }+ if !reached {+ graph.free_ids(chain)+ return m+ }+ // chain is side .. child-of-base; apply in reverse.+ val i: mut usize = @len(chain)+ for i > 0 {+ i--+ val o = @get(chain, i)+ if o is some cid {+ apply_commit(handles, git, has_git, cid, m)+ }+ }+ graph.free_ids(chain)+ return m+}--- /dev/null+++ b/veins/src/merge/resolutions.sx@@ -0,0 +1,72 @@+/// Resolution memory (`.veins/resolutions/`).+///+/// The key is BLAKE3 of the simplified conflict object body. The value is the+/// resolved blob ID, stored as hex text. Only exact conflict matches are reused.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val objid = use("../object/id.sx")+val b3 = use("../crypto/blake3.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")++fn key_hex(body: bytes.Bytes) ref u8 = trust {+ val digest: ref u8 = @alloc(32) as ref u8+ b3.hash(body.ptr, body.len, digest)+ val out: ref u8 = @alloc(65) as ref u8+ objid.hex_encode(digest, 32, out)+ @store8(@ptradd(out, 64), 0)+ @free(digest as ref void)+ return out+}++fn key_path(repo: layout.Repo, key: ref u8) str.StringView = trust {+ val dir: str.StringView = layout.resolutions_dir(repo)+ val path: str.StringView = files.join(dir, str.from_cstr(key))+ files.free_path(dir)+ return path+}++/// Look up the recorded resolution for a conflict body.+pub fn lookup(repo: layout.Repo, body: bytes.Bytes) option[objid.Id] = trust {+ val key: ref u8 = key_hex(body)+ val path: str.StringView = key_path(repo, key)+ val data_opt = files.read_all(path)+ files.free_path(path)+ @free(key as ref void)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ return none+ }+ }+ val result: mut option[objid.Id] = none+ if data.len >= 64 {+ val raw: ref u8 = @alloc(32) as ref u8+ if objid.hex_decode(data.ptr, 32, raw) {+ result = some objid.id(raw)+ } else {+ @free(raw as ref void)+ }+ }+ files.free_buffer(data)+ return result+}++/// Record that the conflict with `body` resolves to `blob`.+pub fn record(repo: layout.Repo, body: bytes.Bytes, blob: objid.Id) bool = trust {+ if blob.ptr == none {+ return false+ }+ val key: ref u8 = key_hex(body)+ val path: str.StringView = key_path(repo, key)+ val hex: ref u8 = objid.Id.hex(blob)+ val wrote: bool = files.write_all(path, bytes.bytes(hex, 64))+ @free(hex as ref void)+ files.free_path(path)+ @free(key as ref void)+ return wrote+}--- /dev/null+++ b/veins/src/merge/treemerge.sx@@ -0,0 +1,834 @@+/// Tree-level merge: flatten signed tree terms, apply renames, merge each path,+/// and rebuild a canonical tree.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val treewalk = use("../object/treewalk.sx")+val conflict = use("../object/conflict.sx")+val store = use("../store/store.sx")+val txnmod = use("../store/txn.sx")+val layout = use("../store/layout.sx")+val object = use("../git/object.sx")+val algebra = use("algebra.sx")+val filemerge = use("filemerge.sx")+val rename = use("rename.sx")+val resolutions = use("resolutions.sx")+val attributes = use("attributes.sx")++pub type TreeTerm = {+ positive: mut bool+ present: mut bool+ id: mut objid.Id+}++pub type EntryTerm = {+ positive: mut bool+ present: mut bool+ kind: mut u8+ target: mut objid.Id+}++pub type Outcome = {+ tree: mut objid.Id+ rerere: mut usize+}++type OrigEntry = {+ term: mut usize+ path: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++type OutEntry = {+ path: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++fn copy_id(id: objid.Id) objid.Id = trust {+ if id.ptr == none {+ return objid.id(none)+ }+ val out: ref u8 = @alloc(32) as ref u8+ @memcpy(out as ref void, id.ptr as ref void, 32)+ return objid.id(out)+}++fn free_id(id: objid.Id) void = trust {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+}++fn new_orig(term: usize, path: bytes.Bytes, kind: u8, target: objid.Id) ref OrigEntry = trust {+ val e: mut ref OrigEntry = @alloc(@sizeof(OrigEntry)) as ref OrigEntry+ e.term = term+ e.path = bytes.Bytes.dup(path)+ e.kind = kind+ e.target = copy_id(target)+ return e+}++fn free_orig(es: list[ref OrigEntry]) void = trust {+ for e in es {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ free_id(e.target)+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(es)+}++fn new_out(path: bytes.Bytes, kind: u8, target: objid.Id) ref OutEntry = trust {+ val e: mut ref OutEntry = @alloc(@sizeof(OutEntry)) as ref OutEntry+ e.path = bytes.Bytes.dup(path)+ e.kind = kind+ e.target = copy_id(target)+ return e+}++fn free_out(es: list[ref OutEntry]) void = trust {+ for e in es {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ free_id(e.target)+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(es)+}++fn find_orig(+ es: list[ref OrigEntry],+ term: usize,+ path: bytes.Bytes+) option[ref OrigEntry] = trust {+ for e in es {+ if e.term == term && bytes.Bytes.eql(e.path, path) {+ return some e+ }+ }+ return none+}++fn has_prefix(path: bytes.Bytes, prefix: bytes.Bytes) bool = trust { if path.len <= prefix.len {+ return false+ }+ if !bytes.Bytes.starts_with(path, prefix) {+ return false+ }+ return bytes.Bytes.at(path, prefix.len) == 47+}++fn list_has_path(xs: list[bytes.Bytes], path: bytes.Bytes) bool = trust {+ for x in xs {+ if bytes.Bytes.eql(x, path) {+ return true+ }+ }+ return false+}++fn sort_out(xs: mut list[ref OutEntry]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref OutEntry = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(xs, j - 1)+ val prev: mut ref OutEntry = none+ if prev_o is some vv {+ prev = vv+ }+ if bytes.Bytes.cmp(prev.path, c.path) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn sort_paths(xs: mut list[bytes.Bytes]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut bytes.Bytes = bytes.empty()+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(xs, j - 1)+ val prev: mut bytes.Bytes = bytes.empty()+ if prev_o is some vv {+ prev = vv+ }+ if bytes.Bytes.cmp(prev, c) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn empty_tree(tx: mut ref txnmod.Txn) objid.Id = trust {+ val entries: list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val encoded = tree.encode(entries)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ return objid.id(none)+ }+ }+ val id: objid.Id = txnmod.add_object(tx, types.TREE, body)+ @listfree(entries)+ return id+}++fn component_end(path: bytes.Bytes, start: usize) usize = trust {+ val i: mut usize = start+ for i < path.len && bytes.Bytes.at(path, i) != 47 {+ i+++ }+ return i+}++fn build_level(+ tx: mut ref txnmod.Txn,+ entries: list[ref OutEntry],+ start: usize,+ end: usize,+ prefix_len: usize+) objid.Id = trust {+ val out: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val i: mut usize = start+ for i < end {+ val e_o = @get(entries, i)+ if e_o is some e {+ val name_end: usize = component_end(e.path, prefix_len)+ val name: bytes.Bytes = bytes.Bytes.slice(e.path, prefix_len, name_end)+ if name_end == e.path.len {+ @append(out, tree.entry(bytes.Bytes.dup(name), e.kind, e.target))+ i+++ } else {+ val j: mut usize = i + 1+ for j < end {+ val f_o = @get(entries, j)+ if f_o is some f {+ val f_end: usize = component_end(f.path, prefix_len)+ if f_end != name_end {+ break+ }+ val f_name: bytes.Bytes = bytes.Bytes.slice(f.path, prefix_len, f_end)+ if !bytes.Bytes.eql(f_name, name) {+ break+ }+ }+ j+++ }+ val child: objid.Id = build_level(tx, entries, i, j, name_end + 1)+ @append(out, tree.entry(bytes.Bytes.dup(name), tree.KIND_SUBTREE, child))+ i = j+ }+ } else {+ i+++ }+ }+ val encoded = tree.encode(out)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ for e in out {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(out)+ return objid.id(none)+ }+ }+ val id: objid.Id = txnmod.add_object(tx, types.TREE, body)+ for e in out {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(out)+ return id+}++fn build_from_entries(tx: mut ref txnmod.Txn, entries: mut list[ref OutEntry]) objid.Id = trust {+ if @len(entries) == 0 {+ return empty_tree(tx)+ }+ sort_out(entries)+ return build_level(tx, entries, 0, @len(entries), 0)+}++fn build_subtree(+ tx: mut ref txnmod.Txn,+ canon: list[ref OrigEntry],+ term: usize,+ prefix: bytes.Bytes+) objid.Id = trust {+ val rels: mut list[ref OutEntry] = lists.new[ref OutEntry]()+ for e in canon {+ if e.term == term && has_prefix(e.path, prefix) {+ val rel: bytes.Bytes = bytes.Bytes.slice(e.path, prefix.len + 1, e.path.len)+ @append(rels, new_out(rel, e.kind, e.target))+ }+ }+ val id: objid.Id = build_from_entries(tx, rels)+ free_out(rels)+ return id+}++fn make_terms(+ handles: list[ref store.Handle],+ terms: list[ref TreeTerm],+ tx: ref txnmod.Txn+) list[ref OrigEntry] = trust {+ val out: mut list[ref OrigEntry] = lists.new[ref OrigEntry]()+ val i: mut usize = 0+ for i < @len(terms) {+ val o = @get(terms, i)+ if o is some t {+ if t.present {+ val flat: list[ref treewalk.FlatEntry] = treewalk.flatten_tx(handles, t.id, tx)+ for e in flat {+ @append(out, new_orig(i, e.path, e.kind, e.target))+ }+ treewalk.free_flat(flat)+ }+ }+ i+++ }+ return out+}++type CanonTarget = {+ map_index: mut usize+ target: mut bytes.Bytes+}++fn canonical_targets(+ path: bytes.Bytes,+ maps: list[ref rename.RenameMap]+) list[ref CanonTarget] = trust {+ val out: mut list[ref CanonTarget] = lists.new[ref CanonTarget]()+ val i: mut usize = 0+ for i < @len(maps) {+ val m = @get(maps, i)+ if m is some mm {+ if mm != none {+ val t = rename.lookup(mm, path)+ if t is some dest {+ val exists: mut bool = false+ for c in out {+ if bytes.Bytes.eql(c.target, dest) {+ exists = true+ }+ }+ if !exists {+ val c: mut ref CanonTarget = @alloc(@sizeof(CanonTarget)) as ref CanonTarget+ c.map_index = i+ c.target = bytes.Bytes.dup(dest)+ @append(out, c)+ }+ }+ }+ }+ i+++ }+ return out+}++fn free_canon(xs: list[ref CanonTarget]) void = trust {+ for c in xs {+ val tp: mut ref void = c.target.ptr as ref void+ @free(tp)+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(xs)+}++fn canonical_path(targets: list[ref CanonTarget], path: bytes.Bytes) bytes.Bytes = trust {+ if @len(targets) == 1 {+ val o = @get(targets, 0)+ if o is some c {+ return c.target+ }+ }+ return path+}++fn add_value(+ adds: mut list[ref conflict.ConflictValue],+ removes: mut list[ref conflict.ConflictValue],+ t: EntryTerm+) void = trust {+ if t.present {+ val v: ref conflict.ConflictValue = conflict.value(t.kind, t.target)+ if t.positive {+ @append(adds, v)+ } else {+ @append(removes, v)+ }+ } else {+ val v2: ref conflict.ConflictValue = conflict.value_absent()+ if t.positive {+ @append(adds, v2)+ } else {+ @append(removes, v2)+ }+ }+}++fn all_files(adds: list[ref conflict.ConflictValue], removes: list[ref conflict.ConflictValue]) bool = trust {+ for v in adds {+ if v.kind != tree.KIND_FILE && v.kind != tree.KIND_EXECUTABLE {+ if v.kind != 0 {+ return false+ }+ }+ }+ for v in removes {+ if v.kind != tree.KIND_FILE && v.kind != tree.KIND_EXECUTABLE {+ if v.kind != 0 {+ return false+ }+ }+ }+ return true+}++fn mode_of(kind: u8) bool = {+ return kind == tree.KIND_EXECUTABLE+}++/// Merge the executable bit for a two-add/one-remove sum. Returns -1 when the+/// mode is unresolved, 0 for regular, and 1 for executable.+fn merge_mode(+ adds: list[ref conflict.ConflictValue],+ removes: list[ref conflict.ConflictValue]+) i32 = trust {+ if @len(adds) != 2 || @len(removes) != 1 {+ return -1+ }+ val a0 = @get(adds, 0)+ val a1 = @get(adds, 1)+ val r0 = @get(removes, 0)+ val ma0: mut i32 = -1+ val ma1: mut i32 = -1+ val mr: mut i32 = -1+ if a0 is some x {+ if x.kind != 0 {+ ma0 = 0+ if mode_of(x.kind) {+ ma0 = 1+ }+ }+ }+ if a1 is some y {+ if y.kind != 0 {+ ma1 = 0+ if mode_of(y.kind) {+ ma1 = 1+ }+ }+ }+ if r0 is some z {+ if z.kind != 0 {+ mr = 0+ if mode_of(z.kind) {+ mr = 1+ }+ }+ }+ if ma0 < 0 || ma1 < 0 {+ return -1+ }+ if ma0 == ma1 {+ return ma0+ }+ if mr >= 0 && ma0 == mr {+ return ma1+ }+ if mr >= 0 && ma1 == mr {+ return ma0+ }+ return -1+}++fn make_conflict_entry(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ path: bytes.Bytes,+ sum: algebra.Sum,+ rerere: mut list[usize]+) option[ref OutEntry] = trust {+ val body: bytes.Bytes = algebra.conflict_body(sum)+ // Resolution memory applies only to file-valued conflicts.+ if all_files(sum.adds, sum.removes) {+ val memo = resolutions.lookup(repo, body)+ if memo is some blob {+ val e: ref OutEntry = new_out(path, tree.KIND_FILE, blob)+ algebra.free_sum(sum)+ val bp: mut ref void = body.ptr as ref void+ @free(bp)+ val lb: mut ref void = blob.ptr as ref void+ @free(lb)+ @append(rerere, 1)+ return some e+ }+ }+ val id: objid.Id = txnmod.add_object(tx, types.CONFLICT, body)+ algebra.free_sum(sum)+ return some new_out(path, tree.KIND_CONFLICT, id)+}++fn term_positive(terms: list[ref TreeTerm], i: usize) bool = trust {+ val o = @get(terms, i)+ if o is some t {+ return t.positive+ }+ return true+}++fn merge_entry(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ path: bytes.Bytes,+ terms: list[EntryTerm],+ adjacent_merge: bool,+ rerere: mut list[usize]+) option[ref OutEntry] = trust {+ val adds: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ val removes: mut list[ref conflict.ConflictValue] = lists.new[ref conflict.ConflictValue]()+ for t in terms {+ add_value(adds, removes, t)+ }+ val sum: algebra.Sum = algebra.simplify_tx(handles, adds, removes, tx)+ val resolved = algebra.resolved(sum)+ if resolved is some v {+ val kind: u8 = v.kind+ val target: objid.Id = v.target+ val out: mut option[ref OutEntry] = none+ if kind != 0 {+ out = some new_out(path, kind, target)+ }+ algebra.free_sum(sum)+ return out+ }+ // Try a content merge for a simple three-term file conflict.+ if all_files(sum.adds, sum.removes) && @len(sum.adds) == 2 && @len(sum.removes) == 1 {+ val a0 = @get(sum.adds, 0)+ val a1 = @get(sum.adds, 1)+ val r0 = @get(sum.removes, 0)+ val success: mut bool = true+ val base_id: mut objid.Id = objid.id_none()+ val ours_id: mut objid.Id = objid.id_none()+ val theirs_id: mut objid.Id = objid.id_none()+ val ours_kind: mut u8 = tree.KIND_FILE+ if a0 is some x {+ if x.kind != 0 {+ ours_id = x.target+ ours_kind = x.kind+ } else {+ success = false+ }+ }+ if a1 is some y {+ if y.kind != 0 {+ theirs_id = y.target+ } else {+ success = false+ }+ }+ if r0 is some z {+ if z.kind != 0 {+ base_id = z.target+ } else {+ success = false+ }+ }+ if success && !attributes.merge_binary(repo, path) {+ val merged = filemerge.merge_blobs_tx(+ handles,+ git,+ has_git,+ base_id,+ ours_id,+ theirs_id,+ adjacent_merge,+ tx+ )+ if merged is some m {+ if !m.conflicted {+ val lines: list[bytes.Bytes] = filemerge.split_lines(m.data)+ val blob_id: objid.Id = filemerge.add_blob(tx, lines)+ @listfree(lines)+ val mode: i32 = merge_mode(sum.adds, sum.removes)+ if mode >= 0 {+ val kind: mut u8 = tree.KIND_FILE+ if mode == 1 {+ kind = tree.KIND_EXECUTABLE+ }+ filemerge.free_edit(m)+ algebra.free_sum(sum)+ return some new_out(path, kind, blob_id)+ }+ free_id(blob_id)+ }+ filemerge.free_edit(m)+ }+ }+ }+ return make_conflict_entry(repo, tx, path, sum, rerere)+}++fn collect_paths(canon: list[ref OrigEntry]) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for e in canon {+ if !list_has_path(out, e.path) {+ @append(out, e.path)+ }+ }+ sort_paths(out)+ return out+}++fn has_children(canon: list[ref OrigEntry], term: usize, path: bytes.Bytes) bool = trust {+ for e in canon {+ if e.term == term && has_prefix(e.path, path) {+ return true+ }+ }+ return false+}++fn exact_entry(canon: list[ref OrigEntry], term: usize, path: bytes.Bytes) option[ref OrigEntry] = trust {+ for e in canon {+ if e.term == term && bytes.Bytes.eql(e.path, path) {+ return some e+ }+ }+ return none+}++/// Merge signed tree terms. `maps[i]` is the rename map for term `i` (or none).+pub fn merge(+ repo: layout.Repo,+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ git: ref object.GitRepo,+ has_git: bool,+ terms: list[ref TreeTerm],+ maps: list[ref rename.RenameMap],+ adjacent_merge: bool+) Outcome = trust {+ val orig: list[ref OrigEntry] = make_terms(handles, terms, tx)+ val canon: mut list[ref OrigEntry] = lists.new[ref OrigEntry]()+ val special: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val consumed: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for e in orig {+ val targets: list[ref CanonTarget] = canonical_targets(e.path, maps)+ if @len(targets) > 1 {+ // Both sides renamed this base path to different destinations.+ if !list_has_path(special, e.path) {+ @append(special, bytes.Bytes.dup(e.path))+ }+ }+ val cp: bytes.Bytes = canonical_path(targets, e.path)+ @append(canon, new_orig(e.term, cp, e.kind, e.target))+ free_canon(targets)+ }++ val out: mut list[ref OutEntry] = lists.new[ref OutEntry]()+ val rerere: mut list[usize] = lists.new[usize]()++ // Both-sides-renamed-differently conflicts are materialized at the original+ // base path with the destinations as terms.+ for sp in special {+ val targets: list[ref CanonTarget] = canonical_targets(sp, maps)+ val ets: mut list[EntryTerm] = lists.new[EntryTerm]()+ for c in targets {+ val found = find_orig(orig, c.map_index, c.target)+ val term: mut EntryTerm = EntryTerm{+ positive: true,+ present: false,+ kind: 0,+ target: objid.id(none)+ }+ if found is some fe {+ term.present = true+ term.kind = fe.kind+ term.target = fe.target+ }+ @append(ets, term)+ if !list_has_path(consumed, c.target) {+ @append(consumed, bytes.Bytes.dup(c.target))+ }+ }+ // The base term is the first negative term.+ val base_term: mut i32 = -1+ val ti: mut usize = 0+ for ti < @len(terms) {+ val to = @get(terms, ti)+ if to is some tt {+ if !tt.positive {+ base_term = ti as i32+ break+ }+ }+ ti+++ }+ if base_term >= 0 {+ val found_base = find_orig(orig, base_term as usize, sp)+ val bt: mut EntryTerm = EntryTerm{+ positive: false,+ present: false,+ kind: 0,+ target: objid.id(none)+ }+ if found_base is some bf {+ bt.present = true+ bt.kind = bf.kind+ bt.target = bf.target+ }+ @append(ets, bt)+ }+ val merged = merge_entry(repo, tx, handles, git, has_git, sp, ets, adjacent_merge, rerere)+ if merged is some me {+ @append(out, me)+ }+ free_canon(targets)+ @listfree(ets)+ if !list_has_path(consumed, sp) {+ @append(consumed, bytes.Bytes.dup(sp))+ }+ }++ val paths: list[bytes.Bytes] = collect_paths(canon)+ for path in paths {+ if list_has_path(consumed, path) {+ continue+ }+ val any_exact: mut bool = false+ val any_children: mut bool = false+ val ti: mut usize = 0+ for ti < @len(terms) {+ if exact_entry(canon, ti, path) is some _ {+ any_exact = true+ }+ if has_children(canon, ti, path) {+ any_children = true+ }+ ti+++ }+ if !any_exact {+ continue+ }+ val mixed: bool = any_children+ val ets: mut list[EntryTerm] = lists.new[EntryTerm]()+ val k: mut usize = 0+ for k < @len(terms) {+ val exact = exact_entry(canon, k, path)+ if exact is some ee {+ @append(+ ets,+ EntryTerm{+ positive: term_positive(terms, k),+ present: true,+ kind: ee.kind,+ target: ee.target+ }+ )+ } elif mixed && has_children(canon, k, path) {+ val sub: objid.Id = build_subtree(tx, canon, k, path)+ @append(+ ets,+ EntryTerm{+ positive: term_positive(terms, k),+ present: true,+ kind: tree.KIND_SUBTREE,+ target: sub+ }+ )+ } else {+ @append(+ ets,+ EntryTerm{+ positive: term_positive(terms, k),+ present: false,+ kind: 0,+ target: objid.id(none)+ }+ )+ }+ k+++ }+ val merged = merge_entry(repo, tx, handles, git, has_git, path, ets, adjacent_merge, rerere)+ if merged is some me {+ @append(out, me)+ }+ @listfree(ets)+ if mixed {+ // Children were folded into the merged subtree at `path`.+ for e in canon {+ if has_prefix(e.path, path) {+ if !list_has_path(consumed, e.path) {+ @append(consumed, bytes.Bytes.dup(e.path))+ }+ }+ }+ }+ }++ val tree_id: objid.Id = build_from_entries(tx, out)+ free_out(out)+ free_orig(canon)+ free_orig(orig)+ @listfree(paths)+ @listfree(special)+ @listfree(consumed)+ val applied: usize = @len(rerere)+ @listfree(rerere)+ return Outcome{tree: tree_id, rerere: applied}+}--- a/veins/src/object/content.sx+++ b/veins/src/object/content.sx@@ -10,6 +10,23 @@ val files = use("../io/files.sx") val lazy = use("../git/lazy.sx") val object = use("../git/object.sx")+val txnmod = use("../store/txn.sx")++fn read_body_any(+ handles: list[ref store.Handle],+ id: objid.Id,+ expected: u8,+ use_cache: bool,+ tx: ref txnmod.Txn+) option[bytes.Bytes] = trust {+ if use_cache {+ val cached = txnmod.find_cached(tx, expected, id)+ if cached is some b {+ return some bytes.Bytes.dup(b)+ }+ }+ return state.read_body(handles, id, expected)+} fn append_blob( handles: list[ref store.Handle],@@ -17,7 +34,9 @@ id: objid.Id, depth: usize, git: object.GitRepo,- has_git: bool+ has_git: bool,+ use_cache: bool,+ tx: ref txnmod.Txn ) bool = trust { if depth > 64 { return false@@ -42,7 +61,7 @@ } } }- val body_opt = state.read_body(handles, id, types.BLOB)+ val body_opt = read_body_any(handles, id, types.BLOB, use_cache, tx) val body: mut bytes.Bytes = bytes.empty() match body_opt { some b => {@@ -68,7 +87,7 @@ buf.Buf.put_bytes(out, b.data) } elif b.form == blob.FORM_LEAF { for e in b.entries {- val chunk_opt = state.read_body(handles, e.id, types.CHUNK)+ val chunk_opt = read_body_any(handles, e.id, types.CHUNK, use_cache, tx) match chunk_opt { some chunk => { buf.Buf.put_bytes(out, chunk)@@ -84,7 +103,7 @@ } } else { for e in b.entries {- if !append_blob(handles, out, e.id, depth + 1, git, has_git) {+ if !append_blob(handles, out, e.id, depth + 1, git, has_git, use_cache, tx) { good = false break }@@ -96,14 +115,16 @@ } /// Read the full content of a blob. The returned bytes are owned by the caller.-pub fn read_blob(+fn read_blob_inner( handles: list[ref store.Handle], id: objid.Id, git: object.GitRepo,- has_git: bool+ has_git: bool,+ use_cache: bool,+ tx: ref txnmod.Txn ) option[bytes.Bytes] = trust { val out: mut buf.Buf = buf.new(4096)- val good: bool = append_blob(handles, out, id, 0, git, has_git)+ val good: bool = append_blob(handles, out, id, 0, git, has_git, use_cache, tx) val result: mut option[bytes.Bytes] = none if good { result = some(bytes.Bytes.dup(buf.Buf.view(out)))@@ -110,4 +131,23 @@ } buf.Buf.free(out) return result+}++pub fn read_blob(+ handles: list[ref store.Handle],+ id: objid.Id,+ git: object.GitRepo,+ has_git: bool+) option[bytes.Bytes] = trust {+ return read_blob_inner(handles, id, git, has_git, false, none)+}++pub fn read_blob_tx(+ handles: list[ref store.Handle],+ id: objid.Id,+ git: object.GitRepo,+ has_git: bool,+ tx: ref txnmod.Txn+) option[bytes.Bytes] = trust {+ return read_blob_inner(handles, id, git, has_git, true, tx) }--- a/veins/src/object/treewalk.sx+++ b/veins/src/object/treewalk.sx@@ -8,6 +8,7 @@ val read = use("../store/state.sx") val store = use("../store/store.sx") val files = use("../io/files.sx")+val txnmod = use("../store/txn.sx") pub val KIND_MISSING: u8 = 0 @@ -23,8 +24,23 @@ return objid.id(out) } -pub fn read_tree(handles: list[ref store.Handle], id: objid.Id) option[ref tree.Tree] = trust {- val body_opt = read.read_body(handles, id, types.TREE)+fn read_tree_inner(+ handles: list[ref store.Handle],+ id: objid.Id,+ use_cache: bool,+ tx: ref txnmod.Txn+) option[ref tree.Tree] = trust {+ val body_opt: mut option[bytes.Bytes] = read.read_body(handles, id, types.TREE)+ if use_cache {+ val cached = txnmod.find_cached(tx, types.TREE, id)+ if cached is some cb {+ val owned: bytes.Bytes = bytes.Bytes.dup(cb)+ if body_opt is some old {+ files.free_buffer(old)+ }+ body_opt = some owned+ }+ } val body: mut bytes.Bytes = bytes.empty() match body_opt { some b => {@@ -45,6 +61,18 @@ return none } }+}++pub fn read_tree(handles: list[ref store.Handle], id: objid.Id) option[ref tree.Tree] = trust {+ return read_tree_inner(handles, id, false, none)+}++pub fn read_tree_tx(+ handles: list[ref store.Handle],+ id: objid.Id,+ tx: ref txnmod.Txn+) option[ref tree.Tree] = trust {+ return read_tree_inner(handles, id, true, tx) } pub fn find_name(t: ref tree.Tree, name: bytes.Bytes) i32 = trust {@@ -97,12 +125,14 @@ tree_id: objid.Id, prefix: bytes.Bytes, out: mut list[ref FlatEntry],- depth: usize+ depth: usize,+ use_cache: bool,+ tx: ref txnmod.Txn ) bool = trust { if depth > 4096 { return false }- val t_opt = read_tree(handles, tree_id)+ val t_opt = read_tree_inner(handles, tree_id, use_cache, tx) val t: mut ref tree.Tree = none match t_opt { some x => {@@ -116,7 +146,7 @@ for e in t.entries { val path: bytes.Bytes = join_path(prefix, e.name) if e.kind == tree.KIND_SUBTREE {- if !flatten_into(handles, e.target, path, out, depth + 1) {+ if !flatten_into(handles, e.target, path, out, depth + 1, use_cache, tx) { files.free_buffer(path) good = false break@@ -195,14 +225,31 @@ } /// Flatten a tree into path entries sorted by full path.-pub fn flatten(handles: list[ref store.Handle], tree_id: objid.Id) list[ref FlatEntry] = trust {+fn flatten_inner(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ use_cache: bool,+ tx: ref txnmod.Txn+) list[ref FlatEntry] = trust { val out: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()- if !flatten_into(handles, tree_id, bytes.empty(), out, 0) {+ if !flatten_into(handles, tree_id, bytes.empty(), out, 0, use_cache, tx) { // Return what was collected; callers treat a short list as an error // through `tree_conflicted` / direct read failures. } sort_flat(out) return out+}++pub fn flatten(handles: list[ref store.Handle], tree_id: objid.Id) list[ref FlatEntry] = trust {+ return flatten_inner(handles, tree_id, false, none)+}++pub fn flatten_tx(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ tx: ref txnmod.Txn+) list[ref FlatEntry] = trust {+ return flatten_inner(handles, tree_id, true, tx) } pub fn flatten_or_empty(@@ -211,6 +258,17 @@ ) list[ref FlatEntry] = trust { if tree is some id { return flatten(handles, id)+ }+ return lists.new[ref FlatEntry]()+}++pub fn flatten_or_empty_tx(+ handles: list[ref store.Handle],+ tree: option[objid.Id],+ tx: ref txnmod.Txn+) list[ref FlatEntry] = trust {+ if tree is some id {+ return flatten_tx(handles, id, tx) } return lists.new[ref FlatEntry]() }--- a/veins/src/store/layout.sx+++ b/veins/src/store/layout.sx@@ -105,6 +105,10 @@ pub fn working_copy_dir(r: Repo) str.StringView = { return files.join(root_view(r), ".veins/working-copy")+}++pub fn resolutions_dir(r: Repo) str.StringView = {+ return files.join(root_view(r), ".veins/resolutions") } pub fn config_path(r: Repo) str.StringView = {--- a/veins/src/store/txn.sx+++ b/veins/src/store/txn.sx@@ -378,6 +378,14 @@ pub fn add_known(tx: mut ref Txn, kind: u8, id: objid.Id, body: bytes.Bytes) objid.Id = trust { return writer.add_known(tx.writer, kind, id, body)+}++pub fn enable_chunk_cache(tx: mut ref Txn) void = trust {+ writer.enable_chunk_cache(tx.writer)+}++pub fn find_cached(tx: ref Txn, kind: u8, id: objid.Id) option[bytes.Bytes] = trust {+ return writer.find_cached(tx.writer, kind, id) } fn host_from_env() bytes.Bytes = trust {--- a/veins/src/store/writer.sx+++ b/veins/src/store/writer.sx@@ -22,6 +22,12 @@ val b3 = use("../crypto/blake3.sx") extern (C) fn sysconf(name: i32) i64 = "sysconf"++type CachedObj = {+ kind: mut u8+ id: mut objid.Id+ body: mut bytes.Bytes+} type PendingRecord = { id: mut objid.Id@@ -49,6 +55,8 @@ pending_bytes: mut usize failed: mut bool seen: mut idmap.IdSet+ cache: mut list[ref CachedObj]+ cache_chunks: mut bool } fn worker_count() usize = trust {@@ -65,6 +73,22 @@ } } return 4+}++fn free_cached(items: list[ref CachedObj]) void = trust {+ for c in items {+ if c.body.ptr != none {+ val bp: mut ref void = c.body.ptr as ref void+ @free(bp)+ }+ if c.id.ptr != none {+ val ip: mut ref void = c.id.ptr as ref void+ @free(ip)+ }+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(items) } fn free_items(items: list[ref PendingRecord]) void = trust {@@ -220,6 +244,8 @@ buf.Buf.free(header) w.failed = false w.seen = idmap.new(1024)+ w.cache = lists.new[ref CachedObj]()+ w.cache_chunks = false return some w } @@ -241,6 +267,15 @@ return id } val _ = idmap.put(w.seen, id_view)+ // Chunks dominate memory for large snapshots, so they are only retained+ // when a command needs to read objects it wrote in the same transaction.+ if kind != 1 || w.cache_chunks {+ val c: mut ref CachedObj = @alloc(@sizeof(CachedObj)) as ref CachedObj+ c.kind = kind+ c.id = copy_id(id)+ c.body = bytes.Bytes.dup(body)+ @append(w.cache, c)+ } val r: mut ref PendingRecord = @alloc(@sizeof(PendingRecord)) as ref PendingRecord r.id = copy_id(id) r.kind = kind@@ -269,6 +304,7 @@ w.fd = -1 } free_meta_list(w.metas)+ free_cached(w.cache) if @len(w.items) > 0 { free_items(w.items) } else {@@ -346,6 +382,21 @@ w.items = lists.new[ref PendingRecord]() w.pending_bytes = 0 return true+}++pub fn enable_chunk_cache(w: mut Writer) void = trust {+ w.cache_chunks = true+}++/// Look up an object written during this writer's lifetime. The returned body+/// is borrowed from the writer.+pub fn find_cached(w: ref Writer, kind: u8, id: objid.Id) option[bytes.Bytes] = trust {+ for c in w.cache {+ if c.kind == kind && objid.Id.eql(c.id, id) {+ return some c.body+ }+ }+ return none } /// Finish the pack and write its index. `w` is consumed.--- a/veins/src/worktree/checkout.sx+++ b/veins/src/worktree/checkout.sx@@ -13,6 +13,8 @@ val names = use("../object/names.sx") val blob = use("../object/blob.sx") val tree = use("../object/tree.sx")+val conflict = use("../object/conflict.sx")+val repoconfig = use("../core/repoconfig.sx") val graph = use("../object/graph.sx") val treewalk = use("../object/treewalk.sx") val view = use("../object/view.sx")@@ -27,6 +29,7 @@ val stat = use("../io/stat.sx") val object = use("../git/object.sx") val lazy = use("../git/lazy.sx")+val filemerge = use("../merge/filemerge.sx") extern (C) fn openat(dirfd: i32, path: ref u8, flags: i32, ...) i32 = "openat" extern (C) fn mkdirat(dirfd: i32, path: ref u8, mode: i32) i32 = "mkdirat"@@ -113,6 +116,11 @@ pub type CheckoutTask = { path: mut bytes.Bytes kind: mut u8+ target: mut objid.Id+}++pub type ConflictTask = {+ path: mut bytes.Bytes target: mut objid.Id } @@ -120,6 +128,7 @@ handles: list[ref store.Handle] tasks: mut list[ref CheckoutTask] dirs: mut list[bytes.Bytes]+ conflicts: mut list[ref ConflictTask] failed: mut bool error: mut bytes.Bytes }@@ -602,6 +611,7 @@ } if !valid_checkout_name(e.name) { walk.failed = true+ walk.error = bytes.Bytes.dup(e.name) break } val path: bytes.Bytes = join_bytes(prefix, e.name)@@ -614,7 +624,13 @@ add_task(walk, path, e.kind, e.target) } elif e.kind == tree.KIND_SUBMODULE { @append(walk.dirs, path)+ } elif e.kind == tree.KIND_CONFLICT {+ val ct: mut ref ConflictTask = @alloc(@sizeof(ConflictTask)) as ref ConflictTask+ ct.path = path+ ct.target = copy_id(e.target)+ @append(walk.conflicts, ct) } else {+ walk.error = bytes.Bytes.dup(path) files.free_buffer(path) walk.failed = true }@@ -701,7 +717,504 @@ } treewalk.free_flat(old_entries) treewalk.free_flat(new_entries)+ return success+}+++fn adjacent_config(repo: layout.Repo) bool = trust {+ val v = repoconfig.get(repo, bytes.bytes(c"merge.adjacent", 14))+ if v is some value {+ val on: bool = bytes.Bytes.eql(value, bytes.bytes(c"merge", 5))+ files.free_buffer(value)+ return on+ }+ return false+}++fn abs_rel(repo: layout.Repo, path: bytes.Bytes) str.StringView = trust {+ return files.join3(layout.root_view(repo), str.from_cstr(c""), files.to_view(path))+}++fn suffix_path(path: bytes.Bytes, suffix: bytes.Bytes) bytes.Bytes = trust {+ val out: ref u8 = @alloc(path.len + suffix.len) as ref u8+ if path.len > 0 {+ @memcpy(out as ref void, path.ptr as ref void, path.len)+ }+ if suffix.len > 0 {+ @memcpy(+ @ptradd(out, path.len as i64) as ref void,+ suffix.ptr as ref void,+ suffix.len+ )+ }+ return bytes.bytes(out, path.len + suffix.len)+}++fn remove_path(repo: layout.Repo, path: bytes.Bytes) void = trust {+ val abs: str.StringView = abs_rel(repo, path)+ val info_opt = stat.read(abs)+ if info_opt is some info {+ if info.kind == stat.KIND_DIR {+ val names: list[ref u8] = files.list_dir(abs)+ for n in names {+ val child: bytes.Bytes = suffix_path(path, bytes.bytes(c"/", 1))+ val child2: bytes.Bytes = suffix_path(child, bytes.from_cstr(n))+ remove_path(repo, child2)+ files.free_buffer(child)+ files.free_buffer(child2)+ }+ files.free_names(names)+ val _ = fs.rmdir_path(abs)+ } else {+ val _ = files.delete(abs)+ }+ }+ files.free_path(abs)+}++fn delete_sidecars(repo: layout.Repo, path: bytes.Bytes) void = trust {+ val suffixes: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ @append(suffixes, bytes.bytes(c".base", 5))+ @append(suffixes, bytes.bytes(c".ours", 5))+ @append(suffixes, bytes.bytes(c".theirs", 7))+ val n: mut usize = 2+ for n <= 64 {+ val b1: ref u8 = @fmtalloc(".base{d}", {n})+ @append(suffixes, bytes.from_cstr(b1))+ val b2: ref u8 = @fmtalloc(".theirs{d}", {n})+ @append(suffixes, bytes.from_cstr(b2))+ n+++ }+ for suffix in suffixes {+ val full: bytes.Bytes = suffix_path(path, suffix)+ remove_path(repo, full)+ files.free_buffer(full)+ }+ @listfree(suffixes)+}++fn write_bytes_path(+ root_fd: i32,+ path: bytes.Bytes,+ data: bytes.Bytes,+ executable: bool+) bool = trust {+ val target_opt = open_parent(root_fd, path)+ if target_opt is none {+ return false+ }+ val t: mut CheckoutTarget = CheckoutTarget{fd: 0, name: none, owned_fd: false}+ if target_opt is some tt {+ t = tt+ }+ val flags: i32 = o_wronly() | o_creat() | o_trunc() | o_nofollow() | o_cloexec()+ val mut_fd: mut i32 = openat(t.fd, t.name, flags, FILE_MODE as i32)+ if mut_fd < 0 {+ val _ = unlinkat(t.fd, t.name, 0)+ mut_fd = openat(t.fd, t.name, flags, FILE_MODE as i32)+ }+ val fd: i32 = mut_fd+ val success: mut bool = false+ if fd >= 0 {+ success = native.write_fd_all(fd, data)+ if success {+ val want: mut u32 = FILE_MODE+ if executable {+ want = EXEC_MODE+ }+ if fchmod(fd, want) != 0 {+ success = false+ }+ }+ close(fd)+ }+ close_target(t)+ return success+}++fn write_path_task(+ handles: list[ref store.Handle],+ root_fd: i32,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool,+ path: bytes.Bytes,+ kind: u8,+ target: objid.Id+) bool = trust {+ val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob+ job.handles = handles+ job.root_fd = root_fd+ job.tasks = lists.new[ref CheckoutTask]()+ job.start = 0+ job.step = 1+ job.failed = false+ job.error = bytes.empty()+ job.git = git+ job.git_lock = git_lock+ job.has_git = has_git+ val task: mut ref CheckoutTask = @alloc(@sizeof(CheckoutTask)) as ref CheckoutTask+ task.path = bytes.Bytes.dup(path)+ task.kind = kind+ task.target = copy_id(target)+ val success: bool = write_task(job, task)+ if !success {+ val hx: ref u8 = objid.Id.hex(target)+ msg.error_prefix()+ stdio.eprint(+ "cannot materialize object {s} at {s}\n",+ {str.from_cstr(hx), str.view(path.ptr, path.len as i64)}+ )+ val hp: mut ref void = hx as ref void+ @free(hp)+ }+ files.free_buffer(task.path)+ free_id(task.target)+ @free(task as ref void)+ @listfree(job.tasks)+ @free(job as ref void)+ return success+}++fn free_walk_lists(walk: CheckoutWalk) void = trust {+ for t in walk.tasks {+ files.free_buffer(t.path)+ free_id(t.target)+ val tp: mut ref void = t as ref void+ @free(tp)+ }+ @listfree(walk.tasks)+ for d in walk.dirs {+ files.free_buffer(d)+ }+ @listfree(walk.dirs)+ for c in walk.conflicts {+ files.free_buffer(c.path)+ free_id(c.target)+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(walk.conflicts)+}++fn write_tree_side(+ handles: list[ref store.Handle],+ root_fd: i32,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool,+ tree_id: objid.Id,+ prefix: bytes.Bytes+) bool = trust {+ val walk: mut CheckoutWalk = CheckoutWalk{+ handles: handles,+ tasks: lists.new[ref CheckoutTask](),+ dirs: lists.new[bytes.Bytes](),+ conflicts: lists.new[ref ConflictTask](),+ failed: false,+ error: bytes.empty()+ }+ walk_tree(walk, tree_id, prefix, 0)+ val success: mut bool = !walk.failed+ if success && prefix.len > 0 {+ if !ensure_dir(root_fd, prefix) {+ success = false+ }+ }+ if success {+ for d in walk.dirs {+ if !ensure_dir(root_fd, d) {+ success = false+ msg.error_prefix()+ stdio.eprint(+ "cannot create conflict directory: {s}\n",+ {str.view(d.ptr, d.len as i64)}+ )+ break+ }+ }+ }+ if success {+ for task in walk.tasks {+ if !write_path_task(+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ task.path,+ task.kind,+ task.target+ ) {+ success = false+ msg.error_prefix()+ stdio.eprint(+ "cannot write conflict sidecar: {s}\n",+ {str.view(task.path.ptr, task.path.len as i64)}+ )+ break+ }+ }+ }+ free_walk_lists(walk)+ return success+}++fn load_conflict(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref conflict.Conflict] = trust {+ val body_opt = state.read_body(handles, id, types.CONFLICT)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = conflict.decode(body)+ val out: mut option[ref conflict.Conflict] = none+ match decoded {+ ok c => {+ out = some c+ }+ err _ => {+ }+ }+ if out is none {+ files.free_buffer(body)+ }+ return out+}++fn materialize_value(+ repo: layout.Repo,+ handles: list[ref store.Handle],+ root_fd: i32,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool,+ path: bytes.Bytes,+ v: ref conflict.ConflictValue+) bool = trust {+ if v.kind == 0 {+ remove_path(repo, path)+ return true+ }+ if v.kind == tree.KIND_SUBTREE {+ remove_path(repo, path)+ return write_tree_side(handles, root_fd, git, git_lock, has_git, v.target, path)+ }+ remove_path(repo, path)+ return write_path_task(+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ path,+ v.kind,+ v.target+ )+}++fn materialize_conflict(+ repo: layout.Repo,+ handles: list[ref store.Handle],+ root_fd: i32,+ git: object.GitRepo,+ git_lock: ref void,+ has_git: bool,+ path: bytes.Bytes,+ target: objid.Id+) bool = trust {+ val c_opt = load_conflict(handles, target)+ if c_opt is none {+ return false+ }+ val c: mut ref conflict.Conflict = none+ if c_opt is some cc {+ c = cc+ }+ val success: mut bool = true+ // Base sidecars.+ val ri: mut usize = 0+ for ri < @len(c.removes) {+ val rv = @get(c.removes, ri)+ if rv is some value {+ val suffix: mut bytes.Bytes = bytes.bytes(c".base", 5)+ if ri > 0 {+ val s: ref u8 = @fmtalloc(".base{d}", {ri + 1})+ suffix = bytes.from_cstr(s)+ }+ val sp: bytes.Bytes = suffix_path(path, suffix)+ if !materialize_value(+ repo,+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ sp,+ value+ ) {+ success = false+ }+ files.free_buffer(sp)+ }+ ri+++ }+ // Add sidecars and the clean merged file.+ val ai: mut usize = 0+ for ai < @len(c.adds) {+ val av = @get(c.adds, ai)+ if av is some value {+ val suffix: mut bytes.Bytes = bytes.empty()+ if ai == 0 {+ suffix = bytes.bytes(c".ours", 5)+ } elif ai == 1 {+ suffix = bytes.bytes(c".theirs", 7)+ } else {+ val s2: ref u8 = @fmtalloc(".theirs{d}", {ai + 1})+ suffix = bytes.from_cstr(s2)+ }+ val sp2: bytes.Bytes = suffix_path(path, suffix)+ if !materialize_value(+ repo,+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ sp2,+ value+ ) {+ success = false+ }+ files.free_buffer(sp2)+ }+ ai+++ }+ // The main path is the merged file with conflicts resolved to ours.+ if @len(c.adds) == 0 {+ remove_path(repo, path)+ } else {+ val ours = @get(c.adds, 0)+ if ours is some ov {+ if ov.kind == 0 {+ remove_path(repo, path)+ } elif ov.kind == tree.KIND_SUBTREE {+ if !write_tree_side(+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ ov.target,+ path+ ) {+ success = false+ }+ } else {+ val merged_ok: mut bool = false+ if @len(c.adds) == 2 && @len(c.removes) == 1 {+ val theirs = @get(c.adds, 1)+ val base = @get(c.removes, 0)+ if theirs is some tv {+ if base is some bv {+ if tv.kind != 0 && bv.kind != 0+ && tv.kind != tree.KIND_SUBTREE+ && bv.kind != tree.KIND_SUBTREE {+ val git_copy: mut object.GitRepo = git+ val merged = filemerge.merge_blobs(+ handles,+ @addr(git_copy),+ has_git,+ bv.target,+ ov.target,+ tv.target,+ adjacent_config(repo)+ )+ if merged is some m {+ val exec: bool = ov.kind == tree.KIND_EXECUTABLE+ remove_path(repo, path)+ merged_ok = write_bytes_path(root_fd, path, m.data, exec)+ filemerge.free_edit(m)+ }+ }+ }+ }+ }+ if !merged_ok {+ if !write_path_task(+ handles,+ root_fd,+ git,+ git_lock,+ has_git,+ path,+ ov.kind,+ ov.target+ ) {+ success = false+ }+ }+ }+ }+ }+ conflict.free_conflict(c) return success+}++fn free_conflict_tasks(xs: list[ref ConflictTask]) void = trust {+ for c in xs {+ files.free_buffer(c.path)+ free_id(c.target)+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(xs)+}++fn sidecar_collision(+ handles: list[ref store.Handle],+ old_tree: option[objid.Id],+ conflicts: list[ref ConflictTask]+) option[bytes.Bytes] = trust {+ val tracked: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)+ val out: mut option[bytes.Bytes] = none+ for ct in conflicts {+ val suffixes: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ @append(suffixes, bytes.bytes(c".base", 5))+ @append(suffixes, bytes.bytes(c".ours", 5))+ @append(suffixes, bytes.bytes(c".theirs", 7))+ val n: mut usize = 2+ for n <= 64 {+ val b1: ref u8 = @fmtalloc(".base{d}", {n})+ @append(suffixes, bytes.from_cstr(b1))+ val b2: ref u8 = @fmtalloc(".theirs{d}", {n})+ @append(suffixes, bytes.from_cstr(b2))+ n+++ }+ for suffix in suffixes {+ val full: bytes.Bytes = suffix_path(ct.path, suffix)+ if treewalk.lookup(tracked, full) is some _ {+ out = some bytes.Bytes.dup(full)+ }+ files.free_buffer(full)+ if out is some _ {+ break+ }+ }+ @listfree(suffixes)+ if out is some _ {+ break+ }+ }+ treewalk.free_flat(tracked)+ return out } fn materialize_tree(@@ -710,12 +1223,6 @@ old_tree: option[objid.Id], new_root: objid.Id ) i32 = trust {- if !delete_stale(repo, handles, old_tree, some(new_root)) {- msg.error_prefix()- stdio.eprint("cannot remove files that are absent from the target tree\n", {})- return 1- }- val root: str.StringView = layout.root_view(repo) val root_c: ref u8 = bytes.Bytes.to_cstr(bytes.from_cstr(root.ptr)) val root_fd: i32 = openat(-100, root_c, o_directory() | o_cloexec(), 0)@@ -728,10 +1235,12 @@ val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]() val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val conflicts: list[ref ConflictTask] = lists.new[ref ConflictTask]() val walk: mut CheckoutWalk = CheckoutWalk{ handles: handles, tasks: tasks, dirs: dirs,+ conflicts: conflicts, failed: false, error: bytes.empty() }@@ -738,7 +1247,40 @@ walk_tree(walk, new_root, bytes.empty(), 0) if walk.failed { msg.error_prefix()- stdio.eprint("checkout tree validation failed\n", {})+ if walk.error.len > 0 {+ stdio.eprint(+ "checkout tree validation failed at: {s}\n",+ {str.view(walk.error.ptr, walk.error.len as i64)}+ )+ } else {+ stdio.eprint("checkout tree validation failed\n", {})+ }+ close(root_fd)+ return 1+ }+ val collision = sidecar_collision(handles, old_tree, conflicts)+ if collision is some cpath {+ msg.error_prefix()+ stdio.eprint(+ "conflict sidecar would overwrite a tracked path: {s}\n",+ {str.view(cpath.ptr, cpath.len as i64)}+ )+ files.free_buffer(cpath)+ close(root_fd)+ return 1+ }+ // Remove sidecars from a previous materialization before writing new ones.+ val old_flat: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)+ for oe in old_flat {+ if oe.kind == tree.KIND_CONFLICT {+ delete_sidecars(repo, oe.path)+ }+ }+ treewalk.free_flat(old_flat)++ if !delete_stale(repo, handles, old_tree, some(new_root)) {+ msg.error_prefix()+ stdio.eprint("cannot remove files that are absent from the target tree\n", {}) close(root_fd) return 1 }@@ -849,6 +1391,24 @@ j++ } + for ct in conflicts {+ if !materialize_conflict(+ repo,+ handles,+ root_fd,+ git_repo,+ git_lock,+ git_usable,+ ct.path,+ ct.target+ ) {+ had_failure = true+ if failed_path.len == 0 {+ failed_path = bytes.Bytes.dup(ct.path)+ }+ }+ }+ free_conflict_tasks(conflicts) if git_lock != none { thread.Mutex.free[allocators.HeapAllocator](ac, git_lock) }--- a/veins/src/worktree/snapshot.sx+++ b/veins/src/worktree/snapshot.sx@@ -28,6 +28,9 @@ val viewops = use("../store/viewops.sx") val identity = use("../core/identity.sx") val gitmap = use("../git/map.sx")+val renamemod = use("../merge/rename.sx")+val object = use("../git/object.sx")+val repoconfig = use("../core/repoconfig.sx") val view = use("../object/view.sx") val files = use("../io/files.sx") val native = use("../io/native.sx")@@ -457,7 +460,53 @@ } @set(xs, j, c) i+++ }+}++fn ends_with(name: bytes.Bytes, suffix: bytes.Bytes) bool = trust {+ if name.len < suffix.len {+ return false+ }+ return bytes.Bytes.eql(+ bytes.Bytes.slice(name, name.len - suffix.len, name.len),+ suffix+ )+}++fn trailing_digits(name: bytes.Bytes) usize = trust {+ val i: mut usize = name.len+ for i > 0 {+ val c: u8 = bytes.Bytes.at(name, i - 1)+ if c < 48 || c > 57 {+ break+ }+ i--+ }+ return name.len - i+}++fn sidecar_base(name: bytes.Bytes) option[bytes.Bytes] = trust {+ if ends_with(name, bytes.bytes(c".base", 5)) && name.len > 5 {+ return some bytes.Bytes.slice(name, 0, name.len - 5)+ }+ if ends_with(name, bytes.bytes(c".ours", 5)) && name.len > 5 {+ return some bytes.Bytes.slice(name, 0, name.len - 5)+ }+ if ends_with(name, bytes.bytes(c".theirs", 7)) && name.len > 7 {+ return some bytes.Bytes.slice(name, 0, name.len - 7)+ }+ val digits: usize = trailing_digits(name)+ if digits > 0 {+ val stem_end: usize = name.len - digits+ if stem_end > 5 && ends_with(bytes.Bytes.slice(name, 0, stem_end), bytes.bytes(c".base", 5)) {+ return some bytes.Bytes.slice(name, 0, stem_end - 5)+ }+ if stem_end > 7+ && ends_with(bytes.Bytes.slice(name, 0, stem_end), bytes.bytes(c".theirs", 7)) {+ return some bytes.Bytes.slice(name, 0, stem_end - 7)+ } }+ return none } fn is_meta_name(name: bytes.Bytes) bool = trust {@@ -548,6 +597,20 @@ val name: bytes.Bytes = bytes.from_cstr(name_c) if is_meta_name(name) { continue+ }+ if have_old {+ val base_opt = sidecar_base(name)+ if base_opt is some base_name {+ val bidx: i32 = treewalk.find_name(old, base_name)+ if bidx >= 0 {+ val be = @get(old.entries, bidx as usize)+ if be is some bee {+ if bee.kind == tree.KIND_CONFLICT {+ continue+ }+ }+ }+ } } val path: bytes.Bytes = join_path(rel, name) val fs_path: str.StringView = files.join(dir, str.from_cstr(name_c))@@ -582,6 +645,23 @@ val old_idx: mut i32 = -1 if have_old { old_idx = treewalk.find_name(old, name)+ }+ if old_idx >= 0 {+ val oe = @get(old.entries, old_idx as usize)+ if oe is some olde {+ if olde.kind == tree.KIND_CONFLICT {+ @append(+ entries,+ tree.entry(+ bytes.Bytes.dup(name),+ tree.KIND_CONFLICT,+ copy_id(olde.target)+ )+ )+ files.free_buffer(path)+ continue+ }+ } } if ignored && old_idx < 0 { files.free_buffer(path)@@ -730,6 +810,19 @@ fn remove_wc_head(v: mut ref view.View, id: objid.Id) void = trust { viewops.remove_head(v, id)+}++fn similar_pct(repo: layout.Repo) i32 = trust {+ val v = repoconfig.get(repo, bytes.bytes(c"rename.autodetect", 17))+ if v is some value {+ val off: bool = bytes.Bytes.eql(value, bytes.bytes(c"off", 3))+ files.free_buffer(value)+ if off {+ return 0+ }+ return 60+ }+ return 60 } /// Snapshot the working tree into `@`. Returns 0 on success.@@ -921,7 +1014,40 @@ random.random_bytes(cid as ref void, 16) change_id = objid.change_id(cid) }- val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ val renames: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ if c != none {+ for r in c.renames {+ @append(+ renames,+ commit.new_rename(+ r.parent_index,+ r.kind,+ bytes.Bytes.dup(r.from_path),+ bytes.Bytes.dup(r.to_path)+ )+ )+ }+ }+ if old_tree is some old_for_rename {+ if !objid.Id.eql(old_for_rename, new_root) {+ val gitfake: mut object.GitRepo = @zeroed+ val detected = renamemod.detect_tx(+ st.handles,+ @addr(gitfake),+ false,+ some old_for_rename,+ some new_root,+ similar_pct(repo),+ 0,+ tx+ )+ for r in detected {+ @append(renames, r)+ }+ @listfree(detected)+ }+ }+ renamemod.sort_renames(renames) val extra: list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]() val nc: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit nc.version = 1@@ -937,6 +1063,18 @@ val encoded: bytes.Bytes = commit.encode(nc) val new_commit: objid.Id = txn.add_object(tx, types.COMMIT, encoded) @listfree(nc.parents)+ for r in nc.renames {+ if r.from_path.ptr != none {+ val fp: mut ref void = r.from_path.ptr as ref void+ @free(fp)+ }+ if r.to_path.ptr != none {+ val tp: mut ref void = r.to_path.ptr as ref void+ @free(tp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ } @listfree(nc.renames) @listfree(nc.extra) @free(nc as ref void)--- /dev/null+++ b/veins/src/worktree/treeedit.sx@@ -0,0 +1,151 @@+/// Small helper for replacing or deleting one path in a tree.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val tree = use("../object/tree.sx")+val treewalk = use("../object/treewalk.sx")+val store = use("../store/store.sx")+val txnmod = use("../store/txn.sx")++fn split(path: bytes.Bytes) usize = trust {+ val i: mut usize = 0+ for i < path.len && bytes.Bytes.at(path, i) != 47 {+ i+++ }+ return i+}++fn empty_tree(tx: mut ref txnmod.Txn) objid.Id = trust {+ val entries: list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val encoded = tree.encode(entries)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ return objid.id(none)+ }+ }+ val id: objid.Id = txnmod.add_object(tx, types.TREE, body)+ @listfree(entries)+ return id+}++fn tree_is_empty(+ handles: list[ref store.Handle],+ id: objid.Id,+ tx: ref txnmod.Txn+) bool = trust {+ val t_opt = treewalk.read_tree_tx(handles, id, tx)+ if t_opt is some t {+ val empty: bool = @len(t.entries) == 0+ tree.free_tree(t)+ return empty+ }+ return true+}++fn edit_into(+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ path: bytes.Bytes,+ present: bool,+ kind: u8,+ target: objid.Id+) objid.Id = trust {+ val t_opt = treewalk.read_tree(handles, tree_id)+ if t_opt is none {+ return objid.id(none)+ }+ val t: mut ref tree.Tree = none+ if t_opt is some tt {+ t = tt+ }+ val cut: usize = split(path)+ val name: bytes.Bytes = bytes.Bytes.slice(path, 0, cut)+ val out: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val found: mut bool = false+ for e in t.entries {+ if bytes.Bytes.eql(e.name, name) {+ found = true+ if cut == path.len {+ if present {+ @append(out, tree.entry(e.name, kind, target))+ }+ } elif e.kind == tree.KIND_SUBTREE {+ val rest: bytes.Bytes = bytes.Bytes.slice(path, cut + 1, path.len)+ val child: objid.Id = edit_into(+ tx,+ handles,+ e.target,+ rest,+ present,+ kind,+ target+ )+ if !objid.Id.is_none(child) && !tree_is_empty(handles, child, tx) {+ @append(out, tree.entry(e.name, tree.KIND_SUBTREE, child))+ }+ } else {+ @append(out, tree.entry(e.name, e.kind, e.target))+ }+ } else {+ @append(out, tree.entry(e.name, e.kind, e.target))+ }+ }+ if !found && cut == path.len && present {+ @append(out, tree.entry(bytes.Bytes.dup(name), kind, target))+ }+ val encoded = tree.encode(out)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ for e in out {+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(out)+ tree.free_tree(t)+ return objid.id(none)+ }+ }+ val id: objid.Id = txnmod.add_object(tx, types.TREE, body)+ for e in out {+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(out)+ tree.free_tree(t)+ return id+}+++/// Replace one entry. The returned ID is a new tree object.+pub fn replace(+ tx: mut ref txnmod.Txn,+ handles: list[ref store.Handle],+ root: objid.Id,+ path: bytes.Bytes,+ present: bool,+ kind: u8,+ target: objid.Id+) option[objid.Id] = trust {+ val id: objid.Id = edit_into(tx, handles, root, path, present, kind, target)+ if objid.Id.is_none(id) {+ return none+ }+ if tree_is_empty(handles, id, tx) {+ val empty: objid.Id = empty_tree(tx)+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ return some empty+ }+ return some id+}