navid/veins / commit

79b5392b34ec

Navid M <navidmomtahen@gmail.com> · 2026-11-26

parents: c07f730c51d3

Browse files at this commit · Download source

all: bookmark mechanism
--- /dev/null+++ b/veins/src/cli/bookmark_cmd.sx@@ -0,0 +1,614 @@+/// `vn bookmark`: manage named, movable pointers (branches).+///+/// Bookmarks are the branching primitive. `vn bookmark set <name>` creates or+/// moves one, `vn new <name>` starts a change on top of it, and `vn co <name>`+/// switches the working copy to it. Rewriting a working-copy commit (through a+/// snapshot, `describe`, or `rm`) moves any bookmark that named that commit.++val str      = use("std/string")+val stdio    = use("std/stdio")+val msg      = use("../core/msg.sx")+val terminal = use("std/terminal")+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 view     = use("../object/view.sx")+val graph    = use("../object/graph.sx")+val changeid = use("../object/changeid.sx")+val store    = use("../store/store.sx")+val layout   = use("../store/layout.sx")+val state    = use("../store/state.sx")+val txn      = use("../store/txn.sx")+val viewops  = use("../store/viewops.sx")+val snapshot = use("../worktree/snapshot.sx")++fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = trust {+    return bytes.Bytes.eql(bytes.from_cstr(a), bytes.bytes(text, len))+}++fn is_flag(a: ref u8) bool = trust {+    if a == none {+        return false+    }+    if @strlen(a) == 0 {+        return false+    }+    return @load8(a) == 45+}++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)+    }+}++/// Copy a byte span with a trailing NUL so it can be passed to the formatted+/// output helpers safely. The reported length excludes the terminator.+fn dup_z(b: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc(b.len + 1) as ref u8+    if b.len > 0 {+        @memcpy(out as ref void, b.ptr as ref void, b.len)+    }+    @store8(@ptradd(out, b.len as i64), 0)+    return bytes.bytes(out, b.len)+}++fn free_targets(ts: view.TargetSet) void = trust {+    // Target IDs are borrowed from the decoded view body. Only the lists are+    // owned by the view.+    @listfree(ts.adds)+    @listfree(ts.removes)+}++fn contains_seq(name: bytes.Bytes, needle: bytes.Bytes) bool = trust {+    if needle.len == 0 || needle.len > name.len {+        return false+    }+    val last: usize = name.len - needle.len+    val i: mut usize = 0+    for i <= last {+        if bytes.Bytes.eql(bytes.Bytes.slice(name, i, i + needle.len), needle) {+            return true+        }+        i+++    }+    return false+}++/// Ref names used as git branches. The data model accepts nearly anything, but+/// a bookmark that cannot be exported as a branch is a trap, so reject git's+/// reserved forms here.+fn valid_bookmark_name(name: bytes.Bytes) bool = trust {+    if name.len == 0 || name.len > prim.MAX_NAME_LEN {+        return false+    }+    val first: u8 = bytes.Bytes.at(name, 0)+    if first == 45 || first == 47 || first == 46 {+        return false+    }+    val last: u8 = bytes.Bytes.at(name, name.len - 1)+    if last == 47 || last == 46 {+        return false+    }+    val i: mut usize = 0+    for i < name.len {+        val c: u8 = bytes.Bytes.at(name, i)+        if c == 0 || c == 32 || c < 32 || c == 127 {+            return false+        }+        if c == 126 || c == 94 || c == 58 || c == 63 || c == 42 || c == 91 || c == 92 {+            return false+        }+        i+++    }+    if contains_seq(name, bytes.bytes(c"..", 2)) {+        return false+    }+    if contains_seq(name, bytes.bytes(c"@{", 2)) {+        return false+    }+    if contains_seq(name, bytes.bytes(c"//", 2)) {+        return false+    }+    if bytes.Bytes.eql(name, bytes.bytes(c"@", 1)) {+        return false+    }+    val lock: bytes.Bytes = bytes.bytes(c".lock", 5)+    if name.len >= lock.len+    && bytes.Bytes.eql(bytes.Bytes.slice(name, name.len - lock.len, name.len), lock) {+        return false+    }+    return true+}++fn make_description(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+    val b: mut buf.Buf = buf.new(prefix.len + 1 + name.len)+    buf.Buf.put_bytes(b, prefix)+    buf.Buf.put_u8(b, 32)+    buf.Buf.put_bytes(b, name)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++fn short_commit(id: objid.Id, n: usize) str.StringView = trust {+    val hex: ref u8 = objid.Id.hex(id)+    val width: usize = 12+    val mut_width: mut usize = width+    if n > 0 {+        mut_width = n+    }+    if mut_width > 64 {+        mut_width = 64+    }+    val out: str.StringView = str.view(hex, mut_width as i64)+    // The view is intentionally freed by the process at exit; callers only+    // format it immediately.+    return out+}++fn short_change(cid: objid.ChangeId) bytes.Bytes = trust {+    val full: bytes.Bytes = changeid.encode(cid)+    val n: usize = 8+    val width: mut usize = n+    if full.len < width {+        width = full.len+    }+    val out: bytes.Bytes = dup_z(bytes.Bytes.slice(full, 0, width))+    changeid.free(full)+    return out+}++fn print_cell(text: str.StringView, width: usize) void = trust {+    stdio.print("{s}", {text})+    val pad: mut i64 = width as i64 - text.len+    for pad > 0 {+        stdio.print(" ", {})+        pad--+    }+}++fn run_set(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {+    val name: mut bytes.Bytes = bytes.empty()+    val rev: 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"-r", 2) || cmd_is(a, c"-rev", 4)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some rv {+                        rev = 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 {+                if name.len == 0 {+                    name = bytes.from_cstr(a)+                } elif rev.len == 0 {+                    rev = bytes.from_cstr(a)+                } else {+                    msg.error_prefix()+                    stdio.eprint("bookmark set accepts a name and one revision\n", {})+                    return 1+                }+            }+        }+        i+++    }+    if name.len == 0 {+        msg.error_prefix()+        stdio.eprint("bookmark set requires a name\n", {})+        return 1+    }+    if !valid_bookmark_name(name) {+        msg.error_prefix()+        stdio.eprint(+            "invalid bookmark name: {s}\n",+            {str.view(name.ptr, name.len as i64)}+        )+        return 1+    }++    val snap: i32 = snapshot.run(repo)+    if snap != 0 {+        return snap+    }+    val tx_opt = txn.begin(repo)+    val tx: mut ref txn.Txn = none+    match tx_opt {+        some t => {+            tx = t+        }+        none => {+            msg.error_prefix()+            stdio.eprint("cannot load repository state\n", {})+            return 1+        }+    }+    val st: store.Store = store.open_all(repo)+    val resolved = graph.resolve(st.handles, tx.view, rev)+    val target: mut objid.Id = objid.id_none()+    val mut_found: mut bool = false+    match resolved {+        some id => {+            target = copy_id(id)+            mut_found = true+        }+        none => {+        }+    }+    if !mut_found {+        msg.error_prefix()+        if rev.len == 0 {+            stdio.eprint("no working-copy commit\n", {})+        } else {+            stdio.eprint(+                "unknown revision: {s}\n",+                {str.view(rev.ptr, rev.len as i64)}+            )+        }+        store.close(st)+        txn.abort(tx)+        return 1+    }++    val existing = viewops.find_bookmark(tx.view, name)+    val changed: mut bool = true+    if existing is some idx {+        val bmo = @get(tx.view.bookmarks, idx)+        if bmo is some bm {+            if viewops.bookmark_points_at(bm, target) {+                changed = false+            } else {+                free_targets(bm.targets)+                bm.targets.adds = lists.new[objid.Id]()+                bm.targets.removes = lists.new[objid.Id]()+                @append(bm.targets.adds, copy_id(target))+            }+        }+    } else {+        val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+        bm.name = bytes.Bytes.dup(name)+        bm.targets = view.empty_target_set()+        @append(bm.targets.adds, copy_id(target))+        @append(tx.view.bookmarks, bm)+        viewops.sort_bookmarks(tx.view.bookmarks)+    }++    if !changed {+        msg.info_prefix()+        stdio.print(+            "bookmark {s} is already at {s}\n",+            {str.view(name.ptr, name.len as i64), short_commit(target, 0)}+        )+        store.close(st)+        txn.abort(tx)+        free_id(target)+        return 0+    }++    viewops.rebuild_heads(tx.view)+    val description: bytes.Bytes = make_description(bytes.bytes(c"bookmark set", 12), name)+    val status: i32 = txn.finish(tx, description)+    if status == 0 {+        msg.info_prefix()+        stdio.print(+            "bookmark {s} set to {s}\n",+            {str.view(name.ptr, name.len as i64), short_commit(target, 0)}+        )+    }+    val dp: mut ref void = description.ptr as ref void+    @free(dp)+    store.close(st)+    free_id(target)+    return status+}++fn run_delete(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {+    val name: 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 && is_flag(a) {+                msg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } else {+                if name.len > 0 {+                    msg.error_prefix()+                    stdio.eprint("bookmark delete accepts exactly one name\n", {})+                    return 1+                }+                name = bytes.from_cstr(a)+            }+        }+        i+++    }+    if name.len == 0 {+        msg.error_prefix()+        stdio.eprint("bookmark delete requires a name\n", {})+        return 1+    }++    val tx_opt = txn.begin(repo)+    val tx: mut ref txn.Txn = none+    match tx_opt {+        some t => {+            tx = t+        }+        none => {+            msg.error_prefix()+            stdio.eprint("cannot load repository state\n", {})+            return 1+        }+    }+    val existing = viewops.find_bookmark(tx.view, name)+    val idx: mut usize = 0+    val mut_found: mut bool = false+    match existing {+        some i2 => {+            idx = i2+            mut_found = true+        }+        none => {+        }+    }+    if !mut_found {+        msg.error_prefix()+        stdio.eprint(+            "no such bookmark: {s}\n",+            {str.view(name.ptr, name.len as i64)}+        )+        txn.abort(tx)+        return 1+    }+    // The removed bookmark's name and target spans belong to the decoded view+    // body; the process is short-lived, so simply drop the slot.+    val _ = @remove(tx.view.bookmarks, idx)+    viewops.rebuild_heads(tx.view)+    val description: bytes.Bytes = make_description(bytes.bytes(c"bookmark delete", 15), name)+    val status: i32 = txn.finish(tx, description)+    if status == 0 {+        msg.info_prefix()+        stdio.print("deleted bookmark {s}\n", {str.view(name.ptr, name.len as i64)})+    }+    val dp: mut ref void = description.ptr as ref void+    @free(dp)+    return status+}++fn run_list(repo: layout.Repo, args: list[ref u8], start: usize) i32 = trust {+    val col_titles: mut bool = true+    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"-no-col-titles", 14) {+                col_titles = false+            } 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("bookmark list takes no operands\n", {})+                return 1+            }+        }+        i+++    }+    val st: store.Store = store.open_all(repo)+    val v_opt = state.current_view(repo, st.handles)+    val v: mut ref view.View = none+    match v_opt {+        some x => {+            v = x+        }+        none => {+            store.close(st)+            msg.error_prefix()+            stdio.eprint("no operation state\n", {})+            return 1+        }+    }+    val wc_opt = viewops.working_copy(v)+    val wc: mut objid.Id = objid.id_none()+    val have_wc: mut bool = false+    if wc_opt is some id {+        wc = id+        have_wc = true+    }+    val w_commit: usize = 12+    val w_change: usize = 8+    val w_name: mut usize = 8+    for bm in v.bookmarks {+        if bm.name.len > w_name {+            w_name = bm.name.len+        }+    }+    if col_titles {+        print_cell(str.from_cstr(c"Bookmark"), w_name)+        stdio.print("  ", {})+        print_cell(str.from_cstr(c"Commit"), w_commit)+        stdio.print("  ", {})+        print_cell(str.from_cstr(c"Change"), w_change)+        stdio.print("  Target\n", {})+    }+    for bm in v.bookmarks {+        val name_z: bytes.Bytes = dup_z(bm.name)+        print_cell(str.view(name_z.ptr, name_z.len as i64), w_name)+        stdio.print("  ", {})+        val have_target: mut bool = false+        val current: mut bool = false+        val conflicted: bool = @len(bm.targets.adds) > 1+        val commit_z: mut bytes.Bytes = bytes.empty()+        val change_z: mut bytes.Bytes = bytes.empty()+        if @len(bm.targets.adds) > 0 {+            val first = @get(bm.targets.adds, 0)+            if first is some tid {+                have_target = true+                if have_wc && objid.Id.eql(tid, wc) {+                    current = true+                }+                val short_c: str.StringView = short_commit(tid, 0)+                commit_z = dup_z(bytes.bytes(short_c.ptr, short_c.len as usize))+                val lc_opt = graph.load_commit(st.handles, tid)+                if lc_opt is some lc {+                    change_z = short_change(lc.c.change_id)+                    graph.free_loaded(lc)+                }+            }+        }+        if !have_target {+            print_cell(str.from_cstr(c"<missing>"), w_commit)+            stdio.print("  ", {})+            print_cell(str.from_cstr(c""), w_change)+            stdio.print("  (missing)\n", {})+        } else {+            print_cell(str.view(commit_z.ptr, commit_z.len as i64), w_commit)+            stdio.print("  ", {})+            print_cell(str.view(change_z.ptr, change_z.len as i64), w_change)+            stdio.print("  ", {})+            if current {+                terminal.print(str.from_cstr(c"@"), terminal.Color.Red)+            }+            if conflicted {+                if current {+                    stdio.print(" ", {})+                }+                terminal.print(str.from_cstr(c"(conflicted)"), terminal.Color.BrightRed)+            }+            stdio.print("\n", {})+        }+        val np: mut ref void = name_z.ptr as ref void+        @free(np)+        if commit_z.ptr != none {+            val cp: mut ref void = commit_z.ptr as ref void+            @free(cp)+        }+        if change_z.ptr != none {+            val chp: mut ref void = change_z.ptr as ref void+            @free(chp)+        }+    }+    if @len(v.bookmarks) == 0 {+        msg.info_prefix()+        stdio.print("no bookmarks\n", {})+    }+    if have_wc {+        free_id(wc)+    }+    view.free_view(v)+    store.close(st)+    return 0+}+fn usage() void = trust {+    stdio.puts("usage: vn bookmark <set|list|delete> ...")+    stdio.puts("")+    stdio.puts("manage named, movable pointers to commits (branches)")+    stdio.puts("")+    stdio.puts("subcommands:")+    stdio.puts("  set <name> [-rev <rev>]   create or move a bookmark (default: @)")+    stdio.puts("  move <name> [-rev <rev>]  alias of set")+    stdio.puts("  list [-no-col-titles]     list bookmarks")+    stdio.puts("  delete <name>             delete a bookmark")+}++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val sub_opt = @get(args, start)+    val sub: mut ref u8 = none+    match sub_opt {+        some s => {+            sub = s+        }+        none => {+            usage()+            return 1+        }+    }+    if cmd_is(sub, c"set", 3) || cmd_is(sub, c"move", 4) {+        val repo_opt = layout.discover(str.from_cstr(c"."))+        match repo_opt {+            some repo => {+                val status: i32 = run_set(repo, args, start + 1)+                layout.free_repo(repo)+                return status+            }+            none => {+                msg.error_prefix()+                stdio.eprint("not a veins repository\n", {})+                return 1+            }+        }+    }+    if cmd_is(sub, c"list", 4) || cmd_is(sub, c"ls", 2) {+        val repo_opt = layout.discover(str.from_cstr(c"."))+        match repo_opt {+            some repo => {+                val status: i32 = run_list(repo, args, start + 1)+                layout.free_repo(repo)+                return status+            }+            none => {+                msg.error_prefix()+                stdio.eprint("not a veins repository\n", {})+                return 1+            }+        }+    }+    if cmd_is(sub, c"delete", 6) || cmd_is(sub, c"remove", 6) || cmd_is(sub, c"forget", 6) {+        val repo_opt = layout.discover(str.from_cstr(c"."))+        match repo_opt {+            some repo => {+                val status: i32 = run_delete(repo, args, start + 1)+                layout.free_repo(repo)+                return status+            }+            none => {+                msg.error_prefix()+                stdio.eprint("not a veins repository\n", {})+                return 1+            }+        }+    }+    if cmd_is(sub, c"help", 4) || cmd_is(sub, c"-h", 2) {+        usage()+        return 0+    }+    msg.error_prefix()+    stdio.eprint("unknown bookmark subcommand: {s}\n", {str.from_cstr(sub)})+    usage()+    return 1+}--- a/veins/src/cli/help_cmd.sx+++ b/veins/src/cli/help_cmd.sx@@ -18,8 +18,10 @@     stdio.puts("  stat         show working-copy changes; alias: status")     stdio.puts("  inf          show a repository breakdown")     stdio.puts("  log          show commit history")+    stdio.puts("  show         show a commit and its diff")     stdio.puts("  diff         show a unified diff")     stdio.puts("  new          start a new change")+    stdio.puts("  bookmark     manage named branch pointers")     stdio.puts("  rm           untrack paths, keeping files on disk by default")     stdio.puts("  ex           add paths or globs to .vnexclude")     stdio.puts("  desc         set the working-copy commit message; alias: describe")@@ -135,6 +137,35 @@     stdio.puts("options:")     stdio.puts("  -rev <revset>             show only the given revision set")     stdio.puts("  -no-col-titles            omit column titles")+}++fn show_show() void = trust {+    stdio.puts("usage: vn show [rev] [-no-col-titles]")+    stdio.puts("")+    stdio.puts("show a commit's metadata and its diff against its first parent")+    stdio.puts("")+    stdio.puts("arguments:")+    stdio.puts("  [rev]                     revision to show (default: @)")+    stdio.puts("")+    stdio.puts("options:")+    stdio.puts("  -no-col-titles            omit the metadata labels")+}++fn show_bookmark() void = trust {+    stdio.puts("usage: vn bookmark <set|list|delete> ...")+    stdio.puts("")+    stdio.puts("manage named, movable pointers to commits (branches)")+    stdio.puts("")+    stdio.puts("subcommands:")+    stdio.puts("  set <name> [-rev <rev>]   create or move a bookmark (default: @)")+    stdio.puts("  move <name> [-rev <rev>]  alias of set")+    stdio.puts("  list [-no-col-titles]     list bookmarks")+    stdio.puts("  delete <name>             delete a bookmark")+    stdio.puts("")+    stdio.puts("examples:")+    stdio.puts("  vn bookmark set main")+    stdio.puts("  vn new main")+    stdio.puts("  vn co main") }  fn show_diff() void = trust {@@ -246,10 +277,18 @@     }     if cmd_is(cmd, c"log", 3) {         show_log()+        return 0+    }+    if cmd_is(cmd, c"show", 4) {+        show_show()         return 0     }     if cmd_is(cmd, c"diff", 4) {         show_diff()+        return 0+    }+    if cmd_is(cmd, c"bookmark", 8) || cmd_is(cmd, c"bookmarks", 9) {+        show_bookmark()         return 0     }     if cmd_is(cmd, c"new", 3) {--- a/veins/src/cli/new_cmd.sx+++ b/veins/src/cli/new_cmd.sx@@ -194,6 +194,9 @@     val encoded: bytes.Bytes = commit.encode(nc)     val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)     viewops.remove_head(tx.view, wc)+    // Repointing a bookmark at the rewritten working-copy commit is what makes+    // an edited named branch advance with its commit.+    viewops.move_bookmarks(tx.view, wc, new_id)     viewops.set_workspace(tx.view, new_id)     viewops.rebuild_heads(tx.view)     val status: i32 = txn.finish(tx, bytes.bytes(c"describe", 8))@@ -261,6 +264,14 @@     if wc_opt is some id {         wc = id         have_wc = true+    }+    val old_root: mut option[objid.Id] = none+    if have_wc {+        val old_lc_opt = graph.load_commit(st.handles, wc)+        if old_lc_opt is some old_lc {+            old_root = some(copy_id(old_lc.c.root_tree))+            graph.free_loaded(old_lc)+        }     }     val parents: mut list[objid.Id] = lists.new[objid.Id]()     val root_tree: mut objid.Id = objid.id_none()@@ -351,9 +362,14 @@     }     viewops.set_workspace(tx.view, new_id)     viewops.rebuild_heads(tx.view)-    val status: i32 = txn.finish(tx, bytes.bytes(c"new", 3))+    val status: mut i32 = txn.finish(tx, bytes.bytes(c"new", 3))     if status == 0 {         val _ = gitmap.mark_native(repo, new_id)+        if @len(revs) > 0 {+            // The new commit was created from the requested revision, but the+            // files on disk still belong to the previous working-copy commit.+            status = checkout.materialize_commit(repo, st.handles, old_root, root_tree)+        }     }     store.close(st)     @listfree(parents)@@ -367,13 +383,13 @@     if wc.ptr != none {         val wp: mut ref void = wc.ptr as ref void         @free(wp)-    }-    identity.free_sig(sig)-    if status != 0 {-        return status     }-    if @len(revs) > 0 {-        return checkout.run(repo, bytes.empty())+    if old_root is some oroot {+        if oroot.ptr != none {+            val orp: mut ref void = oroot.ptr as ref void+            @free(orp)+        }     }-    return 0+    identity.free_sig(sig)+    return status }--- a/veins/src/cli/op_cmd.sx+++ b/veins/src/cli/op_cmd.sx@@ -8,11 +8,15 @@ val objid     = use("../object/id.sx") val operation = use("../object/operation.sx") val view      = use("../object/view.sx")+val graph     = use("../object/graph.sx") val datetime  = use("../core/datetime.sx") val store     = use("../store/store.sx") val state     = use("../store/state.sx") val layout    = use("../store/layout.sx") val txn       = use("../store/txn.sx")+val viewops   = use("../store/viewops.sx")+val checkout  = use("../worktree/checkout.sx")+val snapshot  = use("../worktree/snapshot.sx")  type OpRec = {     id: mut objid.Id@@ -196,10 +200,40 @@     free_ids(heads)     store.close(st)     return 0+}++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)+        }+        if wc.ptr != none {+            val wp: mut ref void = wc.ptr as ref void+            @free(wp)+        }+    }+    return out+}++fn free_tree_opt(t: option[objid.Id]) void = trust {+    if t is some id {+        if id.ptr != none {+            val p: mut ref void = id.ptr as ref void+            @free(p)+        }+    } }  fn write_view(     repo: layout.Repo,+    handles: list[ref store.Handle],     new_view: ref view.View,     description: bytes.Bytes ) i32 = trust {@@ -215,13 +249,27 @@             return 1         }     }+    val old_tree: option[objid.Id] = wc_tree(handles, tx.view)+    val new_tree: option[objid.Id] = wc_tree(handles, new_view)     view.free_view(tx.view)     tx.view = new_view-    val status: i32 = txn.finish(tx, description)+    val status: mut i32 = txn.finish(tx, description)+    if status == 0 {+        val synced: i32 = checkout.materialize_optional(repo, handles, old_tree, new_tree)+        if synced != 0 {+            status = synced+        }+    }+    free_tree_opt(old_tree)+    free_tree_opt(new_tree)     return status }  pub fn restore(repo: layout.Repo, text: bytes.Bytes) i32 = trust {+    val snap: i32 = snapshot.run(repo)+    if snap != 0 {+        return snap+    }     val st: store.Store = store.open_all(repo)     val heads: list[objid.Id] = state.heads(repo)     val recs: mut list[ref OpRec] = collect(st.handles, heads)@@ -232,7 +280,7 @@         if rec_opt is some rec {             val target_view = state.read_view(st.handles, rec.op.view)             if target_view is some tv {-                status = write_view(repo, tv, bytes.bytes(c"op restore", 10))+                status = write_view(repo, st.handles, tv, bytes.bytes(c"op restore", 10))             } else {                 msg.error_prefix()                 stdio.eprint("cannot read operation view\n", {})@@ -251,6 +299,10 @@ pub fn revert(repo: layout.Repo, text: bytes.Bytes) i32 = trust {     // A revert of the latest operation restores its parent view. More complex     // three-way inverses are handled by the merge engine in a later milestone.+    val snap: i32 = snapshot.run(repo)+    if snap != 0 {+        return snap+    }     val st: store.Store = store.open_all(repo)     val heads: list[objid.Id] = state.heads(repo)     val recs: mut list[ref OpRec] = collect(st.handles, heads)@@ -266,7 +318,7 @@                     if parent_opt is some parent {                         val pv = state.read_view(st.handles, parent.view)                         if pv is some tv {-                            status = write_view(repo, tv, bytes.bytes(c"op revert", 9))+                            status = write_view(repo, st.handles, tv, bytes.bytes(c"op revert", 9))                         }                         operation.free_operation(parent)                     }@@ -273,7 +325,7 @@                 }             } else {                 val empty: ref view.View = state.empty_view()-                status = write_view(repo, empty, bytes.bytes(c"op revert", 9))+                status = write_view(repo, st.handles, empty, bytes.bytes(c"op revert", 9))             }         }     } else {@@ -287,6 +339,10 @@ }  pub fn undo(repo: layout.Repo) i32 = trust {+    val snap: i32 = snapshot.run(repo)+    if snap != 0 {+        return snap+    }     val st: store.Store = store.open_all(repo)     val heads: list[objid.Id] = state.heads(repo)     if @len(heads) == 0 {@@ -315,7 +371,7 @@         }         match target_view {             some tv => {-                status = write_view(repo, tv, bytes.bytes(c"undo", 4))+                status = write_view(repo, st.handles, tv, bytes.bytes(c"undo", 4))             }             none => {                 msg.error_prefix()--- a/veins/src/cli/rm_cmd.sx+++ b/veins/src/cli/rm_cmd.sx@@ -485,6 +485,7 @@     val encoded: bytes.Bytes = commit.encode(nc)     val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)     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 status: mut i32 = txn.finish(tx, bytes.bytes(c"rm", 2))--- /dev/null+++ b/veins/src/cli/show_cmd.sx@@ -0,0 +1,206 @@+/// `vn show <rev>`: display a commit and its diff against its first parent.++val str      = use("std/string")+val stdio    = use("std/stdio")+val msg      = use("../core/msg.sx")+val bytes    = use("../core/bytes.sx")+val objid    = use("../object/id.sx")+val view     = use("../object/view.sx")+val graph    = use("../object/graph.sx")+val changeid = use("../object/changeid.sx")+val datetime = use("../core/datetime.sx")+val store    = use("../store/store.sx")+val state    = use("../store/state.sx")+val layout   = use("../store/layout.sx")+val viewops  = use("../store/viewops.sx")+val snapshot = use("../worktree/snapshot.sx")+val diff     = use("diff_cmd.sx")++fn copy_id(id: objid.Id) objid.Id = trust {+    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 dup_z(b: bytes.Bytes) bytes.Bytes = trust {+    val out: ref u8 = @alloc(b.len + 1) as ref u8+    if b.len > 0 {+        @memcpy(out as ref void, b.ptr as ref void, b.len)+    }+    @store8(@ptradd(out, b.len as i64), 0)+    return bytes.bytes(out, b.len)+}++fn print_short(id: objid.Id) void = trust {+    val hex: ref u8 = objid.Id.hex(id)+    stdio.print("{s}", {str.view(hex, 12)})+    @free(hex as ref void)+}++fn parent_tree(+    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 {+                val pl = graph.load_commit(handles, pid)+                if pl is some parent {+                    out = some(copy_id(parent.c.root_tree))+                    graph.free_loaded(parent)+                }+            }+        }+        graph.free_loaded(lc)+    }+    return out+}++pub fn run(repo: layout.Repo, rev: bytes.Bytes, col_titles: 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+    match v_opt {+        some x => {+            v = x+        }+        none => {+            store.close(st)+            msg.error_prefix()+            stdio.eprint("no operation state\n", {})+            return 1+        }+    }+    val resolved = graph.resolve(st.handles, v, rev)+    val target: mut objid.Id = objid.id_none()+    val have_target: mut bool = false+    if resolved is some id {+        target = copy_id(id)+        have_target = true+    }+    if !have_target {+        msg.error_prefix()+        if rev.len == 0 {+            stdio.eprint("no working-copy commit\n", {})+        } else {+            stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})+        }+        view.free_view(v)+        store.close(st)+        return 1+    }++    val lc_opt = graph.load_commit(st.handles, target)+    val lc: mut ref graph.LoadedCommit = none+    match lc_opt {+        some x => {+            lc = x+        }+        none => {+            msg.error_prefix()+            stdio.eprint("cannot read commit\n", {})+            view.free_view(v)+            store.close(st)+            free_id(target)+            return 1+        }+    }++    val hex: ref u8 = objid.Id.hex(target)+    val cid_raw: bytes.Bytes = changeid.encode(lc.c.change_id)+    val cid: bytes.Bytes = dup_z(cid_raw)+    changeid.free(cid_raw)+    val stamp_raw: bytes.Bytes = datetime.format_utc(lc.c.committer.seconds)+    val stamp: bytes.Bytes = dup_z(stamp_raw)+    val author_name: bytes.Bytes = dup_z(lc.c.author.name)+    val author_email: bytes.Bytes = dup_z(lc.c.author.email)+    if col_titles {+        stdio.print("commit   {s}\n", {str.view(hex, 64)})+        stdio.print("change   {s}\n", {str.view(cid.ptr, cid.len as i64)})+        stdio.print("author   {s} <{s}>\n", {+            str.view(author_name.ptr, author_name.len as i64),+            str.view(author_email.ptr, author_email.len as i64)+        })+        stdio.print("date     {s}\n", {str.view(stamp.ptr, stamp.len as i64)})+        stdio.print("parents  ", {})+        if @len(lc.c.parents) == 0 {+            stdio.print("<none>", {})+        } else {+            val pi: mut usize = 0+            for pi < @len(lc.c.parents) {+                if pi > 0 {+                    stdio.print(" ", {})+                }+                val p = @get(lc.c.parents, pi)+                if p is some pid {+                    print_short(pid)+                }+                pi+++            }+        }+        stdio.print("\n", {})+        val names = viewops.bookmark_names(v, target)+        if @len(names) > 0 {+            stdio.print("bookmarks", {})+            for name in names {+                val nz: bytes.Bytes = dup_z(name)+                stdio.print(" [{s}]", {str.view(nz.ptr, nz.len as i64)})+                val nzp: mut ref void = nz.ptr as ref void+                @free(nzp)+            }+            stdio.print("\n", {})+        }+        @listfree(names)+        stdio.print("\n", {})+        if lc.c.message.len > 0 {+            val msgz: bytes.Bytes = dup_z(lc.c.message)+            stdio.print("{s}\n", {str.view(msgz.ptr, msgz.len as i64)})+            val msgzp: mut ref void = msgz.ptr as ref void+            @free(msgzp)+        } else {+            stdio.print("<unset>\n", {})+        }+        stdio.print("\n", {})+    }++    val old_tree: option[objid.Id] = parent_tree(st.handles, target)+    val new_tree: option[objid.Id] = some(copy_id(lc.c.root_tree))+    val git: mut diff.GitSource = diff.open_git(repo)+    diff.render(st.handles, git, old_tree, new_tree)+    diff.close_git(git)++    if old_tree is some ot {+        free_id(ot)+    }+    if new_tree is some nt {+        free_id(nt)+    }+    @free(hex as ref void)+    val cidp: mut ref void = cid.ptr as ref void+    @free(cidp)+    val stampp: mut ref void = stamp.ptr as ref void+    @free(stampp)+    val anp: mut ref void = author_name.ptr as ref void+    @free(anp)+    val aep: mut ref void = author_email.ptr as ref void+    @free(aep)+    graph.free_loaded(lc)+    view.free_view(v)+    store.close(st)+    free_id(target)+    return 0+}--- a/veins/src/git/export.sx+++ b/veins/src/git/export.sx@@ -196,7 +196,7 @@     val dst_len: mut u64 = bound     val rc: i32 = compress2(         dst,-        dst_len,+        @addr(dst_len),         header.ptr,         header.len as u64,         6@@ -378,7 +378,6 @@         }     }     val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()-    val child_oids: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()     val good: mut bool = true     for e in t.entries {         val child: mut option[bytes.Bytes] = none@@ -398,11 +397,12 @@             child = export_blob(ctx, e.target)         }         if child is some co {+            // The entry takes ownership of the child OID allocation; it is+            // released once, with the entry, in the cleanup below.             @append(                 entries,                 tree.entry(bytes.Bytes.dup(e.name), e.kind, objid.id(co.ptr))             )-            @append(child_oids, co)         } else {             good = false         }@@ -425,10 +425,6 @@             @free(ep)         }         @listfree(entries)-        for o in child_oids {-            object.free_digest(o)-        }-        @listfree(child_oids)         return none     }     sort_git_entries(entries)@@ -475,10 +471,6 @@         @free(ep)     }     @listfree(entries)-    for o in child_oids {-        object.free_digest(o)-    }-    @listfree(child_oids)     if !good {         ctx.failed = true         if oid_out.ptr != none {@@ -825,14 +817,53 @@     return good } -pub fn run(repo: layout.Repo) i32 = trust {+fn ensure_dir(path: str.StringView) bool = trust {+    if files.exists_dir(path) {+        return true+    }+    return files.mkdir_all(path)+}++/// A native repository has no `.veins/git` until an import. Export can create a+/// minimal bare repository so history can leave veins without first running+/// git or an import.+fn ensure_mirror(repo: layout.Repo) bool = trust {     val gitp: str.StringView = layout.git_dir(repo)-    if !files.exists_dir(gitp) {+    val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))+    val refs: str.StringView = files.join(gitp, str.from_cstr(c"refs"))+    val refs_heads: str.StringView = files.join(refs, str.from_cstr(c"heads"))+    val refs_tags: str.StringView = files.join(refs, str.from_cstr(c"tags"))+    val good: bool = ensure_dir(gitp)+    && ensure_dir(objects)+    && ensure_dir(refs)+    && ensure_dir(refs_heads)+    && ensure_dir(refs_tags)+    val head: str.StringView = files.join(gitp, str.from_cstr(c"HEAD"))+    if good && !files.exists_file(head) {+        val _ = files.write_all(head, bytes.from_cstr(c"ref: refs/heads/main\n"))+    }+    val config: str.StringView = files.join(gitp, str.from_cstr(c"config"))+    if good && !files.exists_file(config) {+        val body: bytes.Bytes = bytes.from_cstr(c"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n")+        val _ = files.write_all(config, body)+    }+    files.free_path(config)+    files.free_path(head)+    files.free_path(objects)+    files.free_path(refs)+    files.free_path(refs_heads)+    files.free_path(refs_tags)+    files.free_path(gitp)+    return good+}++pub fn run(repo: layout.Repo) i32 = trust {+    if !ensure_mirror(repo) {         msg.error_prefix()-        stdio.eprint("no git mirror; run `vn git import` first\n", {})-        files.free_path(gitp)+        stdio.eprint("cannot create git mirror\n", {})         return 1     }+    val gitp: str.StringView = layout.git_dir(repo)     val git_opt = object.open(gitp)     val git_repo: mut object.GitRepo = @zeroed     val git_open: mut bool = false@@ -1014,9 +1045,11 @@         }     }     if status == 0 {-        val sc = gitmap.save_map(repo, str.from_cstr(c"commits"), commits)-        val stree = gitmap.save_map(repo, str.from_cstr(c"trees"), trees)-        val sblob = gitmap.save_map(repo, str.from_cstr(c"blobs"), blobs)+        // The exporter inserts through `ctx`, which owns the maps that grew+        // during export. The initial locals are only a starting snapshot.+        val sc = gitmap.save_map(repo, str.from_cstr(c"commits"), ctx.commits)+        val stree = gitmap.save_map(repo, str.from_cstr(c"trees"), ctx.trees)+        val sblob = gitmap.save_map(repo, str.from_cstr(c"blobs"), ctx.blobs)         if !sc || !stree || !sblob {             msg.error_prefix()             stdio.eprint("failed to write git mapping tables\n", {})@@ -1066,9 +1099,9 @@     @listfree(resolved_tags)     free_ids(native_ids)     store.close(st)-    oidmap.free(commits)-    oidmap.free(trees)-    oidmap.free(blobs)+    oidmap.free(ctx.commits)+    oidmap.free(ctx.trees)+    oidmap.free(ctx.blobs)     if git_open {         object.free(git_repo)     }--- a/veins/src/main.sx+++ b/veins/src/main.sx@@ -14,8 +14,10 @@ val bench_cmd    = use("cli/bench_cmd.sx") val status_cmd   = use("cli/status_cmd.sx") 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 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")@@ -178,6 +180,53 @@     match repo_opt {         some repo => {             val status: i32 = log_cmd.run(repo, rev, col_titles)+            layout.free_repo(repo)+            return status+        }+        none => {+            return 1+        }+    }+}++fn run_show(args: list[ref u8], start: usize) i32 = trust {+    val rev: mut bytes.Bytes = bytes.empty()+    val col_titles: mut bool = true+    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"-r", 2) || cmd_is(a, c"-rev", 4)) {+                if i + 1 < @len(args) {+                    val v = @get(args, i + 1)+                    if v is some rv {+                        rev = 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"-no-col-titles", 14) {+                col_titles = false+            } elif !end_flags && is_flag(a) {+                msg.error_prefix()+                stdio.eprint("unknown flag: {s}\n", {str.from_cstr(a)})+                return 1+            } else {+                rev = bytes.from_cstr(a)+            }+        }+        i+++    }+    val repo_opt = open_repo_or_error(str.from_cstr(c"."))+    match repo_opt {+        some repo => {+            val status: i32 = show_cmd.run(repo, rev, col_titles)             layout.free_repo(repo)             return status         }@@ -457,6 +506,9 @@     }     if cmd_is(cmd, c"log", 3) {         return run_log(args, 2)+    }+    if cmd_is(cmd, c"show", 4) {+        return run_show(args, 2)     }     if cmd_is(cmd, c"diff", 4) {         return run_diff(args, 2)@@ -466,6 +518,9 @@     }     if cmd_is(cmd, c"rm", 2) {         return rm_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"bookmark", 8) || cmd_is(cmd, c"bookmarks", 9) {+        return bookmark_cmd.run(args, 2)     }     if cmd_is(cmd, c"ex", 2) {         return ex_cmd.run(args, 2)--- a/veins/src/store/viewops.sx+++ b/veins/src/store/viewops.sx@@ -104,7 +104,14 @@     } } +/// Recompute `heads` from the visible roots. Keeping stale heads makes deleted+/// bookmarks remain visible and would export commits that are no longer+/// referenced, so the list is rebuilt from scratch. pub fn rebuild_heads(v: mut ref view.View) void = trust {+    // Head IDs may point into a decoded view body; only the list itself is+    // owned by this view, never the individual ID spans.+    @listfree(v.heads)+    v.heads = lists.new[objid.Id]()     for bm in v.bookmarks {         for id in bm.targets.adds {             add_unique(v.heads, id)@@ -117,6 +124,110 @@         add_unique(v.heads, w.target)     }     sort_heads(v.heads)+}++/// Move bookmarks that point at `old_id` to `new_id`.+///+/// This is how a named branch follows a commit that is rewritten by the+/// working-copy snapshotter, `describe`, or `rm`. It is an explicit consequence+/// of the state-changing command that rewrote the commit; `checkout` and `new`+/// do not call it.+pub fn move_bookmarks(v: ref view.View, old_id: objid.Id, new_id: objid.Id) void = trust {+    if same(old_id, new_id) {+        return+    }+    val i: mut usize = 0+    for i < @len(v.bookmarks) {+        val existing = @get(v.bookmarks, i)+        if existing is some bm {+            if contains(bm.targets.adds, old_id) {+                @listfree(bm.targets.adds)+                @listfree(bm.targets.removes)+                bm.targets.adds = lists.new[objid.Id]()+                bm.targets.removes = lists.new[objid.Id]()+                @append(bm.targets.adds, copy_id(new_id))+            }+        }+        i+++    }+}++pub fn find_bookmark(v: ref view.View, name: bytes.Bytes) option[usize] = trust {+    val i: mut usize = 0+    for i < @len(v.bookmarks) {+        val o = @get(v.bookmarks, i)+        if o is some bm {+            if bytes.Bytes.eql(bm.name, name) {+                return some i+            }+        }+        i+++    }+    return none+}++pub fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {+    val i: mut usize = 1+    for i < @len(xs) {+        val cur = @get(xs, i)+        val c: mut ref view.Bookmark = none+        if cur is some v {+            c = v+        }+        val j: mut usize = i+        for j > 0 {+            val prev_opt = @get(xs, j - 1)+            val prev: mut ref view.Bookmark = none+            if prev_opt is some v2 {+                prev = v2+            }+            if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+                break+            }+            @set(xs, j, prev)+            j--+        }+        @set(xs, j, c)+        i+++    }+}++pub fn sort_tags(xs: mut list[ref view.TagRef]) void = trust {+    val i: mut usize = 1+    for i < @len(xs) {+        val cur = @get(xs, i)+        val c: mut ref view.TagRef = none+        if cur is some v {+            c = v+        }+        val j: mut usize = i+        for j > 0 {+            val prev_opt = @get(xs, j - 1)+            val prev: mut ref view.TagRef = none+            if prev_opt is some v2 {+                prev = v2+            }+            if bytes.Bytes.cmp(prev.name, c.name) <= 0 {+                break+            }+            @set(xs, j, prev)+            j--+        }+        @set(xs, j, c)+        i+++    }+}++/// True when the bookmark's target set is the resolved single target `id`.+pub fn bookmark_points_at(bm: ref view.Bookmark, id: objid.Id) bool = trust {+    if @len(bm.targets.adds) != 1 || @len(bm.targets.removes) != 0 {+        return false+    }+    val o = @get(bm.targets.adds, 0)+    if o is some only {+        return same(only, id)+    }+    return false }  pub fn bookmark_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {--- a/veins/src/worktree/checkout.sx+++ b/veins/src/worktree/checkout.sx@@ -3,6 +3,7 @@ val str        = use("std/string") val stdio      = use("std/stdio") val msg        = use("../core/msg.sx")+val fs         = use("std/fs") val allocators = use("std/allocators") val thread     = use("std/thread") val bytes      = use("../core/bytes.sx")@@ -12,13 +13,18 @@ val names      = use("../object/names.sx") val blob       = use("../object/blob.sx") val tree       = use("../object/tree.sx")-val commit     = use("../object/commit.sx")+val graph      = use("../object/graph.sx")+val treewalk   = use("../object/treewalk.sx") val view       = use("../object/view.sx") val store      = use("../store/store.sx") val layout     = use("../store/layout.sx") val state      = use("../store/state.sx")+val txn        = use("../store/txn.sx")+val viewops    = use("../store/viewops.sx")+val snapshot   = use("../worktree/snapshot.sx") val files      = use("../io/files.sx") val native     = use("../io/native.sx")+val stat       = use("../io/stat.sx") val object     = use("../git/object.sx") val lazy       = use("../git/lazy.sx") @@ -138,9 +144,19 @@ }  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 join_bytes(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {@@ -607,152 +623,98 @@     files.free_buffer(body) } -fn parse_veins_hex(hex: bytes.Bytes) option[objid.Id] = trust {-    if hex.len != 64 {-        return none-    }-    val raw: ref u8 = @alloc(32) as ref u8-    val i: mut usize = 0-    for i < 32 {-        val hi_c: u8 = bytes.Bytes.at(hex, i * 2)-        val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)-        val hi: mut i32 = -1-        val lo: mut i32 = -1-        if hi_c >= 48 && hi_c <= 57 {-            hi = (hi_c - 48) as i32-        } elif hi_c >= 97 && hi_c <= 102 {-            hi = (hi_c - 87) as i32-        } elif hi_c >= 65 && hi_c <= 70 {-            hi = (hi_c - 55) as i32-        }-        if lo_c >= 48 && lo_c <= 57 {-            lo = (lo_c - 48) as i32-        } elif lo_c >= 97 && lo_c <= 102 {-            lo = (lo_c - 87) as i32-        } elif lo_c >= 65 && lo_c <= 70 {-            lo = (lo_c - 55) as i32-        }-        if hi < 0 || lo < 0 {-            @free(raw as ref void)-            return none-        }-        @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))-        i+++fn tree_of_commit(+    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(copy_id(lc.c.root_tree))+        graph.free_loaded(lc)     }-    return some objid.id(raw)+    return out } -fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {-    for bm in v.bookmarks {-        if bytes.Bytes.eql(bm.name, name) {-            if @len(bm.targets.adds) == 1 {-                val a = @get(bm.targets.adds, 0)-                if a is some id {-                    return some id-                }+fn prune_empty_parents(repo: layout.Repo, rel: bytes.Bytes) void = trust {+    val i: mut usize = rel.len+    for i > 0 {+        val slash: mut i64 = -1+        val k: mut usize = 0+        for k < i {+            if bytes.Bytes.at(rel, k) == 47 {+                slash = k as i64             }-            return none+            k++         }-    }-    return none-}--fn tag_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {-    for t in v.tags {-        if bytes.Bytes.eql(t.name, name) {-            return some t.target+        if slash < 0 {+            break         }-    }-    return none-}--fn working_copy_target(v: ref view.View) option[objid.Id] = trust {-    for w in v.working_copies {-        if bytes.Bytes.eql(w.workspace, bytes.bytes(c"default", 7)) {-            return some w.target+        val parent: bytes.Bytes = bytes.Bytes.slice(rel, 0, slash as usize)+        val parent_view: str.StringView = str.view(parent.ptr, parent.len as i64)+        val abs: str.StringView = files.join(layout.root_view(repo), parent_view)+        val removed: bool = fs.rmdir_path(abs)+        files.free_path(abs)+        if !removed {+            break         }-    }-    return none-}--fn resolve_revision(v: ref view.View, rev: bytes.Bytes) option[objid.Id] = trust {-    if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {-        return working_copy_target(v)-    }-    val bm = bookmark_target(v, rev)-    if bm is some id {-        return some id-    }-    val tg = tag_target(v, rev)-    if tg is some id2 {-        return some id2+        i = slash as usize     }-    return parse_veins_hex(rev) } -/// Check out `rev` (empty means the working-copy commit) into the repository.-pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {-    val store_handle: mut store.Store = store.open_all(repo)-    val mut_view = state.current_view(repo, store_handle.handles)-    val v: mut ref view.View = none-    match mut_view {-        some x => {-            v = x-        }-        none => {-            msg.error_prefix()-            stdio.eprint("no operation state; import a repository first\n", {})-            store.close(store_handle)-            return 1-        }-    }-    val target_opt = resolve_revision(v, rev)-    val commit_id: mut objid.Id = objid.id_none()-    match target_opt {-        some id => {-            commit_id = id+/// Delete files that were tracked by the old tree but are not part of the new+/// tree. Untracked and ignored files are never touched.+fn delete_stale(+    repo: layout.Repo,+    handles: list[ref store.Handle],+    old_tree: option[objid.Id],+    new_tree: option[objid.Id]+) bool = trust {+    val old_entries: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, old_tree)+    val new_entries: list[ref treewalk.FlatEntry] = treewalk.flatten_or_empty(handles, new_tree)+    val success: mut bool = true+    for e in old_entries {+        if e.kind == tree.KIND_SUBMODULE {+            continue         }-        none => {-            msg.error_prefix()-            stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})-            view.free_view(v)-            store.close(store_handle)-            return 1+        val keep = treewalk.lookup(new_entries, e.path)+        if keep is some _ {+            continue         }-    }-    val cbody_opt = state.read_body(store_handle.handles, commit_id, types.COMMIT)-    val cbody: mut bytes.Bytes = bytes.empty()-    match cbody_opt {-        some b => {-            cbody = b+        val rel: str.StringView = str.view(e.path.ptr, e.path.len as i64)+        val abs: str.StringView = files.join(layout.root_view(repo), rel)+        val info_opt = stat.read(abs)+        val existed: mut bool = false+        if info_opt is some info {+            if info.kind != stat.KIND_MISSING {+                existed = true+            }         }-        none => {-            msg.error_prefix()-            stdio.eprint("cannot read commit\n", {})-            view.free_view(v)-            store.close(store_handle)-            return 1+        if existed {+            if !files.delete(abs) {+                success = false+            } else {+                prune_empty_parents(repo, e.path)+            }         }+        files.free_path(abs)     }-    val cdecoded = commit.decode(cbody)-    val c: mut ref commit.Commit = none-    match cdecoded {-        ok x => {-            c = x-        }-        err _ => {-            files.free_buffer(cbody)-            msg.error_prefix()-            stdio.eprint("corrupt commit\n", {})-            view.free_view(v)-            store.close(store_handle)-            return 1-        }+    treewalk.free_flat(old_entries)+    treewalk.free_flat(new_entries)+    return success+}++fn materialize_tree(+    repo: layout.Repo,+    handles: list[ref store.Handle],+    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_tree: objid.Id = copy_id(c.root_tree)-    commit.free_commit(c)-    files.free_buffer(cbody)-    view.free_view(v)      val root: str.StringView = layout.root_view(repo)     val root_c: ref u8 = bytes.Bytes.to_cstr(bytes.from_cstr(root.ptr))@@ -761,7 +723,6 @@     if root_fd < 0 {         msg.error_prefix()         stdio.eprint("cannot open working directory\n", {})-        store.close(store_handle)         return 1     } @@ -768,18 +729,17 @@     val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]()     val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()     val walk: mut CheckoutWalk = CheckoutWalk{-        handles: store_handle.handles,+        handles: handles,         tasks: tasks,         dirs: dirs,         failed: false,         error: bytes.empty()     }-    walk_tree(walk, root_tree, bytes.empty(), 0)+    walk_tree(walk, new_root, bytes.empty(), 0)     if walk.failed {         msg.error_prefix()         stdio.eprint("checkout tree validation failed\n", {})         close(root_fd)-        store.close(store_handle)         return 1     } @@ -794,7 +754,6 @@     }     if dir_failed {         close(root_fd)-        store.close(store_handle)         return 1     } @@ -840,7 +799,7 @@     val w: mut usize = 0     for w < workers {         val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob-        job.handles = store_handle.handles+        job.handles = handles         job.root_fd = root_fd         job.tasks = tasks         job.start = w@@ -908,12 +867,197 @@             msg.error_prefix()             stdio.eprint("checkout failed\n", {})         }-        store.close(store_handle)         return 1     }      msg.info_prefix()     stdio.print("checked out {d} files\n", {n})-    store.close(store_handle)+    return 0+}++/// Drop the stat cache after files were written or removed by something other+/// than the snapshotter, so the next snapshot re-reads them instead of trusting+/// stale size/mtime/inode data.+pub fn clear_stat_cache(repo: layout.Repo) void = trust {+    val dir: str.StringView = layout.working_copy_dir(repo)+    val path: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))+    val _ = files.delete(path)+    files.free_path(path)+    files.free_path(dir)+}++/// Materialize `new_root` into the working tree while removing files tracked by+/// `old_tree`. Used by `vn new <rev>` after it has already created its commit.+pub fn materialize_commit(+    repo: layout.Repo,+    handles: list[ref store.Handle],+    old_tree: option[objid.Id],+    new_root: objid.Id+) i32 = trust {+    val same: mut bool = false+    if old_tree is some old_id {+        if objid.Id.eql(old_id, new_root) {+            same = true+        }+    }+    if same {+        return 0+    }+    val status: i32 = materialize_tree(repo, handles, old_tree, new_root)+    if status == 0 {+        clear_stat_cache(repo)+    }+    return status+}++/// Bring the files in the working directory in line with a view whose+/// working-copy commit may have been removed (`vn op restore`/`vn undo`).+pub fn materialize_optional(+    repo: layout.Repo,+    handles: list[ref store.Handle],+    old_tree: option[objid.Id],+    new_tree: option[objid.Id]+) i32 = trust {+    if new_tree is some new_root {+        return materialize_commit(repo, handles, old_tree, new_root)+    }+    if !delete_stale(repo, handles, old_tree, none) {+        msg.error_prefix()+        stdio.eprint("cannot remove files absent from the restored view\n", {})+        return 1+    }+    clear_stat_cache(repo)     return 0+}++/// Check out `rev` (empty means the working-copy commit) into the repository.+/// The working-copy commit is moved to the target, so subsequent edits amend+/// that commit and any bookmark naming it follows the rewrite.+pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {+    val snap: i32 = snapshot.run(repo)+    if snap != 0 {+        return snap+    }+    val store_handle: mut store.Store = store.open_all(repo)+    val mut_view = state.current_view(repo, store_handle.handles)+    val v: mut ref view.View = none+    match mut_view {+        some x => {+            v = x+        }+        none => {+            msg.error_prefix()+            stdio.eprint("no operation state; import a repository first\n", {})+            store.close(store_handle)+            return 1+        }+    }+    val target_opt = graph.resolve(store_handle.handles, v, rev)+    val target: mut objid.Id = objid.id_none()+    val have_target: mut bool = false+    match target_opt {+        some id => {+            target = copy_id(id)+            have_target = true+        }+        none => {+        }+    }+    if !have_target {+        msg.error_prefix()+        stdio.eprint("unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})+        view.free_view(v)+        store.close(store_handle)+        return 1+    }+    val new_root_opt = tree_of_commit(store_handle.handles, target)+    val new_root: mut objid.Id = objid.id_none()+    val have_root: mut bool = false+    if new_root_opt is some nr {+        new_root = nr+        have_root = true+    }+    if !have_root {+        msg.error_prefix()+        stdio.eprint("cannot read commit\n", {})+        view.free_view(v)+        store.close(store_handle)+        free_id(target)+        return 1+    }++    val wc_opt = viewops.working_copy(v)+    val wc: mut objid.Id = objid.id_none()+    val have_wc: mut bool = false+    val old_root: mut option[objid.Id] = none+    if wc_opt is some id2 {+        wc = id2+        have_wc = true+        old_root = tree_of_commit(store_handle.handles, wc)+    }+    view.free_view(v)++    val status: mut i32 = materialize_commit(repo, store_handle.handles, old_root, new_root)+    if status != 0 {+        store.close(store_handle)+        free_id(target)+        free_id(new_root)+        if have_wc {+            free_id(wc)+        }+        if old_root is some or1 {+            free_id(or1)+        }+        return status+    }++    val same_target: mut bool = false+    if have_wc {+        if objid.Id.eql(wc, target) {+            same_target = true+        }+    }+    if !same_target {+        val tx_opt = txn.begin(repo)+        val tx: mut ref txn.Txn = none+        match tx_opt {+            some t => {+                tx = t+            }+            none => {+                msg.error_prefix()+                stdio.eprint("cannot load repository state\n", {})+                store.close(store_handle)+                free_id(target)+                free_id(new_root)+                if have_wc {+                    free_id(wc)+                }+                if old_root is some or2 {+                    free_id(or2)+                }+                return 1+            }+        }+        if have_wc {+            viewops.remove_head(tx.view, wc)+        }+        viewops.set_workspace(tx.view, target)+        viewops.rebuild_heads(tx.view)+        val op_status: i32 = txn.finish(tx, bytes.bytes(c"checkout", 8))+        if op_status != 0 {+            status = op_status+        }+    }++    store.close(store_handle)+    free_id(target)+    free_id(new_root)+    if have_wc {+        free_id(wc)+    }+    if old_root is some or3 {+        free_id(or3)+    }+    return status }--- a/veins/src/worktree/snapshot.sx+++ b/veins/src/worktree/snapshot.sx@@ -943,6 +943,8 @@      if have_wc {         remove_wc_head(tx.view, wc)+        // A bookmark that named the amended commit follows it.+        viewops.move_bookmarks(tx.view, wc, new_commit)     }     viewops.set_workspace(tx.view, new_commit)     viewops.rebuild_heads(tx.view)