navid/veins / commit
aa947294b511
Navid M <navidmomtahen@gmail.com> · 2026-11-26
parents: 4d24b0b41743
Browse files at this commit · Download source
--- /dev/null+++ b/src/src/cli/diff_cmd.sx@@ -0,0 +1,311 @@+/// `vn diff [-r <rev>]`: show a unified diff.++val str = use("std/string")+val stdio = use("std/stdio")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val tree = use("../object/tree.sx")+val view = use("../object/view.sx")+val graph = use("../object/graph.sx")+val treediff = use("../object/treediff.sx")+val treewalk = use("../object/treewalk.sx")+val content = use("../object/content.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 files = use("../io/files.sx")+val object = use("../git/object.sx")+val snapshot = use("../worktree/snapshot.sx")++type DiffOp = {+ tag: mut u8+ ai: mut usize+ bi: mut usize+}++pub type GitSource = {+ repo: mut object.GitRepo+ open: mut bool+}++pub fn open_git(repo: layout.Repo) GitSource = trust {+ val p: str.StringView = layout.git_dir(repo)+ val r = object.open(p)+ files.free_path(p)+ val g: mut GitSource = GitSource{repo: @zeroed, open: false}+ match r {+ ok x => {+ g.repo = x+ g.open = true+ }+ err _ => {+ }+ }+ return g+}++pub fn close_git(g: mut GitSource) void = trust {+ if g.open {+ object.free(g.repo)+ g.open = false+ }+}++fn contains_nul(data: bytes.Bytes) bool = trust {+ val n: usize = data.len+ val limit: usize = 8192+ val i: mut usize = 0+ for i < n && i < limit {+ if bytes.Bytes.at(data, i) == 0 {+ return true+ }+ i+++ }+ return false+}++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 {+ val at_end: bool = i == data.len+ if at_end || bytes.Bytes.at(data, i) == 10 {+ if i > start || !at_end || bytes.Bytes.at(data, i - 1) != 10 {+ @append(out, bytes.Bytes.slice(data, start, i))+ }+ start = i + 1+ }+ i+++ }+ return out+}++fn render_one(+ handles: list[ref store.Handle],+ git: ref GitSource,+ change: ref treediff.Change+) void = trust {+ val path_view = str.view(change.path.ptr, change.path.len as i64)+ if change.new_kind == tree.KIND_CONFLICT {+ stdio.print("Conflict: {s}\n", {path_view})+ return+ }+ val old_data: mut bytes.Bytes = bytes.empty()+ val new_data: mut bytes.Bytes = bytes.empty()+ val old_owned: mut bool = false+ val new_owned: mut bool = false+ if change.old_kind != treewalk.KIND_MISSING {+ val o = content.read_blob(handles, change.old_id, git.repo, git.open)+ if o is some d {+ old_data = d+ old_owned = true+ }+ }+ if change.new_kind != treewalk.KIND_MISSING {+ val n = content.read_blob(handles, change.new_id, git.repo, git.open)+ if n is some d {+ new_data = d+ new_owned = true+ }+ }+ if contains_nul(old_data) || contains_nul(new_data) {+ stdio.print("Binary files a/{s} and b/{s} differ\n", {path_view, path_view})+ } else {+ stdio.print("--- ", {})+ if change.old_kind == treewalk.KIND_MISSING {+ stdio.print("/dev/null", {})+ } else {+ stdio.print("a/{s}", {path_view})+ }+ stdio.print("\n+++ ", {})+ if change.new_kind == treewalk.KIND_MISSING {+ stdio.print("/dev/null", {})+ } else {+ stdio.print("b/{s}", {path_view})+ }+ stdio.print("\n", {})+ val a = split_lines(old_data)+ val b = split_lines(new_data)+ val a_count: usize = @len(a)+ val b_count: usize = @len(b)+ val a_start: mut usize = 1+ if a_count == 0 {+ a_start = 0+ }+ val b_start: mut usize = 1+ if b_count == 0 {+ b_start = 0+ }+ stdio.print("@@ -{d},{d} +{d},{d} @@\n", {a_start, a_count, b_start, b_count})+ val ai: mut usize = 0+ for ai < a_count {+ val line = line_at(a, ai)+ stdio.print("-{s}\n", {str.view(line.ptr, line.len as i64)})+ ai+++ }+ val bi: mut usize = 0+ for bi < b_count {+ val line2 = line_at(b, bi)+ stdio.print("+{s}\n", {str.view(line2.ptr, line2.len as i64)})+ bi+++ }+ @listfree(a)+ @listfree(b)+ }+ if old_owned {+ files.free_buffer(old_data)+ }+ if new_owned {+ files.free_buffer(new_data)+ }+}++pub fn render(+ handles: list[ref store.Handle],+ git: mut GitSource,+ old_tree: option[objid.Id],+ new_tree: option[objid.Id]+) void = trust {+ val changes = treediff.compare(handles, old_tree, new_tree)+ for c in changes {+ render_one(handles, git, c)+ }+ treediff.free(changes)+}++fn list_bytes(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {+ val o = @get(xs, i)+ if o is some b {+ return b+ }+ return bytes.empty()+}++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+ match lc_opt {+ some lc => {+ out = some(graph.copy_id(lc.c.root_tree))+ graph.free_loaded(lc)+ }+ none => {+ }+ }+ return out+}++fn parent_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+ match lc_opt {+ some lc => {+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ val t = tree_of(handles, pid)+ match t {+ some tid => {+ out = some(tid)+ }+ none => {+ }+ }+ }+ }+ graph.free_loaded(lc)+ }+ none => {+ }+ }+ 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)+ }+ }+}++pub fn run(repo: layout.Repo, revs: list[bytes.Bytes]) 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)+ stdio.eprint("vn: no operation state\n", {})+ return 1+ }+ }+ val old_tree: mut option[objid.Id] = none+ val new_tree: mut option[objid.Id] = none+ val status: mut i32 = 0+ if @len(revs) >= 2 {+ val a: bytes.Bytes = list_bytes(revs, 0)+ val b: bytes.Bytes = list_bytes(revs, 1)+ val ra = graph.resolve(st.handles, v, a)+ val rb = graph.resolve(st.handles, v, b)+ if ra is some ia {+ old_tree = tree_of(st.handles, ia)+ } else {+ status = 1+ }+ if rb is some ib {+ new_tree = tree_of(st.handles, ib)+ } else {+ status = 1+ }+ } elif @len(revs) == 1 {+ val a: bytes.Bytes = list_bytes(revs, 0)+ val ra = graph.resolve(st.handles, v, a)+ if ra is some ia {+ old_tree = parent_tree_of(st.handles, ia)+ new_tree = tree_of(st.handles, ia)+ } else {+ status = 1+ }+ } else {+ val wc_opt = viewops.working_copy(v)+ if wc_opt is some wc {+ old_tree = parent_tree_of(st.handles, wc)+ new_tree = tree_of(st.handles, wc)+ }+ }+ if status != 0 {+ stdio.eprint("vn: unknown revision\n", {})+ } else {+ val git: mut GitSource = open_git(repo)+ render(st.handles, git, old_tree, new_tree)+ close_git(git)+ }+ free_tree_opt(old_tree)+ free_tree_opt(new_tree)+ view.free_view(v)+ store.close(st)+ return status+}++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()+}--- a/src/src/cli/git_cmd.sx+++ b/src/src/cli/git_cmd.sx@@ -6,6 +6,7 @@ val layout = use("../store/layout.sx") val mirror = use("../git/mirror.sx") val import = use("../git/import.sx")+val export = use("../git/export.sx") pub fn run(args: list[ref u8], start: usize) i32 = trust { val sub_opt = @get(args, start)@@ -19,11 +20,14 @@ return 1 } }- if @strcmp(sub, c"import") != 0 {- stdio.eprint("vn: unknown git subcommand: {s}\n", {str.from_cstr(sub)})- return 1+ if @strcmp(sub, c"import") == 0 {+ return run_import(args, start + 1) }- return run_import(args, start + 1)+ if @strcmp(sub, c"export") == 0 {+ return run_export(args, start + 1)+ }+ stdio.eprint("vn: unknown git subcommand: {s}\n", {str.from_cstr(sub)})+ return 1 } fn run_import(args: list[ref u8], start: usize) i32 = trust {@@ -73,6 +77,38 @@ } } val status: i32 = import.run(repo)+ layout.free_repo(repo)+ return status+}+++fn run_export(args: list[ref u8], start: usize) i32 = trust {+ val repo_path: mut str.StringView = str.from_cstr(c".")+ val i: mut usize = start+ for i < @len(args) {+ val arg_opt = @get(args, i)+ if arg_opt is some a {+ val av: bytes.Bytes = bytes.from_cstr(a)+ if av.len > 0 && bytes.Bytes.at(av, 0) == 45 {+ stdio.eprint("vn: unknown flag: {s}\n", {str.from_cstr(a)})+ return 1+ }+ repo_path = str.from_cstr(a)+ }+ i+++ }+ val repo_opt = layout.discover(repo_path)+ val repo: mut layout.Repo = layout.Repo{root: @zeroed}+ match repo_opt {+ some r => {+ repo = r+ }+ none => {+ stdio.eprint("vn: not a vein repository: {s}\n", {repo_path})+ return 1+ }+ }+ val status: i32 = export.run(repo) layout.free_repo(repo) return status }--- a/src/src/cli/help_cmd.sx+++ b/src/src/cli/help_cmd.sx@@ -12,8 +12,16 @@ stdio.puts("") stdio.puts("commands:") stdio.puts(" init create a repository")- stdio.puts(" git import from git")+ stdio.puts(" git import from or export to git") stdio.puts(" checkout write a revision into the working directory")+ stdio.puts(" status show working-copy changes")+ stdio.puts(" log show commit history")+ stdio.puts(" diff show a unified diff")+ stdio.puts(" new start a new change")+ stdio.puts(" describe set the working-copy commit message")+ stdio.puts(" commit describe and start a new change")+ stdio.puts(" undo restore the previous operation view")+ stdio.puts(" op operation log commands") stdio.puts(" fsck verify repository integrity") stdio.puts(" self-test run the format self-tests") stdio.puts(" version print version information")@@ -41,6 +49,7 @@ stdio.puts("git bridge commands:") stdio.puts(" import [-source:<gitdir>] [path]") stdio.puts(" import reachable git commits and refs")+ stdio.puts(" export [path] export commits into the git mirror") stdio.puts("") stdio.puts("run 'vn help git <subcommand>' for details") }@@ -95,6 +104,60 @@ stdio.puts("usage: vn version") stdio.puts("") stdio.puts("print version information")+}++fn show_status() void = trust {+ stdio.puts("usage: vn status")+ stdio.puts("")+ stdio.puts("show working-copy changes relative to the parent commit")+}++fn show_log() void = trust {+ stdio.puts("usage: vn log [-r <revset>]")+ stdio.puts("")+ stdio.puts("show commit history")+}++fn show_diff() void = trust {+ stdio.puts("usage: vn diff [-r <rev>] [<rev> <rev>]")+ stdio.puts("")+ stdio.puts("show a unified diff")+}++fn show_new() void = trust {+ 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_describe() void = trust {+ stdio.puts("usage: vn describe [-m <message>] [<message>]")+ stdio.puts("")+ stdio.puts("set the working-copy commit message")+}++fn show_commit() void = trust {+ stdio.puts("usage: vn commit -m <message>")+ stdio.puts("")+ stdio.puts("set the message and start a new change")+}++fn show_undo() void = trust {+ stdio.puts("usage: vn undo")+ stdio.puts("")+ stdio.puts("record an operation that restores the previous operation view")+}++fn show_op() void = trust {+ stdio.puts("usage: vn op <log|restore|revert> [<op>]")+ stdio.puts("")+ stdio.puts("inspect and restore operations")+}++fn show_git_export() void = trust {+ stdio.puts("usage: vn git export [path]")+ stdio.puts("")+ stdio.puts("export commits reachable from bookmarks and tags into .vein/git") } fn show_help() void = trust {@@ -125,6 +188,38 @@ if cmd_is(cmd, c"init", 4) { show_init()+ return 0+ }+ if cmd_is(cmd, c"status", 6) {+ show_status()+ return 0+ }+ if cmd_is(cmd, c"log", 3) {+ show_log()+ return 0+ }+ if cmd_is(cmd, c"diff", 4) {+ show_diff()+ return 0+ }+ if cmd_is(cmd, c"new", 3) {+ show_new()+ return 0+ }+ if cmd_is(cmd, c"describe", 8) {+ show_describe()+ return 0+ }+ if cmd_is(cmd, c"commit", 6) {+ show_commit()+ return 0+ }+ if cmd_is(cmd, c"undo", 4) {+ show_undo()+ return 0+ }+ if cmd_is(cmd, c"op", 2) {+ show_op() return 0 } if cmd_is(cmd, c"git", 3) {@@ -133,6 +228,10 @@ if sub_opt is some sub { if cmd_is(sub, c"import", 6) { show_git_import()+ return 0+ }+ if cmd_is(sub, c"export", 6) {+ show_git_export() return 0 } stdio.eprint("vn: unknown git subcommand: {s}\n", {str.from_cstr(sub)})--- /dev/null+++ b/src/src/cli/log_cmd.sx@@ -0,0 +1,295 @@+/// `vn log [-r <revset>]`: show commit history.++val str = use("std/string")+val stdio = use("std/stdio")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.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 treewalk = use("../object/treewalk.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")++type LogRec = {+ id: mut objid.Id+ cid: mut bytes.Bytes+ seconds: mut i64+ tree: mut objid.Id+ message: mut bytes.Bytes+ author: mut bytes.Bytes+ conflicted: mut bool+}++fn new_rec(+ id: objid.Id,+ cid: bytes.Bytes,+ seconds: i64,+ tree_id: objid.Id,+ message: bytes.Bytes,+ author: bytes.Bytes+) ref LogRec = trust {+ val r: mut ref LogRec = @alloc(@sizeof(LogRec)) as ref LogRec+ r.id = graph.copy_id(id)+ r.cid = bytes.Bytes.dup(cid)+ r.seconds = seconds+ r.tree = graph.copy_id(tree_id)+ r.message = bytes.Bytes.dup(message)+ r.author = bytes.Bytes.dup(author)+ r.conflicted = false+ return r+}++fn free_recs(rs: list[ref LogRec]) void = trust {+ for r in rs {+ if r.id.ptr != none {+ val p: mut ref void = r.id.ptr as ref void+ @free(p)+ }+ if r.cid.ptr != none {+ val p2: mut ref void = r.cid.ptr as ref void+ @free(p2)+ }+ if r.tree.ptr != none {+ val p3: mut ref void = r.tree.ptr as ref void+ @free(p3)+ }+ if r.message.ptr != none {+ val p4: mut ref void = r.message.ptr as ref void+ @free(p4)+ }+ if r.author.ptr != none {+ val p5: mut ref void = r.author.ptr as ref void+ @free(p5)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rs)+}++fn rec_at(rs: list[ref LogRec], i: usize) ref LogRec = trust {+ val o = @get(rs, i)+ if o is some r {+ return r+ }+ assert false+ return none+}++fn sort_recs(rs: mut list[ref LogRec]) void = trust {+ val i: mut usize = 1+ for i < @len(rs) {+ val cur = @get(rs, i)+ val c: mut ref LogRec = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_opt = @get(rs, j - 1)+ val prev: mut ref LogRec = none+ if prev_opt is some v2 {+ prev = v2+ }+ if prev.seconds >= c.seconds {+ break+ }+ @set(rs, j, prev)+ j--+ }+ @set(rs, j, c)+ i+++ }+}++fn first_line(msg: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = 0+ for i < msg.len {+ if bytes.Bytes.at(msg, i) == 10 {+ return bytes.Bytes.slice(msg, 0, i)+ }+ i+++ }+ return msg+}++fn short_cid(rs: list[ref LogRec], idx: usize) bytes.Bytes = trust {+ val target: ref LogRec = rec_at(rs, idx)+ val limit: usize = target.cid.len+ val len: mut usize = 4+ if len > limit {+ len = limit+ }+ for len < limit {+ val prefix: bytes.Bytes = bytes.Bytes.slice(target.cid, 0, len)+ val unique: mut bool = true+ val j: mut usize = 0+ for j < @len(rs) {+ if j != idx {+ val other: ref LogRec = rec_at(rs, j)+ if !bytes.Bytes.eql(other.cid, target.cid) {+ if bytes.Bytes.starts_with(other.cid, prefix) {+ unique = false+ break+ }+ }+ }+ j+++ }+ if unique {+ break+ }+ len+++ }+ return bytes.Bytes.dup(bytes.Bytes.slice(target.cid, 0, len))+}++pub fn run(repo: layout.Repo, rev: bytes.Bytes) 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)+ stdio.eprint("vn: no operation state\n", {})+ return 1+ }+ }+ val wc_opt = viewops.working_copy(v)+ val wc: mut objid.Id = objid.id_none()+ if wc_opt is some id {+ wc = id+ }+ val roots: list[objid.Id] = graph.roots(v)+ val ids: list[objid.Id] = collect_ids(st.handles, v, roots, rev)+ graph.free_ids(roots)+ val recs: mut list[ref LogRec] = lists.new[ref LogRec]()+ for id in ids {+ val lc_opt = graph.load_commit(st.handles, id)+ match lc_opt {+ some lc => {+ val cid_full: bytes.Bytes = changeid.encode(lc.c.change_id)+ val msg: bytes.Bytes = first_line(lc.c.message)+ val rec: mut ref LogRec = new_rec(+ id,+ cid_full,+ lc.c.committer.seconds,+ lc.c.root_tree,+ msg,+ lc.c.author.name+ )+ rec.conflicted = treewalk.conflicted(st.handles, lc.c.root_tree)+ changeid.free(cid_full)+ graph.free_loaded(lc)+ @append(recs, rec)+ }+ none => {+ }+ }+ }+ sort_recs(recs)+ val i: mut usize = 0+ for i < @len(recs) {+ val r: ref LogRec = rec_at(recs, i)+ val marker: mut str.StringView = str.from_cstr(c" ")+ if objid.Id.eql(r.id, wc) {+ marker = str.from_cstr(c"@")+ }+ val hex: ref u8 = objid.Id.hex(r.id)+ val short: str.StringView = str.view(hex, 12)+ val cid: bytes.Bytes = short_cid(recs, i)+ val stamp: bytes.Bytes = datetime.format_utc(r.seconds)+ val msg_view = str.view(r.message.ptr, r.message.len as i64)+ val author_view = str.view(r.author.ptr, r.author.len as i64)+ stdio.print(+ "{s} {s} {s} {s} {s} {s}",+ {+ marker,+ short,+ str.view(cid.ptr, cid.len as i64),+ str.view(stamp.ptr, stamp.len as i64),+ author_view,+ msg_view+ }+ )+ val names = viewops.bookmark_names(v, r.id)+ for name in names {+ stdio.print(" [{s}]", {str.view(name.ptr, name.len as i64)})+ }+ @listfree(names)+ val tnames = viewops.tag_names(v, r.id)+ for name in tnames {+ stdio.print(" <{s}>", {str.view(name.ptr, name.len as i64)})+ }+ @listfree(tnames)+ if r.conflicted {+ stdio.print(" (conflicted)", {})+ }+ val divergent: mut bool = false+ val j: mut usize = 0+ for j < @len(recs) {+ if j != i {+ val other = rec_at(recs, j)+ if bytes.Bytes.eql(other.cid, r.cid) {+ divergent = true+ break+ }+ }+ j+++ }+ if divergent {+ stdio.print(" (divergent)", {})+ }+ stdio.print("\n", {})+ @free(hex as ref void)+ changeid.free(cid)+ // timestamp is freed by the arena-style process exit+ i+++ }+ free_recs(recs)+ graph.free_ids(ids)+ view.free_view(v)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ store.close(st)+ return 0+}++fn collect_ids(+ handles: list[ref store.Handle],+ v: ref view.View,+ roots: list[objid.Id],+ rev: bytes.Bytes+) list[objid.Id] = trust {+ if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"all()", 5)) {+ return graph.collect(handles, roots)+ }+ val resolved = graph.resolve(handles, v, rev)+ match resolved {+ some id => {+ val one: mut list[objid.Id] = lists.new[objid.Id]()+ @append(one, graph.copy_id(id))+ val out = graph.collect(handles, one)+ graph.free_ids(one)+ return out+ }+ none => {+ return lists.new[objid.Id]()+ }+ }+}--- /dev/null+++ b/src/src/cli/new_cmd.sx@@ -0,0 +1,334 @@+/// `vn describe`, `vn new`, and `vn commit`.++val stdio = use("std/stdio")+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 txn = use("../store/txn.sx")+val viewops = use("../store/viewops.sx")+val identity = use("../core/identity.sx")+val gitmap = use("../git/map.sx")+val snapshot = use("../worktree/snapshot.sx")+val checkout = use("../worktree/checkout.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 copy_renames(rs: list[ref commit.Rename]) list[ref commit.Rename] = trust {+ val out: mut list[ref commit.Rename] = lists.new[ref commit.Rename]()+ for r in rs {+ @append(+ out,+ commit.new_rename(+ r.parent_index,+ r.kind,+ bytes.Bytes.dup(r.from_path),+ bytes.Bytes.dup(r.to_path)+ )+ )+ }+ return out+}++fn copy_kvs(xs: list[ref prim.KeyValue]) list[ref prim.KeyValue] = trust {+ val out: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ for kv in xs {+ @append(out, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))+ }+ return out+}++fn free_renames(rs: list[ref commit.Rename]) void = trust {+ for r in rs {+ 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)+}++fn free_kvs(xs: list[ref prim.KeyValue]) void = trust {+ for kv in xs {+ if kv.key.ptr != none {+ val kp: mut ref void = kv.key.ptr as ref void+ @free(kp)+ }+ if kv.value.ptr != none {+ val vp: mut ref void = kv.value.ptr as ref void+ @free(vp)+ }+ val xp: mut ref void = kv as ref void+ @free(xp)+ }+ @listfree(xs)+}++fn join_args(args: list[bytes.Bytes]) bytes.Bytes = trust {+ val b: mut buf.Buf = buf.new(64)+ val i: mut usize = 0+ for i < @len(args) {+ if i > 0 {+ buf.Buf.put_u8(b, 32)+ }+ val o = @get(args, 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+}++pub fn describe(repo: layout.Repo, args: list[bytes.Bytes]) i32 = trust {+ val snap: i32 = snapshot.run(repo)+ if snap != 0 {+ return snap+ }+ val message: bytes.Bytes = join_args(args)+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ stdio.eprint("vn: cannot load repository state\n", {})+ val mp: mut ref void = message.ptr as ref void+ @free(mp)+ return 1+ }+ }+ val wc_opt = viewops.working_copy(tx.view)+ 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+ }+ if !have_wc {+ stdio.eprint("vn: no working-copy commit\n", {})+ txn.abort(tx)+ val mp2: mut ref void = message.ptr as ref void+ @free(mp2)+ return 1+ }+ val st: store.Store = store.open_all(repo)+ val lc_opt = graph.load_commit(st.handles, wc)+ if lc_opt is none {+ stdio.eprint("vn: cannot read working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ val mp2: mut ref void = message.ptr as ref void+ @free(mp2)+ return 1+ }+ val lc: mut ref graph.LoadedCommit = none+ match lc_opt {+ some x => {+ lc = x+ }+ none => {+ }+ }+ val 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 renames: list[ref commit.Rename] = copy_renames(lc.c.renames)+ val extra: list[ref prim.KeyValue] = copy_kvs(lc.c.extra)+ 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(lc.c.root_tree)+ nc.change_id = lc.c.change_id+ nc.author = lc.c.author+ nc.committer = sig+ nc.message = message+ nc.renames_state = lc.c.renames_state+ nc.renames = renames+ nc.extra = extra+ 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.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ val status: i32 = txn.finish(tx, bytes.bytes(c"describe", 8))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_id)+ }+ store.close(st)+ graph.free_loaded(lc)+ @listfree(parents)+ free_renames(renames)+ free_kvs(extra)+ @free(nc.root_tree.ptr as ref void)+ @free(nc as ref void)+ val mp3: mut ref void = message.ptr as ref void+ @free(mp3)+ val nip: mut ref void = new_id.ptr as ref void+ @free(nip)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ identity.free_sig(sig)+ return status+}++pub fn new_change(repo: layout.Repo, revs: list[bytes.Bytes]) i32 = trust {+ 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 => {+ stdio.eprint("vn: 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()+ val have_wc: mut bool = false+ if wc_opt is some id {+ wc = id+ have_wc = true+ }+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ val root_tree: mut objid.Id = objid.id_none()+ if @len(revs) == 0 {+ if !have_wc {+ stdio.eprint("vn: no working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ return 1+ }+ val lc_opt = graph.load_commit(st.handles, wc)+ match lc_opt {+ some lc => {+ @append(parents, copy_id(wc))+ root_tree = copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ none => {+ stdio.eprint("vn: cannot read working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ return 1+ }+ }+ } else {+ val i: mut usize = 0+ val mut_failed: mut bool = false+ for i < @len(revs) {+ val r = @get(revs, i)+ val rev: mut bytes.Bytes = bytes.empty()+ if r is some v {+ rev = v+ }+ val resolved = graph.resolve(st.handles, tx.view, rev)+ match resolved {+ some id => {+ @append(parents, copy_id(id))+ if i == 0 {+ val lc_opt = graph.load_commit(st.handles, id)+ match lc_opt {+ some lc => {+ root_tree = copy_id(lc.c.root_tree)+ graph.free_loaded(lc)+ }+ none => {+ mut_failed = true+ }+ }+ }+ }+ none => {+ mut_failed = true+ }+ }+ i+++ }+ if mut_failed {+ stdio.eprint("vn: unknown revision\n", {})+ store.close(st)+ txn.abort(tx)+ graph.free_ids(parents)+ return 1+ }+ }+ val cid: ref u8 = @alloc(16) as ref u8+ random.random_bytes(cid as ref void, 16)+ val sig = identity.signature(repo)+ val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+ 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+ nc.parents = parents+ nc.root_tree = root_tree+ nc.change_id = objid.change_id(cid)+ nc.author = sig+ nc.committer = sig+ nc.message = bytes.empty()+ nc.renames_state = commit.RENAMES_RECORDED+ nc.renames = renames+ nc.extra = extra+ val encoded: bytes.Bytes = commit.encode(nc)+ val new_id: objid.Id = txn.add_object(tx, types.COMMIT, encoded)+ if have_wc {+ viewops.remove_head(tx.view, wc)+ }+ viewops.set_workspace(tx.view, new_id)+ viewops.rebuild_heads(tx.view)+ val status: i32 = txn.finish(tx, bytes.bytes(c"new", 3))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_id)+ }+ store.close(st)+ @listfree(parents)+ @listfree(renames)+ @listfree(extra)+ @free(root_tree.ptr as ref void)+ @free(nc as ref void)+ @free(cid as ref void)+ val nip: mut ref void = new_id.ptr as ref void+ @free(nip)+ 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())+ }+ return 0+}--- /dev/null+++ b/src/src/cli/op_cmd.sx@@ -0,0 +1,324 @@+/// Operation log commands: `op log`, `op restore`, `op revert`, and `undo`.++val str = use("std/string")+val stdio = use("std/stdio")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val operation = use("../object/operation.sx")+val view = use("../object/view.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")++type OpRec = {+ id: mut objid.Id+ op: mut ref operation.Operation+}++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 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 free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn collect(+ handles: list[ref store.Handle],+ heads: list[objid.Id]+) list[ref OpRec] = trust {+ val out: mut list[ref OpRec] = lists.new[ref OpRec]()+ val seen: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[objid.Id] = lists.new[objid.Id]()+ for h in heads {+ @append(stack, copy_id(h))+ }+ for @len(stack) > 0 {+ val id: objid.Id = @remove(stack, @len(stack) - 1)+ if contains(seen, id) {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ continue+ }+ @append(seen, copy_id(id))+ val op_opt = state.read_operation(handles, id)+ match op_opt {+ some op => {+ for p in op.parents {+ if !contains(seen, p) {+ @append(stack, copy_id(p))+ }+ }+ val rec: mut ref OpRec = @alloc(@sizeof(OpRec)) as ref OpRec+ rec.id = id+ rec.op = op+ @append(out, rec)+ }+ none => {+ }+ }+ }+ @listfree(stack)+ free_ids(seen)+ return out+}++fn free_recs(recs: list[ref OpRec]) void = trust {+ for r in recs {+ operation.free_operation(r.op)+ if r.id.ptr != none {+ val p: mut ref void = r.id.ptr as ref void+ @free(p)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(recs)+}++fn rec_at(rs: list[ref OpRec], i: usize) ref OpRec = trust {+ val o = @get(rs, i)+ if o is some r {+ return r+ }+ assert false+ return none+}++fn sort_recs(rs: mut list[ref OpRec]) void = trust {+ val i: mut usize = 1+ for i < @len(rs) {+ val cur = @get(rs, i)+ val c: mut ref OpRec = 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 OpRec = none+ if prev_o is some vv {+ prev = vv+ }+ if prev.op.end.ms >= c.op.end.ms {+ break+ }+ @set(rs, j, prev)+ j--+ }+ @set(rs, j, c)+ i+++ }+}++fn resolve_op(recs: list[ref OpRec], text: bytes.Bytes) option[objid.Id] = trust {+ val matches: mut list[objid.Id] = lists.new[objid.Id]()+ val i: mut usize = 0+ for i < @len(recs) {+ val r = rec_at(recs, i)+ val hex: ref u8 = objid.Id.hex(r.id)+ val full: bytes.Bytes = bytes.bytes(hex, 64)+ val matched: bool = full.len >= text.len && bytes.Bytes.eql(bytes.Bytes.slice(full, 0, text.len), text)+ @free(hex as ref void)+ if matched {+ @append(matches, copy_id(r.id))+ }+ i+++ }+ val out: mut option[objid.Id] = none+ if @len(matches) == 1 {+ val o = @get(matches, 0)+ if o is some only {+ out = some copy_id(only)+ }+ }+ free_ids(matches)+ return out+}++fn find_rec(recs: list[ref OpRec], id: objid.Id) option[ref OpRec] = trust {+ for r in recs {+ if objid.Id.eql(r.id, id) {+ return some r+ }+ }+ return none+}++pub fn log(repo: layout.Repo) i32 = trust {+ 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)+ sort_recs(recs)+ val i: mut usize = 0+ for i < @len(recs) {+ val r = rec_at(recs, i)+ val hex: ref u8 = objid.Id.hex(r.id)+ val stamp: bytes.Bytes = datetime.format_utc(r.op.end.ms / 1000)+ val marker: mut str.StringView = str.from_cstr(c" ")+ if contains(heads, r.id) {+ marker = str.from_cstr(c"@")+ }+ stdio.print(+ "{s} {s} {s} {s}\n",+ {+ marker,+ str.view(hex, 12),+ str.view(stamp.ptr, stamp.len as i64),+ str.view(r.op.description.ptr, r.op.description.len as i64)+ }+ )+ @free(hex as ref void)+ // timestamp is freed by the arena-style process exit+ i+++ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return 0+}++fn write_view(+ repo: layout.Repo,+ new_view: ref view.View,+ description: bytes.Bytes+) i32 = trust {+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ stdio.eprint("vn: cannot load repository state\n", {})+ return 1+ }+ }+ view.free_view(tx.view)+ tx.view = new_view+ val status: i32 = txn.finish(tx, description)+ return status+}++pub fn restore(repo: layout.Repo, text: bytes.Bytes) i32 = trust {+ 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)+ val target = resolve_op(recs, text)+ val status: mut i32 = 1+ if target is some tid {+ val rec_opt = find_rec(recs, tid)+ 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))+ } else {+ stdio.eprint("vn: cannot read operation view\n", {})+ }+ }+ } else {+ stdio.eprint("vn: unknown operation\n", {})+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}++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 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)+ val target = resolve_op(recs, text)+ val status: mut i32 = 1+ if target is some tid {+ val rec_opt = find_rec(recs, tid)+ if rec_opt is some rec {+ if @len(rec.op.parents) > 0 {+ val p = @get(rec.op.parents, 0)+ if p is some pid {+ val parent_opt = state.read_operation(st.handles, pid)+ 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))+ }+ operation.free_operation(parent)+ }+ }+ } else {+ val empty: ref view.View = state.empty_view()+ status = write_view(repo, empty, bytes.bytes(c"op revert", 9))+ }+ }+ } else {+ stdio.eprint("vn: unknown operation\n", {})+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}++pub fn undo(repo: layout.Repo) i32 = trust {+ val st: store.Store = store.open_all(repo)+ val heads: list[objid.Id] = state.heads(repo)+ if @len(heads) == 0 {+ stdio.eprint("vn: no operations to undo\n", {})+ store.close(st)+ return 1+ }+ val recs: mut list[ref OpRec] = collect(st.handles, heads)+ sort_recs(recs)+ val status: mut i32 = 1+ if @len(recs) > 0 {+ val latest = rec_at(recs, 0)+ val target_view: mut option[ref view.View] = none+ if @len(latest.op.parents) > 0 {+ val p = @get(latest.op.parents, 0)+ if p is some pid {+ val parent_opt = state.read_operation(st.handles, pid)+ if parent_opt is some parent {+ target_view = state.read_view(st.handles, parent.view)+ operation.free_operation(parent)+ }+ }+ } else {+ target_view = some(state.empty_view())+ }+ match target_view {+ some tv => {+ status = write_view(repo, tv, bytes.bytes(c"undo", 4))+ }+ none => {+ stdio.eprint("vn: cannot resolve undo target\n", {})+ }+ }+ }+ free_recs(recs)+ free_ids(heads)+ store.close(st)+ return status+}--- /dev/null+++ b/src/src/cli/status_cmd.sx@@ -0,0 +1,128 @@+/// `vn status`: show working-copy changes relative to the parent commit.++val stdio = use("std/stdio")+val str = use("std/string")+val objid = use("../object/id.sx")+val tree = use("../object/tree.sx")+val graph = use("../object/graph.sx")+val treediff = use("../object/treediff.sx")+val treewalk = use("../object/treewalk.sx")+val view = use("../object/view.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")++fn first_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+ match lc_opt {+ 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(graph.copy_id(parent.c.root_tree))+ graph.free_loaded(parent)+ }+ }+ }+ graph.free_loaded(lc)+ }+ none => {+ }+ }+ return out+}++fn working_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+ match lc_opt {+ some lc => {+ out = some(graph.copy_id(lc.c.root_tree))+ graph.free_loaded(lc)+ }+ none => {+ }+ }+ return out+}++pub fn run(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 v_opt = state.current_view(repo, st.handles)+ val v: mut ref view = none+ match v_opt {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ stdio.eprint("vn: no operation state\n", {})+ return 1+ }+ }+ val wc_opt = viewops.working_copy(v)+ val wc: mut objid.Id = objid.id_none()+ match wc_opt {+ some id => {+ wc = id+ }+ none => {+ stdio.puts("working copy clean")+ view.free_view(v)+ store.close(st)+ return 0+ }+ }+ val new_tree_opt = working_tree(st.handles, wc)+ val old_tree_opt = first_parent_tree(st.handles, wc)+ val changes = treediff.compare(st.handles, old_tree_opt, new_tree_opt)+ val conflicted_count: mut usize = 0+ for c in changes {+ val path_view = str.view(c.path.ptr, c.path.len as i64)+ if c.old_kind == treewalk.KIND_MISSING {+ stdio.print("A {s}\n", {path_view})+ } elif c.new_kind == treewalk.KIND_MISSING {+ stdio.print("D {s}\n", {path_view})+ } elif c.new_kind == tree.KIND_CONFLICT {+ stdio.print("C {s}\n", {path_view})+ conflicted_count+++ } else {+ stdio.print("M {s}\n", {path_view})+ }+ }+ if @len(changes) == 0 {+ stdio.puts("working copy clean")+ }+ if conflicted_count > 0 {+ stdio.print("{d} conflict(s)\n", {conflicted_count})+ }+ treediff.free(changes)+ view.free_view(v)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ if new_tree_opt is some nt {+ if nt.ptr != none {+ val np: mut ref void = nt.ptr as ref void+ @free(np)+ }+ }+ if old_tree_opt is some ot {+ if ot.ptr != none {+ val op: mut ref void = ot.ptr as ref void+ @free(op)+ }+ }+ store.close(st)+ return 0+}--- /dev/null+++ b/src/src/core/datetime.sx@@ -0,0 +1,83 @@+/// UTC timestamp formatting for log and operation output.++val bytes = use("bytes.sx")+val buf = use("buf.sx")++fn floor_div(a: i64, b: i64) i64 = trust {+ val q: i64 = a / b+ val r: i64 = a % b+ if r != 0 && ((r < 0) != (b < 0)) {+ return q - 1+ }+ return q+}++fn put_pad(b: mut buf.Buf, value: i64, width: usize) void = trust {+ val v: mut i64 = value+ if v < 0 {+ v = 0+ }+ val tmp: ref u8 = @alloc(24) as ref u8+ val n: mut usize = 0+ for v > 0 {+ @store8(@ptradd(tmp, n as i64), (48 + (v % 10)) as u8)+ v = v / 10+ n+++ }+ if n == 0 {+ @store8(@ptradd(tmp, 0), 48)+ n = 1+ }+ val pad: usize = width - n+ val i: mut usize = 0+ for i < pad {+ buf.Buf.put_u8(b, 48)+ i+++ }+ val j: mut usize = n+ for j > 0 {+ j--+ buf.Buf.put_u8(b, @load8(@ptradd(tmp, j as i64)))+ }+ @free(tmp as ref void)+}++pub fn format_utc(seconds: i64) bytes.Bytes = trust {+ val days: i64 = floor_div(seconds, 86400)+ val rem: i64 = seconds - days * 86400+ val hour: i64 = rem / 3600+ val minute: i64 = (rem % 3600) / 60+ val second: i64 = rem % 60+ val z: i64 = days + 719468+ val era: i64 = floor_div(z, 146097)+ val doe: i64 = z - era * 146097+ val yoe: i64 = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365+ val y0: i64 = yoe + era * 400+ val doy: i64 = doe - (365 * yoe + yoe / 4 - yoe / 100)+ val mp: i64 = (5 * doy + 2) / 153+ val d: i64 = doy - (153 * mp + 2) / 5 + 1+ val m0: i64 = mp + 3+ val m: mut i64 = m0+ if mp >= 10 {+ m = mp - 9+ }+ val y: mut i64 = y0+ if m <= 2 {+ y = y + 1+ }+ val b: mut buf.Buf = buf.new(32)+ put_pad(b, y, 4)+ buf.Buf.put_u8(b, 45)+ put_pad(b, m, 2)+ buf.Buf.put_u8(b, 45)+ put_pad(b, d, 2)+ buf.Buf.put_u8(b, 32)+ put_pad(b, hour, 2)+ buf.Buf.put_u8(b, 58)+ put_pad(b, minute, 2)+ buf.Buf.put_u8(b, 58)+ put_pad(b, second, 2)+ val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+ buf.Buf.free(b)+ return out+}--- /dev/null+++ b/src/src/core/identity.sx@@ -0,0 +1,148 @@+/// Author/committer identity from the local config or environment.++val str = use("std/string")+val os = use("std/os")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val prim = use("../core/primitives.sx")+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 config_value(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)+ match data_opt {+ some data => {+ 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 {+ if 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 = trim(+ 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)+ }+ none => {+ }+ }+ return none+}++fn env_dup(name: ref u8) option[bytes.Bytes] = trust {+ val v = os.env(name)+ match v {+ some s => {+ return some bytes.Bytes.dup(bytes.from_cstr(s))+ }+ none => {+ return none+ }+ }+}++fn first_config(repo: layout.Repo, key: bytes.Bytes, env1: ref u8, env2: ref u8) bytes.Bytes = trust {+ val c = config_value(repo, key)+ match c {+ some v => {+ return v+ }+ none => {+ }+ }+ val e1 = env_dup(env1)+ match e1 {+ some v => {+ return v+ }+ none => {+ }+ }+ val e2 = env_dup(env2)+ match e2 {+ some v => {+ return v+ }+ none => {+ }+ }+ return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))+}++pub fn signature(repo: layout.Repo) prim.Sig = trust {+ val name: bytes.Bytes = first_config(+ repo,+ bytes.bytes(c"user.name", 9),+ c"GIT_AUTHOR_NAME",+ c"USER"+ )+ val email: bytes.Bytes = first_config(+ repo,+ bytes.bytes(c"user.email", 10),+ c"GIT_AUTHOR_EMAIL",+ c"EMAIL"+ )+ return prim.Sig{+ name: name,+ email: email,+ seconds: time.unix_now(),+ tz_min: 0+ }+}++pub fn free_sig(s: prim.Sig) void = trust {+ if s.name.ptr != none {+ val np: mut ref void = s.name.ptr as ref void+ @free(np)+ }+ if s.email.ptr != none {+ val ep: mut ref void = s.email.ptr as ref void+ @free(ep)+ }+}--- /dev/null+++ b/src/src/git/export.sx@@ -0,0 +1,1079 @@+/// Export vein commits into the bare git mirror.+///+/// Objects are written as loose git objects so export is incremental: only+/// commits missing from the ID map are visited, and each object is hashed+/// exactly once.++lib "z"++val str = use("std/string")+val stdio = use("std/stdio")+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 tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val view = use("../object/view.sx")+val graph = use("../object/graph.sx")+val treewalk = use("../object/treewalk.sx")+val content = use("../object/content.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")+val files = use("../io/files.sx")+val nativeio = use("../io/native.sx")+val object = use("object.sx")+val format = use("format.sx")+val oidmap = use("oidmap.sx")+val gitmap = use("map.sx")+val lazy = use("lazy.sx")++extern (C) fn compress2(+ dest: ref u8,+ dest_len: ref u64,+ source: ref u8,+ source_len: u64,+ level: i32+) i32 = "compress2"+extern (C) fn compressBound(source_len: u64) u64 = "compressBound"++type ExportCtx = {+ repo: mut layout.Repo+ handles: list[ref store.Handle]+ commits: mut oidmap.OidMap+ trees: mut oidmap.OidMap+ blobs: mut oidmap.OidMap+ native: mut list[objid.Id]+ git: mut object.GitRepo+ git_open: mut bool+ failed: mut bool+}++type Mark = {+ id: mut objid.Id+ expanded: mut bool+}++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 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 free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn reverse_lookup(map: oidmap.OidMap, id: objid.Id) option[bytes.Bytes] = trust {+ val i: mut usize = 0+ for i < map.cap {+ if oidmap.slot_used(map, i) {+ val value: bytes.Bytes = oidmap.slot_value(map, i)+ val same: bool = bytes.Bytes.eql(+ bytes.Bytes.slice(value, 0, 32),+ bytes.bytes(id.ptr, 32)+ )+ if same {+ return some(bytes.Bytes.dup(oidmap.slot_oid(map, i)))+ }+ }+ i+++ }+ return none+}++fn map_put(map: mut oidmap.OidMap, git_oid: bytes.Bytes, id: objid.Id) void = trust {+ oidmap.put(map, git_oid, bytes.bytes(id.ptr, 32))+}++fn hex_oid(oid: bytes.Bytes) ref u8 = trust {+ val out: ref u8 = @alloc(41) as ref u8+ objid.hex_encode(oid.ptr, 20, out)+ @store8(@ptradd(out, 40), 0)+ return out+}++fn object_path(repo: layout.Repo, oid: bytes.Bytes) str.StringView = trust {+ val hex: ref u8 = hex_oid(oid)+ val gitp: str.StringView = layout.git_dir(repo)+ val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))+ val dirname: str.StringView = str.view(hex, 2)+ val filename: str.StringView = str.view(@ptradd(hex, 2), 38)+ val dir: str.StringView = files.join(objects, dirname)+ val path: str.StringView = files.join(dir, filename)+ files.free_path(dir)+ files.free_path(objects)+ files.free_path(gitp)+ @free(hex as ref void)+ return path+}++fn put_decimal(b: mut buf.Buf, v: u64) void = trust {+ if v == 0 {+ buf.Buf.put_u8(b, 48)+ return+ }+ val tmp: ref u8 = @alloc(24) as ref u8+ val n: mut usize = 0+ val x: mut u64 = v+ for x > 0 {+ @store8(@ptradd(tmp, n as i64), (48 + (x % 10)) as u8)+ x = x / 10+ n+++ }+ val i: mut usize = n+ for i > 0 {+ i--+ buf.Buf.put_u8(b, @load8(@ptradd(tmp, i as i64)))+ }+ @free(tmp as ref void)+}++fn kind_name(kind: u8) bytes.Bytes = trust {+ if kind == object.KIND_COMMIT {+ return bytes.bytes(c"commit", 6)+ }+ if kind == object.KIND_TREE {+ return bytes.bytes(c"tree", 4)+ }+ if kind == object.KIND_BLOB {+ return bytes.bytes(c"blob", 4)+ }+ return bytes.bytes(c"tag", 3)+}++fn write_loose(+ ctx: ref ExportCtx,+ kind: u8,+ oid: bytes.Bytes,+ body: bytes.Bytes+) bool = trust {+ val final: str.StringView = object_path(ctx.repo, oid)+ if files.exists_file(final) {+ files.free_path(final)+ return true+ }+ val hex: ref u8 = hex_oid(oid)+ val gitp: str.StringView = layout.git_dir(ctx.repo)+ val objects: str.StringView = files.join(gitp, str.from_cstr(c"objects"))+ val dirname: str.StringView = str.view(hex, 2)+ val objdir: str.StringView = files.join(objects, dirname)+ if !files.exists_dir(objdir) {+ val _ = files.mkdir_all(objdir)+ }+ files.free_path(objdir)+ files.free_path(objects)+ files.free_path(gitp)+ @free(hex as ref void)++ val header: mut buf.Buf = buf.new(64)+ buf.Buf.put_bytes(header, kind_name(kind))+ buf.Buf.put_u8(header, 32)+ put_decimal(header, body.len as u64)+ buf.Buf.put_u8(header, 0)+ buf.Buf.put_bytes(header, body)++ val bound: u64 = compressBound(header.len as u64)+ val dst: ref u8 = @alloc(bound as usize) as ref u8+ val dst_len: mut u64 = bound+ val rc: i32 = compress2(+ dst,+ dst_len,+ header.ptr,+ header.len as u64,+ 6+ )+ buf.Buf.free(header)+ if rc != 0 {+ @free(dst as ref void)+ files.free_path(final)+ return false+ }+ val tmpd: str.StringView = layout.tmp_dir(ctx.repo)+ val tmpname: str.StringView = files.basename(final)+ val tmp: str.StringView = files.join(tmpd, tmpname)+ val parent: str.StringView = files.join(layout.git_dir(ctx.repo), str.from_cstr(c"objects"))+ val good: bool = nativeio.write_atomic(+ tmp,+ final,+ tmpd,+ parent,+ bytes.bytes(dst, dst_len as usize)+ )+ files.free_path(tmp)+ files.free_path(tmpd)+ files.free_path(parent)+ files.free_path(final)+ @free(dst as ref void)+ return good+}++fn export_blob(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {+ if lazy.is_lazy(id) {+ val oid: bytes.Bytes = bytes.Bytes.dup(lazy.git_oid(id))+ map_put(ctx.blobs, oid, id)+ return some oid+ }+ val existing = reverse_lookup(ctx.blobs, id)+ if existing is some oid {+ return some oid+ }+ val data_opt = content.read_blob(ctx.handles, id, ctx.git, ctx.git_open)+ val data: mut bytes.Bytes = bytes.empty()+ match data_opt {+ some d => {+ data = d+ }+ none => {+ ctx.failed = true+ return none+ }+ }+ val hash = object.object_hash(object.KIND_BLOB, data)+ val oid: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid = h+ }+ none => {+ ctx.failed = true+ files.free_buffer(data)+ return none+ }+ }+ val wrote: bool = write_loose(ctx, object.KIND_BLOB, oid, data)+ files.free_buffer(data)+ if !wrote {+ ctx.failed = true+ object.free_digest(oid)+ return none+ }+ map_put(ctx.blobs, oid, id)+ return some oid+}++fn entry_key(e: ref tree.TreeEntry) bytes.Bytes = trust {+ // Git compares tree names as if directory names ended in '/'.+ if e.kind == tree.KIND_SUBTREE {+ val out: ref u8 = @alloc(e.name.len + 1) as ref u8+ @memcpy(out as ref void, e.name.ptr as ref void, e.name.len)+ @store8(@ptradd(out, e.name.len as i64), 47)+ return bytes.bytes(out, e.name.len + 1)+ }+ return e.name+}++fn sort_git_entries(entries: mut list[ref tree.TreeEntry]) void = trust {+ val i: mut usize = 1+ for i < @len(entries) {+ val cur = @get(entries, i)+ val c: mut ref tree.TreeEntry = none+ if cur is some v {+ c = v+ }+ val j: mut usize = i+ for j > 0 {+ val prev_o = @get(entries, j - 1)+ val prev: mut ref tree.TreeEntry = none+ if prev_o is some p {+ prev = p+ }+ val ck: bytes.Bytes = entry_key(c)+ val pk: bytes.Bytes = entry_key(prev)+ val cmp: i64 = bytes.Bytes.cmp(pk, ck)+ if pk.len > prev.name.len {+ val pp: mut ref void = pk.ptr as ref void+ @free(pp)+ }+ if ck.len > c.name.len {+ val cp: mut ref void = ck.ptr as ref void+ @free(cp)+ }+ if cmp <= 0 {+ break+ }+ @set(entries, j, prev)+ j--+ }+ @set(entries, j, c)+ i+++ }+}++fn mode_for(kind: u8) bytes.Bytes = trust {+ if kind == tree.KIND_EXECUTABLE {+ return bytes.bytes(c"100755", 6)+ }+ if kind == tree.KIND_SYMLINK {+ return bytes.bytes(c"120000", 6)+ }+ if kind == tree.KIND_SUBTREE {+ return bytes.bytes(c"40000", 5)+ }+ if kind == tree.KIND_SUBMODULE {+ return bytes.bytes(c"160000", 6)+ }+ return bytes.bytes(c"100644", 6)+}++fn export_tree(ctx: mut ExportCtx, id: objid.Id) option[bytes.Bytes] = trust {+ if ctx.failed {+ return none+ }+ val existing = reverse_lookup(ctx.trees, id)+ if existing is some oid {+ return some oid+ }+ val raw_opt = gitmap.load_raw(ctx.repo, id)+ if raw_opt is some raw {+ val hash = object.object_hash(object.KIND_TREE, raw)+ val oid: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid = h+ }+ none => {+ files.free_buffer(raw)+ ctx.failed = true+ return none+ }+ }+ val wrote: bool = write_loose(ctx, object.KIND_TREE, oid, raw)+ files.free_buffer(raw)+ if !wrote {+ ctx.failed = true+ object.free_digest(oid)+ return none+ }+ map_put(ctx.trees, oid, id)+ return some oid+ }+ val t_opt = treewalk.read_tree(ctx.handles, id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ ctx.failed = true+ return none+ }+ }+ 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+ if e.kind == tree.KIND_SUBTREE {+ child = export_tree(ctx, e.target)+ } elif e.kind == tree.KIND_SUBMODULE {+ val oid20: bytes.Bytes = bytes.Bytes.dup(bytes.Bytes.slice(bytes.bytes(e.target.ptr, 32), 0, 20))+ child = some(oid20)+ } elif e.kind == tree.KIND_CONFLICT {+ ctx.failed = true+ good = false+ } else {+ child = export_blob(ctx, e.target)+ }+ if child is some co {+ @append(+ entries,+ tree.entry(bytes.Bytes.dup(e.name), e.kind, objid.id(co.ptr))+ )+ @append(child_oids, co)+ } else {+ good = false+ }+ if !good {+ break+ }+ }+ tree.free_tree(t)+ if !good {+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(entries)+ for o in child_oids {+ object.free_digest(o)+ }+ @listfree(child_oids)+ return none+ }+ sort_git_entries(entries)+ val body: mut buf.Buf = buf.new(@len(entries) * 32 + 8)+ val i: mut usize = 0+ for i < @len(entries) {+ val o = @get(entries, i)+ if o is some e {+ buf.Buf.put_bytes(body, mode_for(e.kind))+ buf.Buf.put_u8(body, 32)+ buf.Buf.put_bytes(body, e.name)+ buf.Buf.put_u8(body, 0)+ buf.Buf.put_bytes(body, bytes.bytes(e.target.ptr, 20))+ }+ i+++ }+ val hash = object.object_hash(object.KIND_TREE, buf.Buf.view(body))+ val oid_out: mut bytes.Bytes = bytes.empty()+ match hash {+ some h => {+ oid_out = h+ }+ none => {+ good = false+ }+ }+ if good {+ good = write_loose(ctx, object.KIND_TREE, oid_out, buf.Buf.view(body))+ if good {+ map_put(ctx.trees, oid_out, id)+ }+ }+ buf.Buf.free(body)+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @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 {+ object.free_digest(oid_out)+ }+ return none+ }+ return some oid_out+}++fn parent_oids(ctx: mut ExportCtx, c: ref commit.Commit) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for p in c.parents {+ val g = reverse_lookup(ctx.commits, p)+ match g {+ some oid => {+ @append(out, oid)+ }+ none => {+ ctx.failed = true+ }+ }+ }+ return out+}++fn serialize_commit(+ ctx: ref ExportCtx,+ id: objid.Id,+ c: ref commit.Commit,+ tree_oid: bytes.Bytes,+ parents: list[bytes.Bytes],+ is_native: bool+) option[bytes.Bytes] = trust {+ val raw_opt = gitmap.load_raw(ctx.repo, id)+ if raw_opt is some raw {+ val parsed_opt = format.parse_commit(raw)+ val use_raw: mut bool = false+ if parsed_opt is some parsed {+ if bytes.Bytes.eql(parsed.tree, tree_oid) && @len(parsed.parents) == @len(parents) {+ use_raw = true+ val pi: mut usize = 0+ for pi < @len(parents) {+ val po = @get(parsed.parents, pi)+ if po is some poid {+ if !bytes.Bytes.eql(poid, parents_at(parents, pi)) {+ use_raw = false+ break+ }+ }+ pi+++ }+ }+ format.free_parsed_commit(parsed)+ }+ if use_raw {+ return some raw+ }+ files.free_buffer(raw)+ }++ val extras: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ for kv in c.extra {+ @append(extras, commit.new_kv(bytes.Bytes.dup(kv.key), bytes.Bytes.dup(kv.value)))+ }+ if is_native {+ val hex: ref u8 = objid.ChangeId.hex(c.change_id)+ @append(+ extras,+ commit.new_kv(+ bytes.Bytes.dup(bytes.bytes(c"vein-change-id", 14)),+ bytes.Bytes.dup(bytes.bytes(hex, 32))+ )+ )+ @free(hex as ref void)+ }+ val pc: mut ref format.ParsedCommit = @alloc(@sizeof(format.ParsedCommit)) as ref format.ParsedCommit+ pc.tree = tree_oid+ pc.parents = lists.new[bytes.Bytes]()+ for p in parents {+ @append(pc.parents, bytes.Bytes.dup(p))+ }+ pc.author = c.author+ pc.committer = c.committer+ pc.message = c.message+ pc.extras = extras+ pc.change_id = bytes.empty()+ pc.canonical = true+ val body: bytes.Bytes = format.serialize_commit(pc)+ // ParsedCommit owns parents/extras here, not the borrowed commit fields.+ for p in pc.parents {+ if p.ptr != none {+ val pp: mut ref void = p.ptr as ref void+ @free(pp)+ }+ }+ @listfree(pc.parents)+ for kv in extras {+ if kv.key.ptr != none {+ val kp: mut ref void = kv.key.ptr as ref void+ @free(kp)+ }+ if kv.value.ptr != none {+ val vp: mut ref void = kv.value.ptr as ref void+ @free(vp)+ }+ val xp: mut ref void = kv as ref void+ @free(xp)+ }+ @listfree(extras)+ @free(pc as ref void)+ return some body+}++fn parents_at(xs: list[bytes.Bytes], i: usize) bytes.Bytes = trust {+ val o = @get(xs, i)+ if o is some b {+ return b+ }+ return bytes.empty()+}++fn export_commit(ctx: mut ExportCtx, id: objid.Id) bool = trust {+ if ctx.failed {+ return false+ }+ val existing = reverse_lookup(ctx.commits, id)+ if existing is some _ {+ return true+ }+ val lc_opt = graph.load_commit(ctx.handles, id)+ val lc: mut ref graph.LoadedCommit = none+ match lc_opt {+ some x => {+ lc = x+ }+ none => {+ ctx.failed = true+ return false+ }+ }+ val tree_opt = export_tree(ctx, lc.c.root_tree)+ val tree_oid: mut bytes.Bytes = bytes.empty()+ match tree_opt {+ some t => {+ tree_oid = t+ }+ none => {+ graph.free_loaded(lc)+ return false+ }+ }+ val parents: list[bytes.Bytes] = parent_oids(ctx, lc.c)+ val is_native: bool = gitmap.is_native(ctx.native, id)+ val body_opt = serialize_commit(ctx, id, lc.c, tree_oid, parents, is_native)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ ctx.failed = true+ }+ }+ val status: mut bool = !ctx.failed+ val oid_out: mut bytes.Bytes = bytes.empty()+ if status {+ val hash = object.object_hash(object.KIND_COMMIT, body)+ match hash {+ some h => {+ oid_out = h+ }+ none => {+ status = false+ }+ }+ }+ if status {+ status = write_loose(ctx, object.KIND_COMMIT, oid_out, body)+ if status {+ map_put(ctx.commits, oid_out, id)+ }+ }+ if body.ptr != none {+ files.free_buffer(body)+ }+ if tree_oid.ptr != none {+ object.free_digest(tree_oid)+ }+ for p in parents {+ object.free_digest(p)+ }+ @listfree(parents)+ if oid_out.ptr != none {+ object.free_digest(oid_out)+ }+ graph.free_loaded(lc)+ if !status {+ ctx.failed = true+ }+ return status+}++fn ordered_commits(+ handles: list[ref store.Handle],+ roots: list[objid.Id]+) list[objid.Id] = trust {+ val all_ids: list[objid.Id] = graph.collect(handles, roots)+ val visited: mut list[objid.Id] = lists.new[objid.Id]()+ val ordered: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[ref Mark] = lists.new[ref Mark]()+ val i0: mut usize = 0+ for i0 < @len(all_ids) {+ val o = @get(all_ids, i0)+ if o is some id {+ val m: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark+ m.id = id+ m.expanded = false+ @append(stack, m)+ }+ i0+++ }+ for @len(stack) > 0 {+ val m: mut ref Mark = @remove(stack, @len(stack) - 1)+ if contains(visited, m.id) {+ @free(m as ref void)+ continue+ }+ if !m.expanded {+ m.expanded = true+ @append(stack, m)+ val lc_opt = graph.load_commit(handles, m.id)+ match lc_opt {+ some lc => {+ val pi: mut usize = @len(lc.c.parents)+ for pi > 0 {+ pi--+ val p = @get(lc.c.parents, pi)+ if p is some pid {+ if !contains(visited, pid) {+ val pm: mut ref Mark = @alloc(@sizeof(Mark)) as ref Mark+ pm.id = copy_id(pid)+ pm.expanded = false+ @append(stack, pm)+ }+ }+ }+ graph.free_loaded(lc)+ }+ none => {+ }+ }+ } else {+ @append(visited, copy_id(m.id))+ @append(ordered, copy_id(m.id))+ @free(m as ref void)+ }+ }+ @listfree(stack)+ free_ids(visited)+ free_ids(all_ids)+ return ordered+}++fn exportable_target(handles: list[ref store.Handle], id: objid.Id) option[objid.Id] = trust {+ val current: mut objid.Id = copy_id(id)+ val steps: mut usize = 0+ for steps < 100000 {+ val lc_opt = graph.load_commit(handles, current)+ if lc_opt is none {+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ return none+ }+ val lc: mut ref graph.LoadedCommit = none+ match lc_opt {+ some x => {+ lc = x+ }+ none => {+ }+ }+ val conflicted: bool = treewalk.conflicted(handles, lc.c.root_tree)+ if !conflicted {+ val out: objid.Id = copy_id(current)+ graph.free_loaded(lc)+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ return some out+ }+ val next: mut option[objid.Id] = none+ if @len(lc.c.parents) > 0 {+ val p = @get(lc.c.parents, 0)+ if p is some pid {+ next = some(copy_id(pid))+ }+ }+ graph.free_loaded(lc)+ if current.ptr != none {+ @free(current.ptr as ref void)+ }+ match next {+ some nid => {+ current = nid+ }+ none => {+ return none+ }+ }+ steps+++ }+ return none+}++fn write_ref(ctx: ref ExportCtx, ref_name: bytes.Bytes, oid: bytes.Bytes) bool = trust {+ val gitp: str.StringView = layout.git_dir(ctx.repo)+ val refstr: str.StringView = files.to_view(ref_name)+ val final: str.StringView = files.join(gitp, refstr)+ val dir0: str.StringView = files.join(gitp, str.from_cstr(c"refs"))+ val dir: mut str.StringView = dir0+ val slash: mut i64 = -1+ val i: mut usize = 0+ for i < final.len {+ if @load8(@ptradd(final.ptr, i as i64)) == 47 {+ slash = i as i64+ }+ i+++ }+ if slash > 0 {+ dir = str.view(final.ptr, slash as usize)+ if !files.exists_dir(dir) {+ val _ = files.mkdir_all(dir)+ }+ }+ val hex: ref u8 = hex_oid(oid)+ val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})+ val tmpd: str.StringView = layout.tmp_dir(ctx.repo)+ val tmpname: ref u8 = @fmtalloc("{s}.tmp", {str.from_cstr(hex)})+ val tmp_name_view: str.StringView = str.from_cstr(tmpname)+ val tmp: str.StringView = files.join(tmpd, tmp_name_view)+ val good: bool = nativeio.write_atomic(tmp, final, tmpd, dir, bytes.from_cstr(line))+ files.free_path(tmp)+ files.free_path(tmp_name_view)+ files.free_path(tmpd)+ files.free_path(dir0)+ files.free_path(final)+ files.free_path(gitp)+ @free(hex as ref void)+ @free(line as ref void)+ return good+}++pub fn run(repo: layout.Repo) i32 = trust {+ val gitp: str.StringView = layout.git_dir(repo)+ if !files.exists_dir(gitp) {+ stdio.eprint("vn: no git mirror; run `vn git import` first\n", {})+ files.free_path(gitp)+ return 1+ }+ val git_opt = object.open(gitp)+ files.free_path(gitp)+ val git_repo: mut object.GitRepo = @zeroed+ val git_open: mut bool = false+ match git_opt {+ ok g => {+ git_repo = g+ git_open = true+ }+ err _ => {+ }+ }++ val commits_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))+ val trees_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))+ val blobs_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))+ val commits: mut oidmap.OidMap = oidmap.new(64)+ val trees: mut oidmap.OidMap = oidmap.new(64)+ val blobs: mut oidmap.OidMap = oidmap.new(64)+ match commits_opt {+ ok m => {+ commits = m+ }+ err _ => {+ }+ }+ match trees_opt {+ ok m => {+ trees = m+ }+ err _ => {+ }+ }+ match blobs_opt {+ ok m => {+ blobs = m+ }+ err _ => {+ }+ }+ val native_ids: list[objid.Id] = gitmap.load_native(repo)+ val st: store.Store = store.open_all(repo)+ val ctx: mut ExportCtx = ExportCtx{+ repo: repo,+ handles: st.handles,+ commits: commits,+ trees: trees,+ blobs: blobs,+ native: native_ids,+ git: git_repo,+ git_open: git_open,+ failed: false+ }+ 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)+ oidmap.free(commits)+ oidmap.free(trees)+ oidmap.free(blobs)+ free_ids(native_ids)+ stdio.eprint("vn: no operation state\n", {})+ return 1+ }+ }+ val roots: mut list[objid.Id] = lists.new[objid.Id]()+ val resolved_bookmarks: mut list[ref view.Bookmark] = lists.new[ref view.Bookmark]()+ val mut_skipped: mut usize = 0+ for bm in v.bookmarks {+ val target = first_target(bm.targets.adds)+ if target is some tid {+ val exp = exportable_target(st.handles, tid)+ match exp {+ some x => {+ if !contains(roots, x) {+ @append(roots, copy_id(x))+ }+ val nb: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ nb.name = bytes.Bytes.dup(bm.name)+ nb.targets = view.empty_target_set()+ @append(nb.targets.adds, copy_id(x))+ @append(resolved_bookmarks, nb)+ if x.ptr != none {+ @free(x.ptr as ref void)+ }+ }+ none => {+ mut_skipped+++ }+ }+ }+ }+ val resolved_tags: mut list[ref view.TagRef] = lists.new[ref view.TagRef]()+ for t in v.tags {+ val exp = exportable_target(st.handles, t.target)+ match exp {+ some x => {+ if !contains(roots, x) {+ @append(roots, copy_id(x))+ }+ val nt: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+ nt.name = bytes.Bytes.dup(t.name)+ nt.target = copy_id(x)+ @append(resolved_tags, nt)+ if x.ptr != none {+ @free(x.ptr as ref void)+ }+ }+ none => {+ mut_skipped+++ }+ }+ }+ val ordered: list[objid.Id] = ordered_commits(st.handles, roots)+ val exported: mut usize = 0+ for id in ordered {+ val had = reverse_lookup(commits, id)+ if had is none {+ if export_commit(ctx, id) {+ exported+++ }+ } else {+ if had is some oid {+ object.free_digest(oid)+ }+ }+ if ctx.failed {+ break+ }+ }+ val status: mut i32 = 0+ if ctx.failed {+ stdio.eprint("vn: git export failed\n", {})+ status = 1+ } else {+ for bm in resolved_bookmarks {+ val target = first_target(bm.targets.adds)+ if target is some tid {+ val g = reverse_lookup(commits, tid)+ if g is some oid {+ val full: ref u8 = @alloc(11 + bm.name.len + 1) as ref u8+ @memcpy(full as ref void, c"refs/heads/", 11)+ @memcpy(@ptradd(full, 11) as ref void, bm.name.ptr as ref void, bm.name.len)+ @store8(@ptradd(full, (11 + bm.name.len) as i64), 0)+ val full_b: bytes.Bytes = bytes.from_cstr(full)+ if !write_ref(ctx, full_b, oid) {+ status = 1+ }+ @free(full as ref void)+ object.free_digest(oid)+ }+ }+ }+ for t in resolved_tags {+ val g = reverse_lookup(commits, t.target)+ if g is some oid {+ val full: ref u8 = @alloc(10 + t.name.len + 1) as ref u8+ @memcpy(full as ref void, c"refs/tags/", 10)+ @memcpy(@ptradd(full, 10) as ref void, t.name.ptr as ref void, t.name.len)+ @store8(@ptradd(full, (10 + t.name.len) as i64), 0)+ val full_b: bytes.Bytes = bytes.from_cstr(full)+ if !write_ref(ctx, full_b, oid) {+ status = 1+ }+ @free(full as ref void)+ object.free_digest(oid)+ }+ }+ if mut_skipped > 0 {+ stdio.eprint("vn: skipped {d} conflicted ref(s)\n", {mut_skipped})+ }+ }+ 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)+ if !sc || !stree || !sblob {+ stdio.eprint("vn: failed to write git mapping tables\n", {})+ status = 1+ }+ }+ stdio.eprint("vn: exported {d} commits\n", {exported})+ view.free_view(v)+ free_ids(roots)+ free_ids(ordered)+ for bm in resolved_bookmarks {+ if bm.name.ptr != none {+ val np: mut ref void = bm.name.ptr as ref void+ @free(np)+ }+ for x in bm.targets.adds {+ if x.ptr != none {+ val xp: mut ref void = x.ptr as ref void+ @free(xp)+ }+ }+ for x in bm.targets.removes {+ if x.ptr != none {+ val xp2: mut ref void = x.ptr as ref void+ @free(xp2)+ }+ }+ @listfree(bm.targets.adds)+ @listfree(bm.targets.removes)+ val bp: mut ref void = bm as ref void+ @free(bp)+ }+ @listfree(resolved_bookmarks)+ for t in resolved_tags {+ if t.name.ptr != none {+ val np: mut ref void = t.name.ptr as ref void+ @free(np)+ }+ if t.target.ptr != none {+ val tp: mut ref void = t.target.ptr as ref void+ @free(tp)+ }+ val xp: mut ref void = t as ref void+ @free(xp)+ }+ @listfree(resolved_tags)+ free_ids(native_ids)+ store.close(st)+ oidmap.free(commits)+ oidmap.free(trees)+ oidmap.free(blobs)+ if git_open {+ object.free(git_repo)+ }+ return status+}++fn first_target(adds: list[objid.Id]) option[objid.Id] = trust {+ if @len(adds) > 0 {+ return @get(adds, 0)+ }+ return none+}--- a/src/src/git/map.sx+++ b/src/src/git/map.sx@@ -2,6 +2,7 @@ val str = use("std/string") val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx") val buf = use("../core/buf.sx") val objid = use("../object/id.sx") val layout = use("../store/layout.sx")@@ -146,4 +147,65 @@ files.free_path(path) @free(hex as ref void) return data+}++fn native_path(repo: layout.Repo) str.StringView = {+ val base: str.StringView = layout.git_map_dir(repo)+ val p: str.StringView = files.join(base, str.from_cstr(c"native"))+ files.free_path(base)+ return p+}++/// Remember that a commit was created natively so the exporter knows whether+/// to add the `vein-change-id` header.+pub fn mark_native(repo: layout.Repo, id: objid.Id) bool = trust {+ val hex: ref u8 = objid.Id.hex(id)+ val line: ref u8 = @fmtalloc("{s}\n", {str.from_cstr(hex)})+ val p: str.StringView = native_path(repo)+ val appended: bool = files.append_all(p, bytes.from_cstr(line))+ files.free_path(p)+ @free(hex as ref void)+ @free(line as ref void)+ return appended+}++pub fn load_native(repo: layout.Repo) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val p: str.StringView = native_path(repo)+ val data_opt = files.read_all(p)+ files.free_path(p)+ match data_opt {+ some data => {+ val start: mut usize = 0+ val i: mut usize = 0+ for i <= data.len {+ if i == data.len || bytes.Bytes.at(data, i) == 10 {+ val line: bytes.Bytes = bytes.Bytes.slice(data, start, i)+ if line.len >= 64 {+ val raw: ref u8 = @alloc(32) as ref u8+ if objid.hex_decode(line.ptr, 32, raw) {+ @append(out, objid.id(raw))+ } else {+ @free(raw as ref void)+ }+ }+ start = i + 1+ }+ i+++ }+ files.free_buffer(data)+ }+ none => {+ }+ }+ return out+}++pub fn is_native(native: list[objid.Id], id: objid.Id) bool = {+ for x in native {+ if objid.Id.eql(x, id) {+ return true+ }+ }+ return false }--- /dev/null+++ b/src/src/io/stat.sx@@ -0,0 +1,120 @@+/// Minimal `lstat`/`readlink` helpers used by working-copy snapshots.+///+/// The C `struct stat` layout differs by platform, so only the fields the+/// snapshot code needs are read, from the offsets used by the hosted runtimes+/// vein targets.++val str = use("std/string")+val allocators = use("std/allocators")+val bytes = use("../core/bytes.sx")++extern (C) fn lstat(path: ref u8, buf: ref void) i32 = "lstat"+extern (C) fn readlink(path: ref u8, buf: ref u8, n: usize) i64 = "readlink"++pub val KIND_MISSING: u8 = 0+pub val KIND_FILE: u8 = 1+pub val KIND_DIR: u8 = 2+pub val KIND_LINK: u8 = 3++pub type StatInfo = {+ kind: mut u8+ executable: mut bool+ size: mut u64+ mtime_ns: mut u64+ inode: mut u64+}++fn heap() allocators.HeapAllocator = trust {+ return @zeroed+}++fn zstr(p: str.StringView) str.ZString = trust {+ return str.zstr_from[allocators.HeapAllocator](heap(), p)+}++fn free_z(z: str.ZString) void = trust {+ str.zstr_free[allocators.HeapAllocator](heap(), z)+}++fn kind_from_mode(mode: u32) u8 = trust {+ val masked: u32 = mode & 61440+ if masked == 16384 {+ return KIND_DIR+ }+ if masked == 32768 {+ return KIND_FILE+ }+ if masked == 40960 {+ return KIND_LINK+ }+ return KIND_MISSING+}++pub fn read(path: str.StringView) option[StatInfo] = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return none+ }+ val buf: ref u8 = @alloc(320) as ref u8+ @memset(buf as ref void, 0, 320)+ val rc: i32 = lstat(z.ptr, buf as ref void)+ free_z(z)+ if rc != 0 {+ @free(buf as ref void)+ return none+ }+ val info: mut StatInfo = StatInfo{+ kind: KIND_MISSING,+ executable: false,+ size: 0,+ mtime_ns: 0,+ inode: 0+ }+ when linux {+ val mode: u32 = @load32(@ptradd(buf, 24) as ref void) as u32+ info.kind = kind_from_mode(mode)+ info.executable = (mode & 73) != 0+ info.inode = @load64(@ptradd(buf, 8) as ref void) as u64+ info.size = @load64(@ptradd(buf, 48) as ref void) as u64+ val sec: u64 = @load64(@ptradd(buf, 88) as ref void) as u64+ val nsec: u64 = @load64(@ptradd(buf, 96) as ref void) as u64+ info.mtime_ns = sec * 1000000000 + nsec+ }+ or when darwin {+ val mode2: u32 = @load16(@ptradd(buf, 4) as ref void) as u32+ info.kind = kind_from_mode(mode2)+ info.executable = (mode2 & 73) != 0+ info.inode = @load64(@ptradd(buf, 8) as ref void) as u64+ info.size = @load64(@ptradd(buf, 96) as ref void) as u64+ val sec2: u64 = @load64(@ptradd(buf, 48) as ref void) as u64+ val nsec2: u64 = @load64(@ptradd(buf, 56) as ref void) as u64+ info.mtime_ns = sec2 * 1000000000 + nsec2+ }+ otherwise {+ info.kind = KIND_FILE+ info.executable = false+ info.inode = 0+ val sz = trust @load64(@ptradd(buf, 48) as ref void) as u64+ info.size = sz+ info.mtime_ns = 0+ }+ @free(buf as ref void)+ return some info+}++/// Read a symlink target. The result is owned by the caller.+pub fn link_target(path: str.StringView) option[bytes.Bytes] = trust {+ val z: str.ZString = zstr(path)+ if z.ptr == none {+ return none+ }+ val cap: usize = 65537+ val buf: ref u8 = @alloc(cap) as ref u8+ val n: i64 = readlink(z.ptr, buf, cap - 1)+ free_z(z)+ if n < 0 {+ @free(buf as ref void)+ return none+ }+ return some bytes.bytes(buf, n as usize)+}--- a/src/src/main.sx+++ b/src/src/main.sx@@ -11,6 +11,13 @@ val checkout_cmd = use("cli/checkout_cmd.sx") val help_cmd = use("cli/help_cmd.sx") 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 diff_cmd = use("cli/diff_cmd.sx")+val new_cmd = use("cli/new_cmd.sx")+val op_cmd = use("cli/op_cmd.sx")+val lists = use("core/lists.sx")+val layout = use("store/layout.sx") fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = { if a == none {@@ -65,6 +72,253 @@ i++ } return fsck_cmd.run(mut_path, verbose)+}+++fn open_repo_or_error(path: str.StringView) option[layout.Repo] = trust {+ val repo_opt = layout.discover(path)+ match repo_opt {+ some repo => {+ return some repo+ }+ none => {+ stdio.eprint("vn: not a vein repository\n", {})+ return none+ }+ }+}++fn run_status() i32 = trust {+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = status_cmd.run(repo)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_log(args: list[ref u8], start: usize) i32 = trust {+ val rev: mut bytes.Bytes = bytes.empty()+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if cmd_is(a, c"-r", 2) || cmd_is(a, c"--rev", 5) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ rev = bytes.from_cstr(rv)+ i+++ }+ }+ } elif !cmd_is(a, c"--", 2) {+ 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 = log_cmd.run(repo, rev)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_diff(args: list[ref u8], start: usize) i32 = trust {+ val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if cmd_is(a, c"-r", 2) || cmd_is(a, c"--rev", 5) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ @append(revs, bytes.from_cstr(rv))+ i+++ }+ }+ } elif !cmd_is(a, c"--", 2) {+ @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 = diff_cmd.run(repo, revs)+ layout.free_repo(repo)+ @listfree(revs)+ return status+ }+ none => {+ @listfree(revs)+ return 1+ }+ }+}++fn run_new(args: list[ref u8], start: usize) i32 = trust {+ val revs: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if !cmd_is(a, c"--", 2) {+ @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 = new_cmd.new_change(repo, revs)+ layout.free_repo(repo)+ @listfree(revs)+ return status+ }+ none => {+ @listfree(revs)+ return 1+ }+ }+}++fn parse_message(args: list[ref u8], start: usize) list[bytes.Bytes] = trust {+ val parts: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val i: mut usize = start+ for i < @len(args) {+ val o = @get(args, i)+ if o is some a {+ if cmd_is(a, c"-m", 2) || cmd_is(a, c"--message", 9) {+ if i + 1 < @len(args) {+ val v = @get(args, i + 1)+ if v is some rv {+ @append(parts, bytes.from_cstr(rv))+ i+++ }+ }+ } elif !cmd_is(a, c"--", 2) {+ @append(parts, bytes.from_cstr(a))+ }+ }+ i+++ }+ return parts+}++fn run_describe(args: list[ref u8], start: usize) i32 = trust {+ val parts = parse_message(args, start)+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = new_cmd.describe(repo, parts)+ layout.free_repo(repo)+ @listfree(parts)+ return status+ }+ none => {+ @listfree(parts)+ return 1+ }+ }+}++fn run_commit(args: list[ref u8], start: usize) i32 = trust {+ val parts = parse_message(args, start)+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val d: i32 = new_cmd.describe(repo, parts)+ @listfree(parts)+ if d != 0 {+ layout.free_repo(repo)+ return d+ }+ val empty: list[bytes.Bytes] = lists.new[bytes.Bytes]()+ val n: i32 = new_cmd.new_change(repo, empty)+ @listfree(empty)+ layout.free_repo(repo)+ return n+ }+ none => {+ @listfree(parts)+ return 1+ }+ }+}++fn run_undo() i32 = trust {+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ match repo_opt {+ some repo => {+ val status: i32 = op_cmd.undo(repo)+ layout.free_repo(repo)+ return status+ }+ none => {+ return 1+ }+ }+}++fn run_op(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 => {+ stdio.eprint("vn: expected an op subcommand (log, restore, revert)\n", {})+ return 1+ }+ }+ val repo_opt = open_repo_or_error(str.from_cstr(c"."))+ val repo: mut layout.Repo = layout.Repo{root: @zeroed}+ match repo_opt {+ some r => {+ repo = r+ }+ none => {+ return 1+ }+ }+ val status: mut i32 = 1+ if cmd_is(sub, c"log", 3) {+ status = op_cmd.log(repo)+ } elif cmd_is(sub, c"restore", 7) {+ val o = @get(args, start + 1)+ if o is some t {+ status = op_cmd.restore(repo, bytes.from_cstr(t))+ } else {+ stdio.eprint("vn: op restore requires an operation id\n", {})+ }+ } elif cmd_is(sub, c"revert", 6) {+ val o = @get(args, start + 1)+ if o is some t {+ status = op_cmd.revert(repo, bytes.from_cstr(t))+ } else {+ stdio.eprint("vn: op revert requires an operation id\n", {})+ }+ } else {+ stdio.eprint("vn: unknown op subcommand: {s}\n", {str.from_cstr(sub)})+ }+ layout.free_repo(repo)+ return status } pub fn main() i32 = trust {@@ -93,6 +347,30 @@ } if cmd_is(cmd, c"checkout", 8) { return checkout_cmd.run(args, 2)+ }+ if cmd_is(cmd, c"status", 6) {+ return run_status()+ }+ if cmd_is(cmd, c"log", 3) {+ return run_log(args, 2)+ }+ if cmd_is(cmd, c"diff", 4) {+ return run_diff(args, 2)+ }+ if cmd_is(cmd, c"new", 3) {+ return run_new(args, 2)+ }+ if cmd_is(cmd, c"describe", 8) {+ return run_describe(args, 2)+ }+ if cmd_is(cmd, c"commit", 6) {+ return run_commit(args, 2)+ }+ if cmd_is(cmd, c"undo", 4) {+ return run_undo()+ }+ if cmd_is(cmd, c"op", 2) {+ return run_op(args, 2) } if cmd_is(cmd, c"fsck", 4) { return run_fsck(args, 2)--- /dev/null+++ b/src/src/object/changeid.sx@@ -0,0 +1,69 @@+/// Lowercase RFC 4648 base32 rendering for change IDs.++val bytes = use("../core/bytes.sx")+val objid = use("../object/id.sx")++fn alphabet() bytes.Bytes = trust {+ return bytes.bytes(c"abcdefghijklmnopqrstuvwxyz234567", 32)+}++/// Full base32 encoding of a 16-byte change ID. No padding is added.+pub fn encode(cid: objid.ChangeId) bytes.Bytes = trust {+ val out: ref u8 = @alloc(32) as ref u8+ val alpha: bytes.Bytes = alphabet()+ val bufv: mut u64 = 0+ val bits: mut usize = 0+ val n: mut usize = 0+ val i: mut usize = 0+ for i < objid.CHANGE_ID_LEN {+ val c: u8 = @load8(@ptradd(cid.ptr, i as i64))+ bufv = (bufv << 8) | (c as u64)+ bits = bits + 8+ for bits >= 5 {+ val shift: usize = bits - 5+ val idx: usize = ((bufv >> shift) & 31) as usize+ @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx))+ n+++ bits = shift+ }+ if bits == 0 {+ bufv = 0+ } else {+ bufv = bufv & ((1 as u64 << bits) - 1)+ }+ i+++ }+ if bits > 0 {+ val idx2: usize = ((bufv << (5 - bits)) & 31) as usize+ @store8(@ptradd(out, n as i64), bytes.Bytes.at(alpha, idx2))+ n+++ }+ return bytes.bytes(out, n)+}++pub fn prefix_matches(full: bytes.Bytes, text: bytes.Bytes) bool = trust {+ if text.len == 0 || text.len > full.len {+ return false+ }+ val i: mut usize = 0+ for i < text.len {+ val a: u8 = bytes.Bytes.at(full, i)+ val c: u8 = bytes.Bytes.at(text, i)+ val lower: mut u8 = c+ if c >= 65 && c <= 90 {+ lower = (c + 32) as u8+ }+ if a != lower {+ return false+ }+ i+++ }+ return true+}++pub fn free(cid: bytes.Bytes) void = trust {+ if cid.ptr != none {+ val p: mut ref void = cid.ptr as ref void+ @free(p)+ }+}--- /dev/null+++ b/src/src/object/content.sx@@ -0,0 +1,113 @@+/// Materialize a blob into memory for diff and inspection commands.++val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val objid = use("../object/id.sx")+val types = use("../object/types.sx")+val blob = use("../object/blob.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")+val lazy = use("../git/lazy.sx")+val object = use("../git/object.sx")++fn append_blob(+ handles: list[ref store.Handle],+ out: mut buf.Buf,+ id: objid.Id,+ depth: usize,+ git: object.GitRepo,+ has_git: bool+) bool = trust {+ if depth > 64 {+ return false+ }+ if lazy.is_lazy(id) {+ if !has_git {+ return false+ }+ val read = object.read_fast(git, lazy.git_oid(id))+ match read {+ ok o => {+ val read_ok: mut bool = false+ if o.kind == object.KIND_BLOB {+ buf.Buf.put_bytes(out, o.body)+ read_ok = true+ }+ object.free_object(o)+ return read_ok+ }+ err _ => {+ return false+ }+ }+ }+ val body_opt = state.read_body(handles, id, types.BLOB)+ 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_INLINE {+ 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)+ match chunk_opt {+ some chunk => {+ buf.Buf.put_bytes(out, chunk)+ files.free_buffer(chunk)+ }+ none => {+ good = false+ }+ }+ if !good {+ break+ }+ }+ } else {+ for e in b.entries {+ if !append_blob(handles, out, e.id, depth + 1, git, has_git) {+ good = false+ break+ }+ }+ }+ blob.free_blob(b)+ files.free_buffer(body)+ return good+}++/// Read the full content of a blob. The returned bytes are owned by the caller.+pub fn read_blob(+ handles: list[ref store.Handle],+ id: objid.Id,+ git: object.GitRepo,+ has_git: bool+) 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 result: mut option[bytes.Bytes] = none+ if good {+ result = some(bytes.Bytes.dup(buf.Buf.view(out)))+ }+ buf.Buf.free(out)+ return result+}--- /dev/null+++ b/src/src/object/graph.sx@@ -0,0 +1,285 @@+/// Commit graph traversal and revision resolution.++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 view = use("../object/view.sx")+val changeid = use("changeid.sx")+val state = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")+val viewops = use("../store/viewops.sx")++pub 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)+}++pub 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 free_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++pub fn roots(v: ref view.View) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ for h in v.heads {+ if !contains(out, h) {+ @append(out, copy_id(h))+ }+ }+ for bm in v.bookmarks {+ for id in bm.targets.adds {+ if !contains(out, id) {+ @append(out, copy_id(id))+ }+ }+ }+ for t in v.tags {+ if !contains(out, t.target) {+ @append(out, copy_id(t.target))+ }+ }+ for w in v.working_copies {+ if !contains(out, w.target) {+ @append(out, copy_id(w.target))+ }+ }+ return out+}++pub type LoadedCommit = {+ c: mut ref commit.Commit+ body: mut bytes.Bytes+}++pub fn load_commit(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref LoadedCommit] = trust {+ val body_opt = state.read_body(handles, id, types.COMMIT)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = commit.decode(body)+ match decoded {+ ok c => {+ val lc: mut ref LoadedCommit = @alloc(@sizeof(LoadedCommit)) as ref LoadedCommit+ lc.c = c+ lc.body = body+ return some lc+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++pub fn free_loaded(lc: ref LoadedCommit) void = trust {+ commit.free_commit(lc.c)+ files.free_buffer(lc.body)+ @free(lc as ref void)+}++/// Collect all commits reachable from `start`.+pub fn collect(handles: list[ref store.Handle], start: list[objid.Id]) list[objid.Id] = trust {+ val out: mut list[objid.Id] = lists.new[objid.Id]()+ val stack: mut list[objid.Id] = lists.new[objid.Id]()+ for id in start {+ if !contains(out, id) && !contains(stack, id) {+ @append(stack, copy_id(id))+ }+ }+ for @len(stack) > 0 {+ val id: objid.Id = @remove(stack, @len(stack) - 1)+ if contains(out, id) {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ continue+ }+ @append(out, id)+ val c_opt = load_commit(handles, id)+ match c_opt {+ some lc => {+ for p in lc.c.parents {+ if !contains(out, p) && !contains(stack, p) {+ @append(stack, copy_id(p))+ }+ }+ free_loaded(lc)+ }+ none => {+ }+ }+ }+ @listfree(stack)+ return out+}++pub fn all(handles: list[ref store.Handle], v: ref view.View) list[objid.Id] = trust {+ val rs: list[objid.Id] = roots(v)+ val out: list[objid.Id] = collect(handles, rs)+ free_ids(rs)+ return out+}++fn is_hex_char(c: u8) bool = trust {+ return (c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70)+}++fn is_hex_prefix(b: bytes.Bytes) bool = trust {+ if b.len < 4 || b.len > 64 {+ return false+ }+ val i: mut usize = 0+ for i < b.len {+ if !is_hex_char(bytes.Bytes.at(b, i)) {+ return false+ }+ i+++ }+ return true+}++fn id_matches_hex(id: objid.Id, text: bytes.Bytes) bool = trust {+ val hex: ref u8 = objid.Id.hex(id)+ val full: bytes.Bytes = bytes.bytes(hex, 64)+ val matched: bool = changeid.prefix_matches(full, text)+ @free(hex as ref void)+ return matched+}++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 o = @get(bm.targets.adds, 0)+ if o is some id {+ return some id+ }+ }+ return none+ }+ }+ 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+ }+ }+ return none+}++fn remote_target(v: ref view.View, text: bytes.Bytes) option[objid.Id] = trust {+ for rr in v.remote_refs {+ val joined: usize = rr.remote.len + 1 + rr.name.len+ if joined == text.len {+ val prefix: bytes.Bytes = bytes.Bytes.slice(text, 0, rr.remote.len)+ if bytes.Bytes.eql(prefix, rr.remote) && bytes.Bytes.at(text, rr.remote.len) == 47 {+ val suffix: bytes.Bytes = bytes.Bytes.slice(+ text,+ rr.remote.len + 1,+ text.len+ )+ if bytes.Bytes.eql(suffix, rr.name) {+ return some rr.target+ }+ }+ }+ }+ return none+}++pub fn resolve(+ handles: list[ref store.Handle],+ v: ref view.View,+ rev: bytes.Bytes+) option[objid.Id] = trust {+ if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {+ return viewops.working_copy(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+ }+ val rr = remote_target(v, rev)+ if rr is some id3 {+ return some id3+ }+ val ids: list[objid.Id] = all(handles, v)+ val matches: mut list[objid.Id] = lists.new[objid.Id]()+ if is_hex_prefix(rev) {+ val i: mut usize = 0+ for i < @len(ids) {+ val o = @get(ids, i)+ if o is some id4 {+ if id_matches_hex(id4, rev) {+ @append(matches, copy_id(id4))+ }+ }+ i+++ }+ }+ if @len(matches) == 0 {+ val i2: mut usize = 0+ for i2 < @len(ids) {+ val o = @get(ids, i2)+ if o is some id5 {+ val c_opt = load_commit(handles, id5)+ if c_opt is some lc {+ if lc.c.change_id.ptr != none {+ val encoded: bytes.Bytes = changeid.encode(lc.c.change_id)+ if changeid.prefix_matches(encoded, rev) {+ @append(matches, copy_id(id5))+ }+ changeid.free(encoded)+ }+ free_loaded(lc)+ }+ }+ i2+++ }+ }+ free_ids(ids)+ val result: mut option[objid.Id] = none+ if @len(matches) == 1 {+ val o = @get(matches, 0)+ if o is some only {+ result = some copy_id(only)+ }+ } else {+ // With divergent changes the change ID is ambiguous; callers report it.+ }+ free_ids(matches)+ return result+}--- a/src/src/object/tree.sx+++ b/src/src/object/tree.sx@@ -24,6 +24,7 @@ pub type Tree = { entries: mut list[ref TreeEntry]+ body: mut bytes.Bytes } pub fn entry(name: bytes.Bytes, kind: u8, target: objid.Id) ref TreeEntry = {@@ -67,6 +68,7 @@ val count: usize = reader.Reader.read_list_len(r, prim.MAX_TREE_ENTRIES)? val t: mut ref Tree = @alloc(@sizeof(Tree)) as ref Tree t.entries = lists.new[ref TreeEntry]()+ t.body = bytes.empty() val prev: mut bytes.Bytes = bytes.empty() val have_prev: mut bool = false val i: mut usize = 0@@ -139,6 +141,10 @@ } pub fn free_tree(t: ref Tree) void = {+ if t.body.ptr != none {+ val bp: mut ref void = t.body.ptr as ref void+ trust @free(bp)+ } for e in t.entries { val p: mut ref void = e as ref void trust @free(p)--- /dev/null+++ b/src/src/object/treediff.sx@@ -0,0 +1,148 @@+/// Sorted path-level comparison between two trees.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val treewalk = use("treewalk.sx")+val store = use("../store/store.sx")++pub type Change = {+ path: mut bytes.Bytes+ old_kind: mut u8+ new_kind: mut u8+ old_id: mut objid.Id+ new_id: 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 new_change(+ path: bytes.Bytes,+ old_kind: u8,+ new_kind: u8,+ oid: objid.Id,+ nid: objid.Id+) ref Change = trust {+ val c: mut ref Change = @alloc(@sizeof(Change)) as ref Change+ c.path = path+ c.old_kind = old_kind+ c.new_kind = new_kind+ c.old_id = copy_id(oid)+ c.new_id = copy_id(nid)+ return c+}++pub fn compare(+ handles: list[ref store.Handle],+ old_tree: option[objid.Id],+ new_tree: option[objid.Id]+) list[ref Change] = trust {+ val old = treewalk.flatten_or_empty(handles, old_tree)+ val new = treewalk.flatten_or_empty(handles, new_tree)+ val out: mut list[ref Change] = lists.new[ref Change]()+ val i: mut usize = 0+ val j: mut usize = 0+ for i < @len(old) || j < @len(new) {+ val take: mut i32 = 0+ if i >= @len(old) {+ take = 1+ } elif j >= @len(new) {+ take = -1+ } else {+ val o = @get(old, i)+ val n = @get(new, j)+ val op: mut bytes.Bytes = bytes.empty()+ val np: mut bytes.Bytes = bytes.empty()+ if o is some oo {+ op = oo.path+ }+ if n is some nn {+ np = nn.path+ }+ take = bytes.Bytes.cmp(op, np) as i32+ }+ if take < 0 {+ val o = @get(old, i)+ if o is some e {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e.path),+ e.kind,+ treewalk.KIND_MISSING,+ e.target,+ objid.id(none)+ )+ )+ }+ i+++ } elif take > 0 {+ val n = @get(new, j)+ if n is some e2 {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e2.path),+ treewalk.KIND_MISSING,+ e2.kind,+ objid.id(none),+ e2.target+ )+ )+ }+ j+++ } else {+ val o = @get(old, i)+ val n = @get(new, j)+ if o is some e3 {+ if n is some e4 {+ val same: bool = e3.kind == e4.kind && objid.Id.eql(e3.target, e4.target)+ if !same {+ @append(+ out,+ new_change(+ bytes.Bytes.dup(e3.path),+ e3.kind,+ e4.kind,+ e3.target,+ e4.target+ )+ )+ }+ }+ }+ i+++ j+++ }+ }+ treewalk.free_flat(old)+ treewalk.free_flat(new)+ return out+}++pub fn free(changes: list[ref Change]) void = trust {+ for c in changes {+ if c.path.ptr != none {+ val pp: mut ref void = c.path.ptr as ref void+ @free(pp)+ }+ if c.old_id.ptr != none {+ val op: mut ref void = c.old_id.ptr as ref void+ @free(op)+ }+ if c.new_id.ptr != none {+ val np: mut ref void = c.new_id.ptr as ref void+ @free(np)+ }+ val cp: mut ref void = c as ref void+ @free(cp)+ }+ @listfree(changes)+}--- /dev/null+++ b/src/src/object/treewalk.sx@@ -0,0 +1,282 @@+/// Helpers for reading, flattening, and comparing tree objects.++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 read = use("../store/state.sx")+val store = use("../store/store.sx")+val files = use("../io/files.sx")++pub val KIND_MISSING: u8 = 0++pub type FlatEntry = {+ path: mut bytes.Bytes+ kind: mut u8+ target: mut objid.Id+}++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)+}++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)+ val body: mut bytes.Bytes = bytes.empty()+ match body_opt {+ some b => {+ body = b+ }+ none => {+ return none+ }+ }+ val decoded = tree.decode(body)+ match decoded {+ ok t => {+ t.body = body+ return some t+ }+ err _ => {+ files.free_buffer(body)+ return none+ }+ }+}++pub fn find_name(t: ref tree.Tree, name: bytes.Bytes) i32 = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(t.entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val e = @get(t.entries, mid)+ val c: mut i64 = 0+ if e is some entry {+ c = bytes.Bytes.cmp(entry.name, name)+ if c == 0 {+ return mid as i32+ }+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return -1+}++fn join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+ if prefix.len == 0 {+ return bytes.Bytes.dup(name)+ }+ val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8+ @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+ @store8(@ptradd(out, prefix.len as i64), 47)+ @memcpy(+ @ptradd(out, (prefix.len + 1) as i64) as ref void,+ name.ptr as ref void,+ name.len+ )+ return bytes.bytes(out, prefix.len + 1 + name.len)+}++fn new_flat(path: bytes.Bytes, kind: u8, target: objid.Id) ref FlatEntry = trust {+ val e: mut ref FlatEntry = @alloc(@sizeof(FlatEntry)) as ref FlatEntry+ e.path = path+ e.kind = kind+ e.target = copy_id(target)+ return e+}++fn flatten_into(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ prefix: bytes.Bytes,+ out: mut list[ref FlatEntry],+ depth: usize+) bool = trust {+ if depth > 4096 {+ return false+ }+ val t_opt = read_tree(handles, tree_id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ return false+ }+ }+ val good: mut bool = true+ 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) {+ files.free_buffer(path)+ good = false+ break+ }+ files.free_buffer(path)+ } else {+ @append(out, new_flat(path, e.kind, e.target))+ }+ }+ tree.free_tree(t)+ return good+}++fn entry_at(xs: list[ref FlatEntry], i: usize) ref FlatEntry = trust {+ val o = @get(xs, i)+ if o is some e {+ return e+ }+ assert false+ return none+}++fn merge_sort(xs: mut list[ref FlatEntry], lo: usize, hi: usize, tmp: mut list[ref FlatEntry]) void = trust {+ if hi - lo <= 1 {+ return+ }+ val mid: usize = lo + (hi - lo) / 2+ merge_sort(xs, lo, mid, tmp)+ merge_sort(xs, mid, hi, tmp)+ val i: mut usize = lo+ val j: mut usize = mid+ val k: mut usize = lo+ for k < hi {+ val take_left: mut bool = false+ if i >= mid {+ take_left = false+ } elif j >= hi {+ take_left = true+ } else {+ take_left = bytes.Bytes.cmp(entry_at(xs, i).path, entry_at(xs, j).path) <= 0+ }+ if take_left {+ @set(tmp, k, entry_at(xs, i))+ i+++ } else {+ @set(tmp, k, entry_at(xs, j))+ j+++ }+ k+++ }+ val m: mut usize = lo+ for m < hi {+ @set(xs, m, entry_at(tmp, m))+ m+++ }+}++pub fn sort_flat(xs: mut list[ref FlatEntry]) void = trust {+ val n: usize = @len(xs)+ if n <= 1 {+ return+ }+ val tmp: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()+ val i: mut usize = 0+ for i < n {+ @append(tmp, none)+ i+++ }+ merge_sort(xs, 0, n, tmp)+ @listfree(tmp)+}++/// 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 {+ val out: mut list[ref FlatEntry] = lists.new[ref FlatEntry]()+ if !flatten_into(handles, tree_id, bytes.empty(), out, 0) {+ // 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_or_empty(+ handles: list[ref store.Handle],+ tree: option[objid.Id]+) list[ref FlatEntry] = trust {+ if tree is some id {+ return flatten(handles, id)+ }+ return lists.new[ref FlatEntry]()+}++pub fn lookup(entries: list[ref FlatEntry], path: bytes.Bytes) option[ref FlatEntry] = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val c: i64 = bytes.Bytes.cmp(entry_at(entries, mid).path, path)+ if c == 0 {+ return some entry_at(entries, mid)+ }+ if c < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++fn conflicted_into(+ handles: list[ref store.Handle],+ tree_id: objid.Id,+ depth: usize+) bool = trust {+ if depth > 4096 {+ return true+ }+ val t_opt = read_tree(handles, tree_id)+ val t: mut ref tree.Tree = none+ match t_opt {+ some x => {+ t = x+ }+ none => {+ return true+ }+ }+ val found: mut bool = false+ for e in t.entries {+ if e.kind == tree.KIND_CONFLICT {+ found = true+ break+ }+ if e.kind == tree.KIND_SUBTREE && conflicted_into(handles, e.target, depth + 1) {+ found = true+ break+ }+ }+ tree.free_tree(t)+ return found+}++pub fn conflicted(handles: list[ref store.Handle], tree_id: objid.Id) bool = trust {+ return conflicted_into(handles, tree_id, 0)+}++pub fn free_flat(xs: list[ref FlatEntry]) void = trust {+ for e in xs {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(xs)+}--- a/src/src/store/fsck.sx+++ b/src/src/store/fsck.sx@@ -553,6 +553,12 @@ } i++ }+}++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 seen_contains(seen: list[objid.Id], id: objid.Id) bool = {@@ -599,7 +605,7 @@ match operation.decode(body) { ok o => { for p in o.parents {- @append(frontier, p)+ @append(frontier, copy_id(p)) } val _ = check_ref(ctx, handles, path, o.view, types.VIEW, "operation view") operation.free_operation(o)--- /dev/null+++ b/src/src/store/txn.sx@@ -0,0 +1,478 @@+/// Operation transactions: load the current view, append objects and a new+/// operation to a single pack, then advance the operation heads.++val stdio = use("std/stdio")+val os = use("std/os")+val time = use("std/time")+val bytes = use("../core/bytes.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 operation = use("../object/operation.sx")+val view = use("../object/view.sx")+val writer = use("../store/writer.sx")+val store = use("../store/store.sx")+val state = use("../store/state.sx")+val layout = use("../store/layout.sx")++pub type Txn = {+ repo: mut layout.Repo+ writer: mut ref writer.Writer+ view: mut ref view.View+ parents: mut list[objid.Id]+ start_ms: mut i64+}++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_ids(ids: list[objid.Id]) void = trust {+ for id in ids {+ if id.ptr != none {+ val p: mut ref void = id.ptr as ref void+ @free(p)+ }+ }+ @listfree(ids)+}++fn same_id(a: objid.Id, b: objid.Id) bool = trust {+ return objid.Id.eql(a, b)+}++fn contains_id(xs: list[objid.Id], id: objid.Id) bool = trust {+ for x in xs {+ if same_id(x, id) {+ return true+ }+ }+ return false+}++fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {+ if !contains_id(xs, id) {+ @append(xs, copy_id(id))+ }+}++fn clone_targets(ts: view.TargetSet) view.TargetSet = trust {+ val out: mut view.TargetSet = view.empty_target_set()+ for a in ts.adds {+ @append(out.adds, copy_id(a))+ }+ for r in ts.removes {+ @append(out.removes, copy_id(r))+ }+ return out+}++fn clone_bookmark(bm: ref view.Bookmark) ref view.Bookmark = trust {+ val b: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+ b.name = bytes.Bytes.dup(bm.name)+ b.targets = clone_targets(bm.targets)+ return b+}++fn clone_tag(t: ref view.TagRef) ref view.TagRef = trust {+ val out: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+ out.name = bytes.Bytes.dup(t.name)+ out.target = copy_id(t.target)+ return out+}++fn clone_workspace(w: ref view.WorkspaceRef) ref view.WorkspaceRef = trust {+ val out: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ out.workspace = bytes.Bytes.dup(w.workspace)+ out.target = copy_id(w.target)+ return out+}++fn find_bookmark(v: ref view.View, name: bytes.Bytes) i32 = 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 i as i32+ }+ }+ i+++ }+ return -1+}++fn find_tag(v: ref view.View, name: bytes.Bytes) i32 = trust {+ val i: mut usize = 0+ for i < @len(v.tags) {+ val o = @get(v.tags, i)+ if o is some t {+ if bytes.Bytes.eql(t.name, name) {+ return i as i32+ }+ }+ i+++ }+ return -1+}++fn find_workspace(v: ref view.View, name: bytes.Bytes) i32 = trust {+ val i: mut usize = 0+ for i < @len(v.working_copies) {+ val o = @get(v.working_copies, i)+ if o is some w {+ if bytes.Bytes.eql(w.workspace, name) {+ return i as i32+ }+ }+ i+++ }+ return -1+}++fn conflict_targets(a: objid.Id, b: objid.Id) view.TargetSet = trust {+ val ts: mut view.TargetSet = view.empty_target_set()+ @append(ts.adds, copy_id(a))+ @append(ts.adds, copy_id(b))+ @append(ts.removes, objid.id(none))+ return ts+}++fn merge_view_into(dst: mut ref view.View, src: ref view.View) void = trust {+ for h in src.heads {+ add_unique(dst.heads, h)+ }+ for bm in src.bookmarks {+ val idx: i32 = find_bookmark(dst, bm.name)+ if idx < 0 {+ @append(dst.bookmarks, clone_bookmark(bm))+ } else {+ val existing = @get(dst.bookmarks, idx as usize)+ if existing is some e {+ val a: mut objid.Id = objid.id_none()+ val b: mut objid.Id = objid.id_none()+ if @len(e.targets.adds) > 0 {+ val o = @get(e.targets.adds, 0)+ if o is some id {+ a = id+ }+ }+ if @len(bm.targets.adds) > 0 {+ val o2 = @get(bm.targets.adds, 0)+ if o2 is some id2 {+ b = id2+ }+ }+ if !same_id(a, b) || @len(e.targets.adds) != @len(bm.targets.adds) {+ @listfree(e.targets.adds)+ @listfree(e.targets.removes)+ e.targets = conflict_targets(a, b)+ }+ }+ }+ }+ for t in src.tags {+ if find_tag(dst, t.name) < 0 {+ @append(dst.tags, clone_tag(t))+ }+ }+ for w in src.working_copies {+ if find_workspace(dst, w.workspace) < 0 {+ @append(dst.working_copies, clone_workspace(w))+ }+ }+}++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+++ }+}++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+++ }+}++fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.WorkspaceRef = 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.WorkspaceRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn load_view_for_head(+ handles: list[ref store.Handle],+ id: objid.Id+) option[ref view.View] = trust {+ val op_opt = state.read_operation(handles, id)+ val op: mut ref operation.Operation = none+ match op_opt {+ some o => {+ op = o+ }+ none => {+ return none+ }+ }+ val view_id: objid.Id = copy_id(op.view)+ operation.free_operation(op)+ val v_opt = state.read_view(handles, view_id)+ if view_id.ptr != none {+ val vp: mut ref void = view_id.ptr as ref void+ @free(vp)+ }+ return v_opt+}++pub fn begin(repo: layout.Repo) option[ref Txn] = trust {+ val heads: list[objid.Id] = state.heads(repo)+ val st: store.Store = store.open_all(repo)+ val v: mut ref view.View = none+ if @len(heads) == 0 {+ v = state.empty_view()+ } elif @len(heads) == 1 {+ val only = @get(heads, 0)+ val id: mut objid.Id = objid.id_none()+ if only is some x {+ id = x+ }+ val loaded = load_view_for_head(st.handles, id)+ match loaded {+ some x => {+ v = x+ }+ none => {+ store.close(st)+ free_ids(heads)+ return none+ }+ }+ } else {+ val first = @get(heads, 0)+ val first_id: mut objid.Id = objid.id_none()+ if first is some x {+ first_id = x+ }+ val base = load_view_for_head(st.handles, first_id)+ val base_view: mut ref view.View = none+ match base {+ some x => {+ base_view = x+ }+ none => {+ store.close(st)+ free_ids(heads)+ return none+ }+ }+ val i: mut usize = 1+ for i < @len(heads) {+ val o = @get(heads, i)+ val hid: mut objid.Id = objid.id_none()+ if o is some x {+ hid = x+ }+ val extra = load_view_for_head(st.handles, hid)+ match extra {+ some ev => {+ merge_view_into(base_view, ev)+ view.free_view(ev)+ }+ none => {+ }+ }+ i+++ }+ add_unique(base_view.heads, first_id)+ v = base_view+ }+ store.close(st)+ sort_bookmarks(v.bookmarks)+ sort_tags(v.tags)+ sort_workspaces(v.working_copies)+ val w_opt = writer.open(repo)+ val w: mut ref writer.Writer = none+ match w_opt {+ some x => {+ w = x+ }+ none => {+ view.free_view(v)+ free_ids(heads)+ return none+ }+ }+ val tx: mut ref Txn = @alloc(@sizeof(Txn)) as ref Txn+ tx.repo = repo+ tx.writer = w+ tx.view = v+ tx.parents = heads+ tx.start_ms = time.unix_now_millis()+ return some tx+}++pub fn add_object(tx: mut ref Txn, kind: u8, body: bytes.Bytes) objid.Id = trust {+ return writer.add(tx.writer, kind, body)+}++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)+}++fn host_from_env() bytes.Bytes = trust {+ val h = os.env(c"HOSTNAME")+ match h {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"localhost", 9))+ }+ }+}++fn user_from_env() bytes.Bytes = trust {+ val u = os.env(c"USER")+ match u {+ some v => {+ return bytes.Bytes.dup(bytes.from_cstr(v))+ }+ none => {+ return bytes.Bytes.dup(bytes.bytes(c"unknown", 7))+ }+ }+}++fn free_txn(tx: mut ref Txn) void = trust {+ if tx.view != none {+ view.free_view(tx.view)+ }+ free_ids(tx.parents)+ @free(tx as ref void)+}++pub fn abort(tx: mut ref Txn) void = trust {+ writer.abort(tx.writer)+ free_txn(tx)+}++/// Encode the view, write an operation, and advance the heads.+pub fn finish(tx: mut ref Txn, description: bytes.Bytes) i32 = trust {+ val view_body: bytes.Bytes = view.encode(tx.view)+ val view_id: objid.Id = writer.add(tx.writer, types.VIEW, view_body)+ val now: i64 = time.unix_now_millis()+ val hostname: bytes.Bytes = host_from_env()+ val username: bytes.Bytes = user_from_env()+ val tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+ val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+ kv.key = bytes.bytes(c"command", 7)+ kv.value = bytes.Bytes.dup(description)+ @append(tags, kv)+ val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation+ op.parents = lists.new[objid.Id]()+ for p in tx.parents {+ @append(op.parents, copy_id(p))+ }+ op.view = view_id+ op.start = prim.TimeMs{ms: tx.start_ms, tz_min: 0}+ op.end = prim.TimeMs{ms: now, tz_min: 0}+ op.hostname = hostname+ op.username = username+ op.description = bytes.Bytes.dup(description)+ op.tags = tags+ val op_body: bytes.Bytes = operation.encode(op)+ val op_id: objid.Id = writer.add(tx.writer, types.OPERATION, op_body)+ operation.free_operation(op)++ val wrote: bool = writer.finish(tx.writer)+ if !wrote {+ stdio.eprint("vn: failed to write object pack\n", {})+ free_txn(tx)+ return 1+ }+ val head_ok: bool = state.write_head(tx.repo, op_id)+ if head_ok {+ for p in tx.parents {+ if !objid.Id.is_none(p) {+ val _ = state.delete_head(tx.repo, p)+ }+ }+ }+ if view_id.ptr != none {+ val vp: mut ref void = view_id.ptr as ref void+ @free(vp)+ }+ if op_id.ptr != none {+ val opp: mut ref void = op_id.ptr as ref void+ @free(opp)+ }+ free_txn(tx)+ if !head_ok {+ return 1+ }+ return 0+}--- /dev/null+++ b/src/src/store/viewops.sx@@ -0,0 +1,166 @@+/// Small view mutations shared by working-copy and operation commands.++val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val objid = use("../object/id.sx")+val view = use("../object/view.sx")++pub 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)+}++pub fn same(a: objid.Id, b: objid.Id) bool = trust {+ return objid.Id.eql(a, b)+}++pub fn contains(xs: list[objid.Id], id: objid.Id) bool = trust {+ for x in xs {+ if same(x, id) {+ return true+ }+ }+ return false+}++pub fn add_unique(xs: mut list[objid.Id], id: objid.Id) void = trust {+ if !contains(xs, id) {+ @append(xs, copy_id(id))+ }+}++pub fn workspace_name() bytes.Bytes = trust {+ return bytes.bytes(c"default", 7)+}++pub fn working_copy(v: ref view.View) option[objid.Id] = trust {+ val name: bytes.Bytes = workspace_name()+ for w in v.working_copies {+ if bytes.Bytes.eql(w.workspace, name) {+ return some copy_id(w.target)+ }+ }+ return none+}++pub fn set_workspace(v: mut ref view.View, id: objid.Id) void = trust {+ val name: bytes.Bytes = workspace_name()+ val i: mut usize = 0+ for i < @len(v.working_copies) {+ val o = @get(v.working_copies, i)+ if o is some w {+ if bytes.Bytes.eql(w.workspace, name) {+ w.target = copy_id(id)+ return+ }+ }+ i+++ }+ val w2: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+ w2.workspace = bytes.Bytes.dup(name)+ w2.target = copy_id(id)+ @append(v.working_copies, w2)+ sort_workspaces(v.working_copies)+}++pub fn remove_head(v: mut ref view.View, id: objid.Id) void = trust {+ val i: mut usize = 0+ for i < @len(v.heads) {+ val o = @get(v.heads, i)+ if o is some h {+ if same(h, id) {+ @remove(v.heads, i)+ return+ }+ }+ i+++ }+}++fn sort_heads(xs: mut list[objid.Id]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut objid.Id = objid.id_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 objid.Id = objid.id_none()+ if prev_opt is some v2 {+ prev = v2+ }+ if objid.Id.cmp(prev, c) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++pub fn rebuild_heads(v: mut ref view.View) void = trust {+ for bm in v.bookmarks {+ for id in bm.targets.adds {+ add_unique(v.heads, id)+ }+ }+ for t in v.tags {+ add_unique(v.heads, t.target)+ }+ for w in v.working_copies {+ add_unique(v.heads, w.target)+ }+ sort_heads(v.heads)+}++pub fn bookmark_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for bm in v.bookmarks {+ if contains(bm.targets.adds, id) {+ @append(out, bm.name)+ }+ }+ return out+}++pub fn tag_names(v: ref view.View, id: objid.Id) list[bytes.Bytes] = trust {+ val out: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+ for t in v.tags {+ if same(t.target, id) {+ @append(out, t.name)+ }+ }+ return out+}++pub fn sort_workspaces(xs: mut list[ref view.WorkspaceRef]) void = trust {+ val i: mut usize = 1+ for i < @len(xs) {+ val cur = @get(xs, i)+ val c: mut ref view.WorkspaceRef = 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.WorkspaceRef = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.workspace, c.workspace) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}--- /dev/null+++ b/src/src/worktree/ignore.sx@@ -0,0 +1,306 @@+/// Gitignore-style ignore rules for working-copy snapshots.+///+/// Supports the subset of `.vnexclude` / `.gitignore` syntax that matters for+/// deciding which new files enter a snapshot: comments, negation, directory+/// patterns, anchored patterns, `*`, `?`, and `**`.++val str = use("std/string")+val bytes = use("../core/bytes.sx")+val lists = use("../core/lists.sx")+val files = use("../io/files.sx")++pub type Rule = {+ pattern: mut bytes.Bytes+ negated: mut bool+ dir_only: mut bool+ anchored: mut bool+ has_slash: mut bool+ base: mut bytes.Bytes+}++pub type Rules = {+ items: mut list[ref Rule]+}++fn new_rule(+ pattern: bytes.Bytes,+ negated: bool,+ dir_only: bool,+ anchored: bool,+ has_slash: bool,+ base: bytes.Bytes+) ref Rule = trust {+ val r: mut ref Rule = @alloc(@sizeof(Rule)) as ref Rule+ r.pattern = pattern+ r.negated = negated+ r.dir_only = dir_only+ r.anchored = anchored+ r.has_slash = has_slash+ r.base = base+ return r+}++pub fn empty() Rules = trust {+ return Rules{items: lists.new[ref Rule]()}+}++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 {+ break+ }+ start+++ }+ for end > start {+ val c2: u8 = bytes.Bytes.at(b, end - 1)+ if c2 != 32 && c2 != 9 && c2 != 13 {+ break+ }+ end--+ }+ return bytes.Bytes.slice(b, start, end)+}++fn add_line(rules: mut Rules, base: bytes.Bytes, line_in: bytes.Bytes) void = trust {+ val line: bytes.Bytes = trim(line_in)+ if line.len == 0 {+ return+ }+ if bytes.Bytes.at(line, 0) == 35 {+ return+ }+ val negated: mut bool = false+ val start: mut usize = 0+ if bytes.Bytes.at(line, 0) == 33 {+ negated = true+ start = 1+ }+ if start >= line.len {+ return+ }+ val mut_end: mut usize = line.len+ val dir_only: mut bool = false+ if bytes.Bytes.at(line, mut_end - 1) == 47 {+ dir_only = true+ mut_end--+ }+ if start >= mut_end {+ return+ }+ val anchored: mut bool = false+ if bytes.Bytes.at(line, start) == 47 {+ anchored = true+ start+++ }+ if start >= mut_end {+ return+ }+ val pattern: bytes.Bytes = bytes.Bytes.slice(line, start, mut_end)+ val has_slash: mut bool = false+ val i: mut usize = 0+ for i < pattern.len {+ if bytes.Bytes.at(pattern, i) == 47 {+ has_slash = true+ }+ i+++ }+ @append(+ rules.items,+ new_rule(pattern, negated, dir_only, anchored, has_slash, base)+ )+}++pub fn load_file(rules: mut Rules, repo_root: str.StringView, base: bytes.Bytes, name: str.StringView) void = trust {+ val base_view: str.StringView = files.to_view(base)+ val dir: str.StringView = files.join(repo_root, base_view)+ val path: str.StringView = files.join(dir, name)+ val data_opt = files.read_all(path)+ files.free_path(dir)+ files.free_path(path)+ match data_opt {+ some data => {+ val pos: mut usize = 0+ val line_start: mut usize = 0+ for pos <= data.len {+ val at_end: bool = pos == data.len+ if at_end || bytes.Bytes.at(data, pos) == 10 {+ add_line(rules, bytes.Bytes.dup(base), bytes.Bytes.slice(data, line_start, pos))+ line_start = pos + 1+ }+ pos+++ }+ files.free_buffer(data)+ }+ none => {+ }+ }+}++/// Load root-level `.vnexclude` and `.gitignore`. Per-directory files are+/// added during traversal by `load_file`.+pub fn load_root(rules: mut Rules, repo_root: str.StringView) void = trust {+ load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".vnexclude"))+ load_file(rules, repo_root, bytes.empty(), str.from_cstr(c".gitignore"))+}++fn glob_here(pattern: bytes.Bytes, pi: usize, text: bytes.Bytes, ti: usize) bool = trust {+ if pi >= pattern.len {+ return ti >= text.len+ }+ val pc: u8 = bytes.Bytes.at(pattern, pi)+ if pc == 42 {+ val double: bool = pi + 1 < pattern.len && bytes.Bytes.at(pattern, pi + 1) == 42+ if double {+ val next: usize = pi + 2+ if next < pattern.len && bytes.Bytes.at(pattern, next) == 47 {+ val after: usize = next + 1+ val j: mut usize = ti+ for {+ if glob_here(pattern, after, text, j) {+ return true+ }+ if j >= text.len {+ break+ }+ if bytes.Bytes.at(text, j) == 47 {+ j+++ continue+ }+ j+++ for j < text.len && bytes.Bytes.at(text, j) != 47 {+ j+++ }+ }+ return false+ }+ val j2: mut usize = ti+ for {+ if glob_here(pattern, next, text, j2) {+ return true+ }+ if j2 >= text.len {+ break+ }+ j2+++ }+ return false+ }+ val j3: mut usize = ti+ for {+ if glob_here(pattern, pi + 1, text, j3) {+ return true+ }+ if j3 >= text.len || bytes.Bytes.at(text, j3) == 47 {+ break+ }+ j3+++ }+ return false+ }+ if ti >= text.len {+ return false+ }+ if pc == 63 {+ if bytes.Bytes.at(text, ti) == 47 {+ return false+ }+ return glob_here(pattern, pi + 1, text, ti + 1)+ }+ if pc != bytes.Bytes.at(text, ti) {+ return false+ }+ return glob_here(pattern, pi + 1, text, ti + 1)+}++fn component_end(text: bytes.Bytes, start: usize) usize = trust {+ val i: mut usize = start+ for i < text.len && bytes.Bytes.at(text, i) != 47 {+ i+++ }+ return i+}++fn match_component(pattern: bytes.Bytes, text: bytes.Bytes) bool = trust {+ return glob_here(pattern, 0, text, 0)+}++fn relative_to(base: bytes.Bytes, path: bytes.Bytes) option[bytes.Bytes] = trust {+ if base.len == 0 {+ return some path+ }+ if path.len <= base.len {+ return none+ }+ val prefix: bytes.Bytes = bytes.Bytes.slice(path, 0, base.len)+ if !bytes.Bytes.eql(prefix, base) {+ return none+ }+ if bytes.Bytes.at(path, base.len) != 47 {+ return none+ }+ return some bytes.Bytes.slice(path, base.len + 1, path.len)+}++fn rule_matches(rule: ref Rule, path: bytes.Bytes, is_dir: bool) bool = trust {+ val rel_opt = relative_to(rule.base, path)+ val rel: mut bytes.Bytes = bytes.empty()+ match rel_opt {+ some r => {+ rel = r+ }+ none => {+ return false+ }+ }+ if rel.len == 0 {+ return false+ }+ if rule.dir_only && !is_dir {+ return false+ }+ if !rule.has_slash && !rule.anchored {+ val start: mut usize = 0+ for {+ val end: usize = component_end(rel, start)+ if match_component(rule.pattern, bytes.Bytes.slice(rel, start, end)) {+ return true+ }+ if end >= rel.len {+ break+ }+ start = end + 1+ }+ return false+ }+ return glob_here(rule.pattern, 0, rel, 0)+}++/// True when `path` is ignored. Later rules override earlier ones.+pub fn ignored(rules: Rules, path: bytes.Bytes, is_dir: bool) bool = trust {+ val ignored_flag: mut bool = false+ for r in rules.items {+ if rule_matches(r, path, is_dir) {+ ignored_flag = !r.negated+ }+ }+ return ignored_flag+}++pub fn free(rules: Rules) void = trust {+ for r in rules.items {+ if r.pattern.ptr != none {+ val pp: mut ref void = r.pattern.ptr as ref void+ @free(pp)+ }+ if r.base.ptr != none {+ val bp: mut ref void = r.base.ptr as ref void+ @free(bp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ @listfree(rules.items)+}--- /dev/null+++ b/src/src/worktree/snapshot.sx@@ -0,0 +1,1013 @@+/// Working-copy snapshotting.+///+/// Before a command reads or writes the working copy, vein snapshots the files+/// on disk into the working-copy commit. The commit keeps its change ID and+/// message and is amended in place. A snapshot that produces the same tree as+/// the existing commit does not create an operation.++val str = use("std/string")+val stdio = use("std/stdio")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val buf = use("../core/buf.sx")+val reader = use("../core/reader.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 tree = use("../object/tree.sx")+val commit = use("../object/commit.sx")+val blob = use("../object/blob.sx")+val treewalk = use("../object/treewalk.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 identity = use("../core/identity.sx")+val gitmap = use("../git/map.sx")+val view = use("../object/view.sx")+val files = use("../io/files.sx")+val native = use("../io/native.sx")+val stat = use("../io/stat.sx")+val raw = use("../object/raw.sx")+val ignore = use("ignore.sx")++type CacheEntry = {+ path: mut bytes.Bytes+ size: mut u64+ mtime_ns: mut u64+ inode: mut u64+ kind: mut u8+ executable: mut bool+ target: mut objid.Id+}++type Cache = {+ entries: mut list[ref CacheEntry]+ written_ms: mut i64+}++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 join_path(prefix: bytes.Bytes, name: bytes.Bytes) bytes.Bytes = trust {+ if prefix.len == 0 {+ return bytes.Bytes.dup(name)+ }+ val out: ref u8 = @alloc(prefix.len + 1 + name.len) as ref u8+ @memcpy(out as ref void, prefix.ptr as ref void, prefix.len)+ @store8(@ptradd(out, prefix.len as i64), 47)+ @memcpy(+ @ptradd(out, (prefix.len + 1) as i64) as ref void,+ name.ptr as ref void,+ name.len+ )+ return bytes.bytes(out, prefix.len + 1 + name.len)+}++fn new_entry(+ path: bytes.Bytes,+ info: stat.StatInfo,+ executable: bool,+ target: objid.Id+) ref CacheEntry = trust {+ val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry+ e.path = path+ e.size = info.size+ e.mtime_ns = info.mtime_ns+ e.inode = info.inode+ e.kind = info.kind+ e.executable = executable+ e.target = copy_id(target)+ return e+}++fn free_entry(e: ref CacheEntry) void = trust {+ if e.path.ptr != none {+ val pp: mut ref void = e.path.ptr as ref void+ @free(pp)+ }+ if e.target.ptr != none {+ val tp: mut ref void = e.target.ptr as ref void+ @free(tp)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+}++fn free_cache(c: Cache) void = trust {+ for e in c.entries {+ free_entry(e)+ }+ @listfree(c.entries)+}++fn entry_at(xs: list[ref CacheEntry], i: usize) ref CacheEntry = trust {+ val o = @get(xs, i)+ if o is some e {+ return e+ }+ assert false+ return none+}++fn sort_cache(xs: mut list[ref CacheEntry]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref CacheEntry = 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 CacheEntry = none+ if prev_opt is some v2 {+ prev = v2+ }+ if bytes.Bytes.cmp(prev.path, c.path) <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn cache_lookup(c: Cache, path: bytes.Bytes) option[ref CacheEntry] = trust {+ val lo: mut usize = 0+ val hi: mut usize = @len(c.entries)+ for lo < hi {+ val mid: usize = lo + (hi - lo) / 2+ val e: ref CacheEntry = entry_at(c.entries, mid)+ val cmp: i64 = bytes.Bytes.cmp(e.path, path)+ if cmp == 0 {+ return some e+ }+ if cmp < 0 {+ lo = mid + 1+ } else {+ hi = mid+ }+ }+ return none+}++fn cache_u8(r: mut reader.Reader) option[u8] = trust {+ val x = reader.Reader.read_u8(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_u64(r: mut reader.Reader) option[u64] = trust {+ val x = reader.Reader.read_u64_le(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_varint(r: mut reader.Reader) option[u64] = trust {+ val x = reader.Reader.read_varint(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_bytes(r: mut reader.Reader, max: usize) option[bytes.Bytes] = trust {+ val x = reader.Reader.read_bytes(r, max)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn cache_id(r: mut reader.Reader) option[ref u8] = trust {+ val x = reader.Reader.read_id(r)+ match x {+ ok v => {+ return some(v)+ }+ err _ => {+ return none+ }+ }+}++fn load_cache(repo: layout.Repo) Cache = trust {+ val c: mut Cache = Cache{entries: lists.new[ref CacheEntry](), written_ms: 0}+ val dir: str.StringView = layout.working_copy_dir(repo)+ val path: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))+ files.free_path(dir)+ 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 c+ }+ }+ if data.len < 13 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 4), bytes.bytes(c"VST1", 4)) {+ files.free_buffer(data)+ return c+ }+ val r: mut reader.Reader = reader.new(data.ptr, data.len)+ val version_opt = cache_u8(r)+ val version: mut u8 = 0+ match version_opt {+ some v => {+ version = v+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ if version != 49 {+ files.free_buffer(data)+ return c+ }+ val written_opt = cache_u64(r)+ match written_opt {+ some written => {+ c.written_ms = written as i64+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ val count_opt = cache_varint(r)+ val count: mut usize = 0+ match count_opt {+ some v => {+ count = v as usize+ }+ none => {+ files.free_buffer(data)+ return c+ }+ }+ val i: mut usize = 0+ for i < count {+ val p_opt = cache_bytes(r, 65536)+ val p: mut bytes.Bytes = bytes.empty()+ match p_opt {+ some v => {+ p = v+ }+ none => {+ break+ }+ }+ val sz_o = cache_u64(r)+ val mt_o = cache_u64(r)+ val ino_o = cache_u64(r)+ val kind_o = cache_u8(r)+ val ex_o = cache_u8(r)+ val idp_o = cache_id(r)+ if sz_o is none {+ break+ }+ if mt_o is none {+ break+ }+ if ino_o is none {+ break+ }+ if kind_o is none {+ break+ }+ if ex_o is none {+ break+ }+ if idp_o is none {+ break+ }+ val sz: mut u64 = 0+ val mt: mut u64 = 0+ val ino: mut u64 = 0+ val kind: mut u8 = 0+ val ex: mut u8 = 0+ val idp: mut ref u8 = none+ match sz_o {+ some v => {+ sz = v+ }+ none => {+ }+ }+ match mt_o {+ some v => {+ mt = v+ }+ none => {+ }+ }+ match ino_o {+ some v => {+ ino = v+ }+ none => {+ }+ }+ match kind_o {+ some v => {+ kind = v+ }+ none => {+ }+ }+ match ex_o {+ some v => {+ ex = v+ }+ none => {+ }+ }+ match idp_o {+ some v => {+ idp = v+ }+ none => {+ }+ }+ val e: mut ref CacheEntry = @alloc(@sizeof(CacheEntry)) as ref CacheEntry+ e.path = bytes.Bytes.dup(p)+ e.size = sz+ e.mtime_ns = mt+ e.inode = ino+ e.kind = kind+ e.executable = ex != 0+ e.target = copy_id(objid.id(idp))+ @append(c.entries, e)+ i+++ }+ files.free_buffer(data)+ sort_cache(c.entries)+ return c+}++fn save_cache(repo: layout.Repo, c: Cache) bool = trust {+ val b: mut buf.Buf = buf.new(4096)+ buf.Buf.put_raw(b, c"VST1", 4)+ buf.Buf.put_u8(b, 49)+ buf.Buf.put_u64_le(b, time.unix_now_millis() as u64)+ buf.Buf.put_varint(b, @len(c.entries) as u64)+ for e in c.entries {+ buf.Buf.put_length_prefixed(b, e.path)+ buf.Buf.put_u64_le(b, e.size)+ buf.Buf.put_u64_le(b, e.mtime_ns)+ buf.Buf.put_u64_le(b, e.inode)+ buf.Buf.put_u8(b, e.kind)+ val ex: mut u8 = 0+ if e.executable {+ ex = 1+ }+ buf.Buf.put_u8(b, ex)+ buf.Buf.put_id(b, e.target.ptr)+ }+ val dir: str.StringView = layout.working_copy_dir(repo)+ val final: str.StringView = files.join(dir, str.from_cstr(c"stat-cache"))+ val tmpd: str.StringView = layout.tmp_dir(repo)+ val tmp: str.StringView = files.join(tmpd, str.from_cstr(c"stat-cache.tmp"))+ val wrote: bool = native.write_atomic(tmp, final, tmpd, dir, buf.Buf.view(b))+ files.free_path(dir)+ files.free_path(final)+ files.free_path(tmpd)+ files.free_path(tmp)+ buf.Buf.free(b)+ return wrote+}++fn add_blob_data(tx: mut ref txn.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 _ = txn.add_known(tx, orf.type_byte, oid, orf.body)+ orf.body = bytes.empty()+ }+ ri+++ }+ blob.free_build(built)+ return id+}++fn cache_matches(e: ref CacheEntry, info: stat.StatInfo, executable: bool, now_ms: i64, written_ms: i64) bool = trust {+ if e.size != info.size || e.mtime_ns != info.mtime_ns || e.inode != info.inode {+ return false+ }+ if e.executable != executable || e.kind != info.kind {+ return false+ }+ // Files touched inside the racy window are re-verified by content.+ val now_ns: i64 = now_ms * 1000000+ val written_ns: i64 = written_ms * 1000000+ val window: i64 = 2000000000+ if info.mtime_ns as i64 >= written_ns - window {+ return false+ }+ if now_ns - (info.mtime_ns as i64) < window {+ return false+ }+ return true+}++fn sort_names(xs: mut list[ref u8]) void = trust {+ val n: usize = @len(xs)+ val i: mut usize = 1+ for i < n {+ val cur = @get(xs, i)+ val c: mut ref u8 = 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 u8 = none+ if prev_opt is some v2 {+ prev = v2+ }+ val cmp: i64 = bytes.Bytes.cmp(bytes.from_cstr(prev), bytes.from_cstr(c))+ if cmp <= 0 {+ break+ }+ @set(xs, j, prev)+ j--+ }+ @set(xs, j, c)+ i+++ }+}++fn is_meta_name(name: bytes.Bytes) bool = trust {+ if bytes.Bytes.eql(name, bytes.bytes(c".vein", 5)) {+ return true+ }+ if bytes.Bytes.eql(name, bytes.bytes(c".git", 4)) {+ return true+ }+ return false+}++fn free_local(local: ignore.Rules, keep: usize) void = trust {+ val i: mut usize = keep+ for i < @len(local.items) {+ val o = @get(local.items, i)+ if o is some r {+ if r.pattern.ptr != none {+ val pp: mut ref void = r.pattern.ptr as ref void+ @free(pp)+ }+ if r.base.ptr != none {+ val bp: mut ref void = r.base.ptr as ref void+ @free(bp)+ }+ val rp: mut ref void = r as ref void+ @free(rp)+ }+ i+++ }+ @listfree(local.items)+}++fn build_dir(+ tx: mut ref txn.Txn,+ root: str.StringView,+ handles: list[ref store.Handle],+ rel: bytes.Bytes,+ old_tree: option[objid.Id],+ base_rules: ignore.Rules,+ cache: Cache,+ new_cache: mut list[ref CacheEntry],+ now_ms: i64+) option[objid.Id] = trust {+ val local: mut ignore.Rules = ignore.empty()+ for r in base_rules.items {+ @append(local.items, r)+ }+ val keep: usize = @len(local.items)+ ignore.load_file(local, root, rel, str.from_cstr(c".vnexclude"))+ ignore.load_file(local, root, rel, str.from_cstr(c".gitignore"))++ val old: mut ref tree.Tree = none+ val have_old: mut bool = false+ if old_tree is some oid {+ val t_opt = treewalk.read_tree(handles, oid)+ match t_opt {+ some t => {+ old = t+ have_old = true+ }+ none => {+ free_local(local, keep)+ return none+ }+ }+ }++ val rel_view: str.StringView = files.to_view(rel)+ val dir: str.StringView = files.join(root, rel_view)+ if !files.exists_dir(dir) {+ files.free_path(dir)+ if have_old {+ tree.free_tree(old)+ }+ free_local(local, keep)+ return none+ }+ val names_list: mut list[ref u8] = files.list_dir(dir)+ sort_names(names_list)++ val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+ val failed: mut bool = false+ for name_c in names_list {+ if failed {+ break+ }+ val name: bytes.Bytes = bytes.from_cstr(name_c)+ if is_meta_name(name) {+ continue+ }+ val path: bytes.Bytes = join_path(rel, name)+ val fs_path: str.StringView = files.join(dir, str.from_cstr(name_c))+ val stat_opt = stat.read(fs_path)+ files.free_path(fs_path)+ if stat_opt is none {+ files.free_buffer(path)+ continue+ }+ val info: mut stat.StatInfo = stat.StatInfo{kind: 0, executable: false, size: 0, mtime_ns: 0, inode: 0}+ match stat_opt {+ some si => {+ info = si+ }+ none => {+ files.free_buffer(path)+ continue+ }+ }+ if info.kind == stat.KIND_MISSING {+ files.free_buffer(path)+ continue+ }+ val is_dir: bool = info.kind == stat.KIND_DIR+ val ignored: bool = ignore.ignored(local, path, is_dir)+ val old_idx: mut i32 = -1+ if have_old {+ old_idx = treewalk.find_name(old, name)+ }+ if ignored && old_idx < 0 {+ files.free_buffer(path)+ continue+ }+ if is_dir {+ val child_old: mut option[objid.Id] = none+ if have_old && old_idx >= 0 {+ val oe = @get(old.entries, old_idx as usize)+ if oe is some e {+ if e.kind == tree.KIND_SUBTREE {+ child_old = some copy_id(e.target)+ }+ }+ }+ val child_opt = build_dir(+ tx,+ root,+ handles,+ path,+ child_old,+ local,+ cache,+ new_cache,+ now_ms+ )+ if child_old is some co {+ if co.ptr != none {+ val cp: mut ref void = co.ptr as ref void+ @free(cp)+ }+ }+ match child_opt {+ some cid => {+ @append(entries, tree.entry(bytes.Bytes.dup(name), tree.KIND_SUBTREE, cid))+ }+ none => {+ }+ }+ files.free_buffer(path)+ } elif info.kind == stat.KIND_LINK {+ val fs2: str.StringView = files.join(dir, str.from_cstr(name_c))+ val target_opt = stat.link_target(fs2)+ files.free_path(fs2)+ match target_opt {+ some target => {+ val bid: objid.Id = add_blob_data(tx, target.ptr, target.len)+ val kind: u8 = tree.KIND_SYMLINK+ @append(entries, tree.entry(bytes.Bytes.dup(name), kind, bid))+ @append(new_cache, new_entry(bytes.Bytes.dup(path), info, false, bid))+ files.free_buffer(target)+ }+ none => {+ }+ }+ files.free_buffer(path)+ } else {+ val executable: bool = info.executable+ val cached = cache_lookup(cache, path)+ val reuse: mut bool = false+ val target: mut objid.Id = objid.id_none()+ if cached is some ce {+ if cache_matches(ce, info, executable, now_ms, cache.written_ms) {+ target = copy_id(ce.target)+ reuse = true+ }+ }+ if !reuse {+ val fs3: str.StringView = files.join(dir, str.from_cstr(name_c))+ val data_opt = files.read_all(fs3)+ files.free_path(fs3)+ match data_opt {+ some data => {+ target = add_blob_data(tx, data.ptr, data.len)+ files.free_buffer(data)+ }+ none => {+ failed = true+ }+ }+ }+ if !failed {+ @append(new_cache, new_entry(bytes.Bytes.dup(path), info, executable, target))+ val kind: mut u8 = tree.KIND_FILE+ if executable {+ kind = tree.KIND_EXECUTABLE+ }+ @append(entries, tree.entry(bytes.Bytes.dup(name), kind, target))+ }+ files.free_buffer(path)+ }+ }+ files.free_names(names_list)+ files.free_path(dir)++ val out: mut option[objid.Id] = none+ if !failed {+ if @len(entries) > 0 {+ val encoded = tree.encode(entries)+ match encoded {+ ok body => {+ val id: objid.Id = txn.add_object(tx, types.TREE, body)+ out = some(copy_id(id))+ if id.ptr != none {+ val ip: mut ref void = id.ptr as ref void+ @free(ip)+ }+ }+ err _ => {+ failed = true+ }+ }+ }+ }+ for e in entries {+ if e.name.ptr != none {+ val np: mut ref void = e.name.ptr as ref void+ @free(np)+ }+ if e.target.ptr != none {+ val tp2: mut ref void = e.target.ptr as ref void+ @free(tp2)+ }+ val ep: mut ref void = e as ref void+ @free(ep)+ }+ @listfree(entries)+ if have_old {+ tree.free_tree(old)+ }+ free_local(local, keep)+ if failed {+ return none+ }+ return out+}++fn empty_tree_id(tx: mut ref txn.Txn) objid.Id = trust {+ val t: tree.Tree = tree.empty()+ val encoded = tree.encode(t.entries)+ val body: mut bytes.Bytes = bytes.empty()+ match encoded {+ ok b => {+ body = b+ }+ err _ => {+ return objid.id(none)+ }+ }+ val id: objid.Id = txn.add_object(tx, types.TREE, body)+ @listfree(t.entries)+ return id+}++fn remove_wc_head(v: mut ref view.View, id: objid.Id) void = trust {+ viewops.remove_head(v, id)+}++/// Snapshot the working tree into `@`. Returns 0 on success.+pub fn run(repo: layout.Repo) i32 = trust {+ val tx_opt = txn.begin(repo)+ val tx: mut ref txn.Txn = none+ match tx_opt {+ some t => {+ tx = t+ }+ none => {+ stdio.eprint("vn: 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()+ val have_wc: mut bool = false+ if wc_opt is some id {+ wc = id+ have_wc = true+ }++ val cbody: mut bytes.Bytes = bytes.empty()+ val c: mut ref commit.Commit = none+ val old_tree: mut option[objid.Id] = none+ if have_wc {+ val body_opt = state.read_body(st.handles, wc, types.COMMIT)+ match body_opt {+ some b => {+ cbody = b+ val decoded = commit.decode(cbody)+ match decoded {+ ok x => {+ c = x+ old_tree = some(copy_id(c.root_tree))+ }+ err _ => {+ stdio.eprint("vn: corrupt working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ if wc.ptr != none {+ val wp: mut ref void = wc.ptr as ref void+ @free(wp)+ }+ return 1+ }+ }+ }+ none => {+ stdio.eprint("vn: missing working-copy commit\n", {})+ store.close(st)+ txn.abort(tx)+ if wc.ptr != none {+ val wp2: mut ref void = wc.ptr as ref void+ @free(wp2)+ }+ return 1+ }+ }+ }++ val root: str.StringView = layout.root_view(repo)+ val rules: mut ignore.Rules = ignore.empty()+ ignore.load_root(rules, root)+ val cache: Cache = load_cache(repo)+ val new_cache: mut list[ref CacheEntry] = lists.new[ref CacheEntry]()+ val now_ms: i64 = time.unix_now_millis()+ val built = build_dir(+ tx,+ root,+ st.handles,+ bytes.empty(),+ old_tree,+ rules,+ cache,+ new_cache,+ now_ms+ )+ val new_root: mut objid.Id = objid.id_none()+ val build_failed: mut bool = false+ match built {+ some id => {+ new_root = id+ }+ none => {+ if @len(new_cache) > 0 {+ // Files were produced before a failure; treat as an error.+ build_failed = true+ } else {+ new_root = empty_tree_id(tx)+ }+ }+ }+ if objid.Id.is_none(new_root) && !build_failed {+ stdio.eprint("vn: failed to build working-copy tree\n", {})+ build_failed = true+ }+ if build_failed {+ store.close(st)+ txn.abort(tx)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot {+ if ot.ptr != none {+ val op: mut ref void = ot.ptr as ref void+ @free(op)+ }+ }+ if wc.ptr != none {+ val wp3: mut ref void = wc.ptr as ref void+ @free(wp3)+ }+ ignore.free(rules)+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return 1+ }++ val unchanged: mut bool = false+ if old_tree is some ot2 {+ if objid.Id.eql(ot2, new_root) {+ unchanged = true+ }+ }++ if unchanged {+ store.close(st)+ txn.abort(tx)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot3 {+ if ot3.ptr != none {+ val op2: mut ref void = ot3.ptr as ref void+ @free(op2)+ }+ }+ if wc.ptr != none {+ val wp4: mut ref void = wc.ptr as ref void+ @free(wp4)+ }+ if new_root.ptr != none {+ val np2: mut ref void = new_root.ptr as ref void+ @free(np2)+ }+ ignore.free(rules)+ val sorted: mut Cache = Cache{entries: new_cache, written_ms: now_ms}+ sort_cache(sorted.entries)+ val _ = save_cache(repo, sorted)+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return 0+ }++ val committer: prim.Sig = identity.signature(repo)+ val author: mut prim.Sig = committer+ val parents: mut list[objid.Id] = lists.new[objid.Id]()+ val change_id: mut objid.ChangeId = objid.change_id(none)+ val message: mut bytes.Bytes = bytes.empty()+ if c != none {+ author = c.author+ for p in c.parents {+ @append(parents, copy_id(p))+ }+ change_id = c.change_id+ message = c.message+ } else {+ val cid: ref u8 = @alloc(16) as ref u8+ 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 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+ nc.parents = parents+ nc.root_tree = new_root+ nc.change_id = change_id+ nc.author = author+ nc.committer = committer+ nc.message = message+ nc.renames_state = commit.RENAMES_RECORDED+ nc.renames = renames+ nc.extra = extra+ val encoded: bytes.Bytes = commit.encode(nc)+ val new_commit: objid.Id = txn.add_object(tx, types.COMMIT, encoded)+ @listfree(nc.parents)+ @listfree(nc.renames)+ @listfree(nc.extra)+ @free(nc as ref void)++ if have_wc {+ remove_wc_head(tx.view, wc)+ }+ viewops.set_workspace(tx.view, new_commit)+ viewops.rebuild_heads(tx.view)++ val status: i32 = txn.finish(tx, bytes.bytes(c"snapshot", 8))+ if status == 0 {+ val _ = gitmap.mark_native(repo, new_commit)+ }+ store.close(st)+ if c != none {+ commit.free_commit(c)+ }+ if cbody.ptr != none {+ files.free_buffer(cbody)+ }+ if old_tree is some ot4 {+ if ot4.ptr != none {+ val op3: mut ref void = ot4.ptr as ref void+ @free(op3)+ }+ }+ if wc.ptr != none {+ val wp5: mut ref void = wc.ptr as ref void+ @free(wp5)+ }+ if new_root.ptr != none {+ val np3: mut ref void = new_root.ptr as ref void+ @free(np3)+ }+ if new_commit.ptr != none {+ val cp2: mut ref void = new_commit.ptr as ref void+ @free(cp2)+ }+ identity.free_sig(committer)+ // Author/message/change ID fields borrowed from the old commit body (freed+ // above) or the freshly allocated random ID.+ if c == none && change_id.ptr != none {+ val cip: mut ref void = change_id.ptr as ref void+ @free(cip)+ }+ ignore.free(rules)+ if status == 0 {+ val sorted2: mut Cache = Cache{entries: new_cache, written_ms: now_ms}+ sort_cache(sorted2.entries)+ val _ = save_cache(repo, sorted2)+ }+ free_cache(cache)+ for e in new_cache {+ free_entry(e)+ }+ @listfree(new_cache)+ return status+}