navid/veins / commit

cba7a7a323b2

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

parents: 1be23d628109

Browse files at this commit · Download source

all: fixes
--- /dev/null+++ b/src/src/cli/checkout_cmd.sx@@ -0,0 +1,29 @@+/// `vn checkout [rev]`: materialize a revision into the working directory.++val str      = use("std/string")+val stdio    = use("std/stdio")+val bytes    = use("../core/bytes.sx")+val layout   = use("../store/layout.sx")+val checkout = use("../worktree/checkout.sx")++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val rev: mut bytes.Bytes = bytes.empty()+    if start < @len(args) {+        val r_opt = @get(args, start)+        if r_opt is some r {+            rev = bytes.from_cstr(r)+        }+    }+    val repo_opt = layout.discover(str.from_cstr(c"."))+    match repo_opt {+        some repo => {+            val status: i32 = checkout.run(repo, rev)+            layout.free_repo(repo)+            return status+        }+        none => {+            stdio.eprint("vn: not a vein repository\n", {})+            return 1+        }+    }+}--- /dev/null+++ b/src/src/cli/git_cmd.sx@@ -0,0 +1,80 @@+/// `vn git`: the git bridge. M1 provides `import`.++val str    = use("std/string")+val stdio  = use("std/stdio")+val layout = use("../store/layout.sx")+val mirror = use("../git/mirror.sx")+val import = use("../git/import.sx")++pub fn run(args: list[ref u8], start: usize) i32 = trust {+    val sub_opt = @get(args, start)+    val sub: mut ref u8 = none+    match sub_opt {+        some s => {+            sub = s+        }+        none => {+            stdio.eprint("vn: expected a git subcommand (import)\n", {})+            return 1+        }+    }+    if @strcmp(sub, c"import") != 0 {+        stdio.eprint("vn: unknown git subcommand: {s}\n", {str.from_cstr(sub)})+        return 1+    }+    return run_import(args, start + 1)+}++fn run_import(args: list[ref u8], start: usize) i32 = trust {+    val repo_path: mut str.StringView = str.from_cstr(c".")+    val source: mut option[str.StringView] = none+    val i: mut usize = start+    for i < @len(args) {+        val arg_opt = @get(args, i)+        if arg_opt is some a {+            val av: str.StringView = str.from_cstr(a)+            if @strcmp(av.ptr, c"--source") == 0 {+                if i + 1 >= @len(args) {+                    stdio.eprint("vn: --source requires a path\n", {})+                    return 1+                }+                val src_opt = @get(args, i + 1)+                if src_opt is some s {+                    source = some str.from_cstr(s)+                }+                i = i + 2+            } else {+                repo_path = av+                i+++            }+        } else {+            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+        }+    }+    match source {+        some src => {+            val prepared = mirror.prepare(repo, src)+            if prepared != 0 {+                stdio.eprint("vn: cannot prepare git mirror (code {d})\n", {prepared})+                layout.free_repo(repo)+                return 1+            }+        }+        none => {+        }+    }+    val status: i32 = import.run(repo)+    layout.free_repo(repo)+    return status+}--- a/src/src/cli/init_cmd.sx+++ b/src/src/cli/init_cmd.sx@@ -1,19 +1,37 @@-/// `vn init`: create the on-disk repository skeleton.+/// `vn init`: create the on-disk repository skeleton and optionally import git.  val str    = use("std/string") val stdio  = use("std/stdio") val layout = use("../store/layout.sx")+val mirror = use("../git/mirror.sx")+val import = use("../git/import.sx") -pub fn run(path: str.StringView) i32 = {+pub fn run(path: str.StringView, source: option[str.StringView]) i32 = trust {     val result = layout.init(path)     match result {         ok repo => {-            trust stdio.print("initialized vein repository at {s}\n", {layout.root_view(repo)})+            stdio.print("initialized vein repository at {s}\n", {layout.root_view(repo)})+            val mut_source = source+            match mut_source {+                some src => {+                    val prepared: i32 = mirror.prepare(repo, src)+                    if prepared != 0 {+                        stdio.eprint("vn: cannot prepare git mirror (code {d})\n", {prepared})+                        layout.free_repo(repo)+                        return 1+                    }+                    val status: i32 = import.run(repo)+                    layout.free_repo(repo)+                    return status+                }+                none => {+                }+            }             layout.free_repo(repo)             return 0         }         err code => {-            trust stdio.eprint("vn: init failed with code {d}\n", {code})+            stdio.eprint("vn: init failed with code {d}\n", {code})             return 1         }     }--- /dev/null+++ b/src/src/git/format.sx@@ -0,0 +1,664 @@+/// Parsing and canonical serialization of git commit, tree, and tag objects.++val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val prim   = use("../core/primitives.sx")+val lists  = use("../core/lists.sx")+val tree   = use("../object/tree.sx")+val object = use("object.sx")++pub type RawTreeEntry = {+    mode: mut bytes.Bytes+    name: mut bytes.Bytes+    oid: mut bytes.Bytes+    canonical: mut bool+}++pub type ParsedTree = {+    entries: mut list[ref RawTreeEntry]+    canonical: mut bool+}++pub type ParsedTag = {+    target: mut bytes.Bytes+    target_kind: mut u8+}++pub type ParsedCommit = {+    tree: mut bytes.Bytes+    parents: mut list[bytes.Bytes]+    author: mut prim.Sig+    committer: mut prim.Sig+    message: mut bytes.Bytes+    extras: mut list[ref prim.KeyValue]+    change_id: mut bytes.Bytes+    canonical: mut bool+}++fn hex_digit(n: u8) u8 = trust {+    if n < 10 {+        return (48 + n) as u8+    }+    return (87 + n) as u8+}++fn hex_value(c: u8) i32 = trust {+    if c >= 48 && c <= 57 {+        return (c - 48) as i32+    }+    if c >= 97 && c <= 102 {+        return (c - 87) as i32+    }+    if c >= 65 && c <= 70 {+        return (c - 55) as i32+    }+    return -1+}++pub fn oid_from_hex(hex: bytes.Bytes) option[bytes.Bytes] = trust {+    if hex.len != 40 {+        return none+    }+    val out: ref u8 = @alloc(20) as ref u8+    val i: mut usize = 0+    for i < 20 {+        val hi: i32 = hex_value(bytes.Bytes.at(hex, i * 2))+        val lo: i32 = hex_value(bytes.Bytes.at(hex, i * 2 + 1))+        if hi < 0 || lo < 0 {+            @free(out as ref void)+            return none+        }+        @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))+        i+++    }+    return some bytes.bytes(out, 20)+}++fn put_hex_id(b: mut buf.Buf, oid: bytes.Bytes) void = trust {+    val i: mut usize = 0+    for i < 20 {+        val v: u8 = bytes.Bytes.at(oid, i)+        buf.Buf.put_u8(b, hex_digit(v >> 4))+        buf.Buf.put_u8(b, hex_digit(v & 15))+        i+++    }+}++fn parse_u64(text: bytes.Bytes) option[u64] = trust {+    if text.len == 0 {+        return none+    }+    val v: mut u64 = 0+    val i: mut usize = 0+    for i < text.len {+        val c: u8 = bytes.Bytes.at(text, i)+        if c < 48 || c > 57 {+            return none+        }+        v = v * 10 + (c - 48) as u64+        i+++    }+    return some v+}++fn parse_i64(text: bytes.Bytes) option[i64] = trust {+    if text.len == 0 {+        return none+    }+    val negative: bool = bytes.Bytes.at(text, 0) == 45+    val start: mut usize = 0+    if negative {+        start = 1+    }+    val mag_opt = parse_u64(bytes.Bytes.slice(text, start, text.len))+    val mag: mut u64 = 0+    match mag_opt {+        some v => {+            mag = v+        }+        none => {+            return none+        }+    }+    if mag > 9223372036854775807 {+        return none+    }+    val signed: mut i64 = mag as i64+    if negative {+        signed = 0 - signed+    }+    return some signed+}++fn parse_tz(text: bytes.Bytes) option[i16] = trust {+    if text.len != 5 {+        return none+    }+    val sign: u8 = bytes.Bytes.at(text, 0)+    if sign != 43 && sign != 45 {+        return none+    }+    val hours_opt = parse_u64(bytes.Bytes.slice(text, 1, 3))+    val mins_opt = parse_u64(bytes.Bytes.slice(text, 3, 5))+    val hours: mut u64 = 0+    val mins: mut u64 = 0+    match hours_opt {+        some v => {+            hours = v+        }+        none => {+            return none+        }+    }+    match mins_opt {+        some v => {+            mins = v+        }+        none => {+            return none+        }+    }+    val total: i64 = (hours * 60 + mins) as i64+    if total > 32767 {+        return none+    }+    val tz: mut i16 = total as i16+    if sign == 45 {+        tz = 0 - tz+    }+    return some tz+}++fn last_index_of(value: bytes.Bytes, needle: u8, end: usize) i64 = trust {+    val i: mut i64 = end as i64 - 1+    for i >= 0 {+        if bytes.Bytes.at(value, i as usize) == needle {+            return i+        }+        i--+    }+    return -1+}++/// Parse "Name <email> seconds timezone".+pub fn parse_sig(value: bytes.Bytes) option[prim.Sig] = trust {+    val tz_space: i64 = last_index_of(value, 32, value.len)+    if tz_space < 0 {+        return none+    }+    val sec_space: i64 = last_index_of(value, 32, tz_space as usize)+    if sec_space < 0 {+        return none+    }+    val sec_opt = parse_i64(bytes.Bytes.slice(value, sec_space as usize + 1, tz_space as usize))+    val tz_opt = parse_tz(bytes.Bytes.slice(value, tz_space as usize + 1, value.len))+    val seconds: mut i64 = 0+    val tz: mut i16 = 0+    match sec_opt {+        some v => {+            seconds = v+        }+        none => {+            return none+        }+    }+    match tz_opt {+        some v => {+            tz = v+        }+        none => {+            return none+        }+    }+    val ident: bytes.Bytes = bytes.Bytes.slice(value, 0, sec_space as usize)+    val lt: i64 = last_index_of(ident, 60, ident.len)+    if lt < 0 {+        return none+    }+    val gt: i64 = last_index_of(ident, 62, ident.len)+    if gt <= lt {+        return none+    }+    val name_end: usize = lt as usize+    val email_start: usize = lt as usize + 1+    val email_end: usize = gt as usize+    val raw_name: bytes.Bytes = bytes.Bytes.slice(ident, 0, name_end)+    val name: mut bytes.Bytes = raw_name+    if raw_name.len > 0 && bytes.Bytes.at(raw_name, raw_name.len - 1) == 32 {+        name = bytes.Bytes.slice(raw_name, 0, raw_name.len - 1)+    }+    return some prim.Sig{+        name: name,+        email: bytes.Bytes.slice(ident, email_start, email_end),+        seconds: seconds,+        tz_min: tz+    }+}++fn put_sig(b: mut buf.Buf, sig: prim.Sig) void = trust {+    buf.Buf.put_bytes(b, sig.name)+    buf.Buf.put_u8(b, 32)+    buf.Buf.put_u8(b, 60)+    buf.Buf.put_bytes(b, sig.email)+    buf.Buf.put_u8(b, 62)+    buf.Buf.put_u8(b, 32)+    val sec_text: ref u8 = @fmtalloc("{d}", {sig.seconds})+    buf.Buf.put_bytes(b, bytes.from_cstr(sec_text))+    @free(sec_text as ref void)+    buf.Buf.put_u8(b, 32)+    val minutes: i64 = sig.tz_min as i64+    val abs_min: mut i64 = minutes+    if minutes < 0 {+        buf.Buf.put_u8(b, 45)+        abs_min = -minutes+    } else {+        buf.Buf.put_u8(b, 43)+    }+    val hh: i64 = abs_min / 60+    val mm: i64 = abs_min % 60+    buf.Buf.put_u8(b, (48 + hh / 10) as u8)+    buf.Buf.put_u8(b, (48 + hh % 10) as u8)+    buf.Buf.put_u8(b, (48 + mm / 10) as u8)+    buf.Buf.put_u8(b, (48 + mm % 10) as u8)+}++fn find_blank_line(data: bytes.Bytes) i64 = trust {+    if data.len < 2 {+        return -1+    }+    val i: mut usize = 0+    for i + 1 < data.len {+        if bytes.Bytes.at(data, i) == 10 && bytes.Bytes.at(data, i + 1) == 10 {+            return i as i64+        }+        i+++    }+    return -1+}++fn starts_with_space(line: bytes.Bytes) bool = trust {+    return line.len > 0 && bytes.Bytes.at(line, 0) == 32+}++fn parse_header_line(line: bytes.Bytes) option[prim.KeyValue] = trust {+    val space: mut usize = 0+    for space < line.len && bytes.Bytes.at(line, space) != 32 {+        space+++    }+    if space == 0 || space >= line.len {+        return none+    }+    val key: bytes.Bytes = bytes.Bytes.slice(line, 0, space)+    val value: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)+    return some prim.KeyValue{key: key, value: value}+}++fn new_kv(key: bytes.Bytes, value: bytes.Bytes) ref prim.KeyValue = trust {+    val kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+    kv.key = key+    kv.value = value+    return kv+}++fn find_line_end(data: bytes.Bytes, start: usize, end: usize) usize = trust {+    val i: mut usize = start+    for i < end && bytes.Bytes.at(data, i) != 10 {+        i+++    }+    return i+}++pub fn parse_commit(body: bytes.Bytes) option[ref ParsedCommit] = trust {+    val blank: i64 = find_blank_line(body)+    if blank < 0 {+        return none+    }+    val header_end: usize = blank as usize+    val message: bytes.Bytes = bytes.Bytes.slice(body, header_end + 2, body.len)+    val out: mut ref ParsedCommit = @alloc(@sizeof(ParsedCommit)) as ref ParsedCommit+    out.tree = bytes.empty()+    out.parents = lists.new[bytes.Bytes]()+    out.author = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}+    out.committer = prim.Sig{name: bytes.empty(), email: bytes.empty(), seconds: 0, tz_min: 0}+    out.message = message+    out.extras = lists.new[ref prim.KeyValue]()+    out.change_id = bytes.empty()+    out.canonical = true++    val last_extra: mut ref prim.KeyValue = none+    val last_extra_start: mut usize = 0+    val pos: mut usize = 0+    for pos < header_end {+        val line_end: usize = find_line_end(body, pos, header_end)+        val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)+        if starts_with_space(line) {+            if last_extra == none {+                out.canonical = false+            } else {+                last_extra.value = bytes.Bytes.slice(body, last_extra_start, line_end)+            }+        } else {+            last_extra = none+            val kv_opt = parse_header_line(line)+            match kv_opt {+                some kv => {+                    if bytes.Bytes.eql(kv.key, bytes.bytes(c"tree", 4)) {+                        val oid_opt = oid_from_hex(kv.value)+                        match oid_opt {+                            some oid => {+                                out.tree = oid+                            }+                            none => {+                                out.canonical = false+                            }+                        }+                    } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"parent", 6)) {+                        val oid_opt2 = oid_from_hex(kv.value)+                        match oid_opt2 {+                            some oid => {+                                @append(out.parents, oid)+                            }+                            none => {+                                out.canonical = false+                            }+                        }+                    } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"author", 6)) {+                        val sig_opt = parse_sig(kv.value)+                        match sig_opt {+                            some sig => {+                                out.author = sig+                            }+                            none => {+                                out.canonical = false+                            }+                        }+                    } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"committer", 9)) {+                        val sig_opt2 = parse_sig(kv.value)+                        match sig_opt2 {+                            some sig => {+                                out.committer = sig+                            }+                            none => {+                                out.canonical = false+                            }+                        }+                    } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"vein-change-id", 14)) {+                        if kv.value.len == 32 {+                            val cid: ref u8 = @alloc(16) as ref u8+                            val j: mut usize = 0+                            for j < 16 {+                                val hi: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2))+                                val lo: i32 = hex_value(bytes.Bytes.at(kv.value, j * 2 + 1))+                                if hi < 0 || lo < 0 {+                                    @free(cid as ref void)+                                    out.canonical = false+                                    break+                                }+                                @store8(@ptradd(cid, j as i64), ((hi * 16 + lo) as u8))+                                j+++                            }+                            if j == 16 {+                                out.change_id = bytes.bytes(cid, 16)+                            }+                        } else {+                            out.canonical = false+                        }+                    } else {+                        val extra: ref prim.KeyValue = new_kv(kv.key, kv.value)+                        @append(out.extras, extra)+                        last_extra = extra+                        last_extra_start = pos + kv.key.len + 1+                    }+                }+                none => {+                    out.canonical = false+                }+            }+        }+        pos = line_end + 1+    }+    return some out+}++pub fn free_parsed_commit(c: ref ParsedCommit) void = trust {+    for p in c.parents {+        if p.ptr != none {+            val pp: mut ref void = p.ptr as ref void+            @free(pp)+        }+    }+    @listfree(c.parents)+    if c.change_id.ptr != none {+        @free(c.change_id.ptr as ref void)+    }+    for kv in c.extras {+        val kp: mut ref void = kv as ref void+        @free(kp)+    }+    @listfree(c.extras)+    @free(c as ref void)+}++pub fn serialize_commit(c: ref ParsedCommit) bytes.Bytes = trust {+    val b: mut buf.Buf = buf.new(c.message.len + 256)+    buf.Buf.put_bytes(b, bytes.bytes(c"tree ", 5))+    put_hex_id(b, c.tree)+    buf.Buf.put_u8(b, 10)+    for p in c.parents {+        buf.Buf.put_bytes(b, bytes.bytes(c"parent ", 7))+        put_hex_id(b, p)+        buf.Buf.put_u8(b, 10)+    }+    buf.Buf.put_bytes(b, bytes.bytes(c"author ", 7))+    put_sig(b, c.author)+    buf.Buf.put_u8(b, 10)+    buf.Buf.put_bytes(b, bytes.bytes(c"committer ", 10))+    put_sig(b, c.committer)+    buf.Buf.put_u8(b, 10)+    for kv in c.extras {+        buf.Buf.put_bytes(b, kv.key)+        buf.Buf.put_u8(b, 32)+        buf.Buf.put_bytes(b, kv.value)+        buf.Buf.put_u8(b, 10)+    }+    buf.Buf.put_u8(b, 10)+    buf.Buf.put_bytes(b, c.message)+    val out: bytes.Bytes = bytes.Bytes.dup(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++pub fn canonical_commit_bytes(body: bytes.Bytes) option[bytes.Bytes] = trust {+    val parsed_opt = parse_commit(body)+    match parsed_opt {+        some c => {+            val out: bytes.Bytes = serialize_commit(c)+            val same: bool = bytes.Bytes.eql(out, body)+            free_parsed_commit(c)+            if !same {+                val op: mut ref void = out.ptr as ref void+                @free(op)+                return none+            }+            return some out+        }+        none => {+            return none+        }+    }+}++pub fn parse_tree(body: bytes.Bytes) option[ref ParsedTree] = trust {+    val out: mut ref ParsedTree = @alloc(@sizeof(ParsedTree)) as ref ParsedTree+    out.entries = lists.new[ref RawTreeEntry]()+    out.canonical = true+    val pos: mut usize = 0+    for pos < body.len {+        val mode_start: usize = pos+        for pos < body.len && bytes.Bytes.at(body, pos) != 32 {+            pos+++        }+        if pos >= body.len {+            out.canonical = false+            break+        }+        val mode: bytes.Bytes = bytes.Bytes.slice(body, mode_start, pos)+        pos+++        val name_start: usize = pos+        for pos < body.len && bytes.Bytes.at(body, pos) != 0 {+            pos+++        }+        if pos >= body.len {+            out.canonical = false+            break+        }+        val name: bytes.Bytes = bytes.Bytes.slice(body, name_start, pos)+        pos+++        if pos + 20 > body.len {+            out.canonical = false+            break+        }+        val oid: bytes.Bytes = bytes.Bytes.slice(body, pos, pos + 20)+        pos = pos + 20+        val e: mut ref RawTreeEntry = @alloc(@sizeof(RawTreeEntry)) as ref RawTreeEntry+        e.mode = mode+        e.name = name+        e.oid = oid+        e.canonical = canonical_mode(mode)+        if !e.canonical {+            out.canonical = false+        }+        @append(out.entries, e)+    }+    if pos != body.len {+        out.canonical = false+    }+    return some out+}++fn canonical_mode(mode: bytes.Bytes) bool = trust {+    if bytes.Bytes.eql(mode, bytes.bytes(c"100644", 6)) {+        return true+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {+        return true+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {+        return true+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5)) {+        return true+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {+        return true+    }+    return false+}++pub fn mode_kind(mode: bytes.Bytes) u8 = trust {+    if bytes.Bytes.eql(mode, bytes.bytes(c"40000", 5))+        || bytes.Bytes.eql(mode, bytes.bytes(c"040000", 6)) {+        return tree.KIND_SUBTREE+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"120000", 6)) {+        return tree.KIND_SYMLINK+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"160000", 6)) {+        return tree.KIND_SUBMODULE+    }+    if bytes.Bytes.eql(mode, bytes.bytes(c"100755", 6)) {+        return tree.KIND_EXECUTABLE+    }+    return tree.KIND_FILE+}++fn entry_at(entries: list[ref RawTreeEntry], i: usize) mut ref RawTreeEntry = trust {+    val o = @get(entries, i)+    if o is some e {+        return e+    }+    assert false+    return none+}+++/// Sort entries by plain name (vein's tree order).+pub fn sort_raw_entries(entries: mut list[ref RawTreeEntry]) void = trust {+    val n: usize = @len(entries)+    val i: mut usize = 1+    for i < n {+        val cur = entry_at(entries, i)+        val j: mut usize = i+        for j > 0 {+            val prev = entry_at(entries, j - 1)+            if bytes.Bytes.cmp(prev.name, cur.name) <= 0 {+                break+            }+            @set(entries, j, prev)+            j--+        }+        @set(entries, j, cur)+        i+++    }+}++pub fn free_parsed_tree(t: ref ParsedTree) void = trust {+    for e in t.entries {+        val ep: mut ref void = e as ref void+        @free(ep)+    }+    @listfree(t.entries)+    @free(t as ref void)+}++pub fn parse_tag(body: bytes.Bytes) option[ParsedTag] = trust {+    val out: mut ref ParsedTag = @alloc(@sizeof(ParsedTag)) as ref ParsedTag+    out.target = bytes.empty()+    out.target_kind = 0+    val pos: mut usize = 0+    for pos < body.len {+        val line_end: usize = find_line_end(body, pos, body.len)+        val line: bytes.Bytes = bytes.Bytes.slice(body, pos, line_end)+        if line.len == 0 {+            break+        }+        val kv_opt = parse_header_line(line)+        match kv_opt {+            some kv => {+                if bytes.Bytes.eql(kv.key, bytes.bytes(c"object", 6)) {+                    val oid_opt = oid_from_hex(kv.value)+                    match oid_opt {+                        some oid => {+                            out.target = oid+                        }+                        none => {+                        }+                    }+                } elif bytes.Bytes.eql(kv.key, bytes.bytes(c"type", 4)) {+                    if bytes.Bytes.eql(kv.value, bytes.bytes(c"commit", 6)) {+                        out.target_kind = object.KIND_COMMIT+                    } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tree", 4)) {+                        out.target_kind = object.KIND_TREE+                    } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"blob", 4)) {+                        out.target_kind = object.KIND_BLOB+                    } elif bytes.Bytes.eql(kv.value, bytes.bytes(c"tag", 3)) {+                        out.target_kind = object.KIND_TAG+                    }+                }+            }+            none => {+            }+        }+        pos = line_end + 1+    }+    return some out+}++pub fn free_parsed_tag(t: ref ParsedTag) void = trust {+    if t.target.ptr != none {+        val tp: mut ref void = t.target.ptr as ref void+        @free(tp)+    }+    val tq: mut ref void = t as ref void+    @free(tq)+}--- /dev/null+++ b/src/src/git/import.sx@@ -0,0 +1,1273 @@+lib "z"++/// Import a git object graph into the vein store and record an operation.++val str       = use("std/string")+val stdio     = use("std/stdio")+val os        = use("std/os")+val time      = use("std/time")+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 b3        = use("../crypto/blake3.sx")+val objid     = use("../object/id.sx")+val types     = use("../object/types.sx")+val tree      = use("../object/tree.sx")+val blob      = use("../object/blob.sx")+val commit    = use("../object/commit.sx")+val operation = use("../object/operation.sx")+val view      = use("../object/view.sx")+val raw       = use("../object/raw.sx")+val layout    = use("../store/layout.sx")+val store     = use("../store/store.sx")+val state     = use("../store/state.sx")+val files     = use("../io/files.sx")+val object    = use("object.sx")+val format    = use("format.sx")+val refs      = use("refs.sx")+val oidmap    = use("oidmap.sx")+val gitmap    = use("map.sx")++pub type ImportStats = {+    commits: mut usize+    trees: mut usize+    blobs: mut usize+}++type ImportNamedTarget = {+    name: mut bytes.Bytes+    oid: mut bytes.Bytes+}++type ImportCommitRec = {+    oid: mut bytes.Bytes+    body: mut bytes.Bytes+    parsed: mut ref format.ParsedCommit+}++type ImportRawSave = {+    id: mut objid.Id+    body: mut bytes.Bytes+}++type ImportCtx = {+    git: object.GitRepo+    commits_map: mut oidmap.OidMap+    trees_map: mut oidmap.OidMap+    blobs_map: mut oidmap.OidMap+    objects: mut list[ref raw.RawObject]+    raw_saves: mut list[ref ImportRawSave]+    new_commits: mut usize+    new_trees: mut usize+    new_blobs: mut usize+    object_bytes: mut usize+}++fn put_usize(map: mut oidmap.OidMap, oid: bytes.Bytes, value: usize) void = trust {+    val v: ref u8 = @alloc(8) as ref u8+    @store64(v as ref void, value as i64)+    oidmap.put(map, oid, bytes.bytes(v, 8))+    @free(v as ref void)+}++fn get_usize(map: oidmap.OidMap, oid: bytes.Bytes) option[usize] = trust {+    val got = oidmap.get(map, oid)+    match got {+        some v => {+            return some (@load64(v.ptr as ref void) as usize)+        }+        none => {+            return none+        }+    }+}++fn get_id(map: oidmap.OidMap, oid: bytes.Bytes) option[objid.Id] = trust {+    val got = oidmap.get(map, oid)+    match got {+        some v => {+            return some objid.id(v.ptr)+        }+        none => {+            return none+        }+    }+}++fn put_id(map: mut oidmap.OidMap, oid: bytes.Bytes, id: objid.Id) void = trust {+    oidmap.put(map, oid, bytes.bytes(id.ptr, 32))+}++fn dup_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 append_object(ctx: mut ImportCtx, kind: u8, body: bytes.Bytes) objid.Id = trust {+    val id: objid.Id = objid.object_id(kind, body)+    ctx.object_bytes = ctx.object_bytes + body.len+    @append(ctx.objects, raw.raw(kind, body))+    return id+}++fn derive_change_id(oid: bytes.Bytes) objid.ChangeId = trust {+    val b: mut buf.Buf = buf.new(48)+    buf.Buf.put_raw(b, c"vein/change", 11)+    buf.Buf.put_bytes(b, oid)+    val out: ref u8 = @alloc(32) as ref u8+    b3.hash(b.ptr, b.len, out)+    buf.Buf.free(b)+    return objid.change_id(out)+}++fn peel_to_commit(git: object.GitRepo, start: bytes.Bytes) option[bytes.Bytes] = trust {+    val current: mut bytes.Bytes = bytes.Bytes.dup(start)+    for {+        val obj_opt = object.read(git, current)+        val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+        match obj_opt {+            ok o => {+                obj = o+            }+            err _ => {+                val cp: mut ref void = current.ptr as ref void+                @free(cp)+                return none+            }+        }+        if obj.kind == object.KIND_COMMIT {+            object.free_object(obj)+            return some current+        }+        if obj.kind != object.KIND_TAG {+            object.free_object(obj)+            val cp2: mut ref void = current.ptr as ref void+            @free(cp2)+            return none+        }+        val parsed_opt = format.parse_tag(obj.body)+        val parsed: mut ref format.ParsedTag = none+        match parsed_opt {+            some t => {+                parsed = t+            }+            none => {+                object.free_object(obj)+                val cp3: mut ref void = current.ptr as ref void+                @free(cp3)+                return none+            }+        }+        val next: mut bytes.Bytes = bytes.empty()+        if parsed.target.ptr != none {+            next = bytes.Bytes.dup(parsed.target)+        }+        format.free_parsed_tag(parsed)+        object.free_object(obj)+        val cp4: mut ref void = current.ptr as ref void+        @free(cp4)+        if next.ptr == none {+            return none+        }+        current = next+    }+    return none+}++fn import_blob(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {+    val existing = get_id(ctx.blobs_map, oid)+    if existing is some id {+        return some id+    }+    val obj_opt = object.read(ctx.git, oid)+    val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+    match obj_opt {+        ok o => {+            obj = o+        }+        err _ => {+            return none+        }+    }+    if obj.kind != object.KIND_BLOB {+        object.free_object(obj)+        return none+    }+    val built: ref blob.BlobBuild = blob.build(obj.body.ptr, obj.body.len)+    val root: objid.Id = blob.root_id(built)+    for ro in built.objects {+        ctx.object_bytes = ctx.object_bytes + ro.body.len+        @append(ctx.objects, ro)+    }+    @listfree(built.objects)+    put_id(ctx.blobs_map, oid, root)+    ctx.new_blobs+++    val out: objid.Id = dup_id(root)+    val root_ptr: mut ref void = built.root as ref void+    @free(root_ptr)+    @free(built as ref void)+    object.free_object(obj)+    return some out+}++fn import_tree(ctx: mut ImportCtx, oid: bytes.Bytes) option[objid.Id] = trust {+    val existing = get_id(ctx.trees_map, oid)+    if existing is some id {+        return some id+    }+    val obj_opt = object.read(ctx.git, oid)+    val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+    match obj_opt {+        ok o => {+            obj = o+        }+        err _ => {+            return none+        }+    }+    if obj.kind != object.KIND_TREE {+        object.free_object(obj)+        return none+    }+    val parsed_opt = format.parse_tree(obj.body)+    val parsed: mut ref format.ParsedTree = none+    match parsed_opt {+        some t => {+            parsed = t+        }+        none => {+            object.free_object(obj)+            return none+        }+    }+    format.sort_raw_entries(parsed.entries)+    val entries: mut list[ref tree.TreeEntry] = lists.new[ref tree.TreeEntry]()+    val failed: mut bool = false+    for e in parsed.entries {+        val kind: u8 = format.mode_kind(e.mode)+        val target: mut objid.Id = objid.id_none()+        if kind == tree.KIND_SUBTREE {+            val child = import_tree(ctx, e.oid)+            match child {+                some id => {+                    target = id+                }+                none => {+                    failed = true+                }+            }+        } elif kind == tree.KIND_SUBMODULE {+            val out: ref u8 = @alloc(32) as ref u8+            @memset(out as ref void, 0, 32)+            @memcpy(out as ref void, e.oid.ptr as ref void, 20)+            target = objid.id(out)+        } else {+            val child2 = import_blob(ctx, e.oid)+            match child2 {+                some id2 => {+                    target = id2+                }+                none => {+                    failed = true+                }+            }+        }+        if failed {+            break+        }+        @append(entries, tree.entry(bytes.Bytes.dup(e.name), kind, target))+    }+    if failed {+        for te in entries {+            if te.name.ptr != none {+                val np: mut ref void = te.name.ptr as ref void+                @free(np)+            }+            val tp: mut ref void = te as ref void+            @free(tp)+        }+        @listfree(entries)+        format.free_parsed_tree(parsed)+        object.free_object(obj)+        return none+    }+    val body_opt = tree.encode(entries)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        ok b => {+            body = b+        }+        err _ => {+            failed = true+        }+    }+    for te in entries {+        if te.name.ptr != none {+            val np2: mut ref void = te.name.ptr as ref void+            @free(np2)+        }+        val tp2: mut ref void = te as ref void+        @free(tp2)+    }+    @listfree(entries)+    if failed {+        format.free_parsed_tree(parsed)+        object.free_object(obj)+        return none+    }+    val id: objid.Id = append_object(ctx, types.TREE, body)+    put_id(ctx.trees_map, oid, id)+    ctx.new_trees+++    if !parsed.canonical {+        val copy: bytes.Bytes = bytes.Bytes.dup(obj.body)+        val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave+        rsave.id = dup_id(id)+        rsave.body = copy+        @append(ctx.raw_saves, rsave)+    }+    val out2: objid.Id = dup_id(id)+    format.free_parsed_tree(parsed)+    object.free_object(obj)+    return some out2+}++fn add_branch_target(list: mut list[ref ImportNamedTarget], name: bytes.Bytes, oid: bytes.Bytes) void = trust {+    val t: mut ref ImportNamedTarget = @alloc(@sizeof(ImportNamedTarget)) as ref ImportNamedTarget+    t.name = name+    t.oid = oid+    @append(list, t)+}++fn free_named_targets(xs: list[ref ImportNamedTarget]) void = trust {+    for t in xs {+        if t.oid.ptr != none {+            val op: mut ref void = t.oid.ptr as ref void+            @free(op)+        }+        val tp: mut ref void = t as ref void+        @free(tp)+    }+    @listfree(xs)+}++fn sort_bookmarks(xs: mut list[ref view.Bookmark]) void = trust {+    val n: usize = @len(xs)+    val i: mut usize = 1+    for i < n {+        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 n: usize = @len(xs)+    val i: mut usize = 1+    for i < n {+        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 set_bookmark(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val bi: mut usize = 0+    for bi < @len(v.bookmarks) {+        val bmo = @get(v.bookmarks, bi)+        if bmo is some bm {+            if bytes.Bytes.eql(bm.name, name) {+                @listfree(bm.targets.adds)+                @listfree(bm.targets.removes)+                val adds: mut list[objid.Id] = lists.new[objid.Id]()+                @append(adds, id)+                bm.targets.adds = adds+                bm.targets.removes = lists.new[objid.Id]()+                return+            }+        }+        bi+++    }+    val bm: mut ref view.Bookmark = @alloc(@sizeof(view.Bookmark)) as ref view.Bookmark+    bm.name = bytes.Bytes.dup(name)+    val adds2: mut list[objid.Id] = lists.new[objid.Id]()+    @append(adds2, id)+    bm.targets = view.TargetSet{adds: adds2, removes: lists.new[objid.Id]()}+    @append(v.bookmarks, bm)+}++fn set_tag(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val ti: mut usize = 0+    for ti < @len(v.tags) {+        val to = @get(v.tags, ti)+        if to is some t {+            if bytes.Bytes.eql(t.name, name) {+                t.target = id+                return+            }+        }+        ti+++    }+    val t: mut ref view.TagRef = @alloc(@sizeof(view.TagRef)) as ref view.TagRef+    t.name = bytes.Bytes.dup(name)+    t.target = id+    @append(v.tags, t)+}++fn set_workspace(v: mut ref view.View, name: bytes.Bytes, id: objid.Id) void = trust {+    val wi: mut usize = 0+    for wi < @len(v.working_copies) {+        val wo = @get(v.working_copies, wi)+        if wo is some w {+            if bytes.Bytes.eql(w.workspace, name) {+                w.target = id+                return+            }+        }+        wi+++    }+    val w: mut ref view.WorkspaceRef = @alloc(@sizeof(view.WorkspaceRef)) as ref view.WorkspaceRef+    w.workspace = bytes.Bytes.dup(name)+    w.target = id+    @append(v.working_copies, w)+}++fn clear_view_view(v: mut ref view.View) void = trust {+    @listfree(v.heads)+    for bm in v.bookmarks {+        @listfree(bm.targets.adds)+        @listfree(bm.targets.removes)+        val bp: mut ref void = bm as ref void+        @free(bp)+    }+    @listfree(v.bookmarks)+    for t in v.tags {+        val tp: mut ref void = t as ref void+        @free(tp)+    }+    @listfree(v.tags)+    for rr in v.remote_refs {+        val rp: mut ref void = rr as ref void+        @free(rp)+    }+    @listfree(v.remote_refs)+    for w in v.working_copies {+        val wp: mut ref void = w as ref void+        @free(wp)+    }+    @listfree(v.working_copies)+    @free(v as ref void)+}++fn add_unique_head(heads: mut list[objid.Id], id: objid.Id) void = trust {+    for x in heads {+        if objid.Id.eql(x, id) {+            return+        }+    }+    @append(heads, id)+}++fn sort_head_ids(heads: mut list[objid.Id]) void = trust {+    val n: usize = @len(heads)+    val i: mut usize = 1+    for i < n {+        val cur = @get(heads, i)+        val cid: mut objid.Id = objid.id_none()+        if cur is some v {+            cid = v+        }+        val j: mut usize = i+        for j > 0 {+            val prev_opt = @get(heads, j - 1)+            val prev: mut objid.Id = objid.id_none()+            if prev_opt is some v2 {+                prev = v2+            }+            if objid.Id.cmp(prev, cid) <= 0 {+                break+            }+            @set(heads, j, prev)+            j--+        }+        @set(heads, j, cid)+        i+++    }+}++fn free_commit_records(recs: list[ref ImportCommitRec]) void = trust {+    for r in recs {+        if r.body.ptr != none {+            val bp: mut ref void = r.body.ptr as ref void+            @free(bp)+        }+        if r.oid.ptr != none {+            val op: mut ref void = r.oid.ptr as ref void+            @free(op)+        }+        format.free_parsed_commit(r.parsed)+        val rp: mut ref void = r as ref void+        @free(rp)+    }+    @listfree(recs)+}++fn free_raw_saves(xs: list[ref ImportRawSave]) void = trust {+    for r in xs {+        if r.body.ptr != none {+            val bp: mut ref void = r.body.ptr as ref void+            @free(bp)+        }+        if r.id.ptr != none {+            val ip: mut ref void = r.id.ptr as ref void+            @free(ip)+        }+        val rp: mut ref void = r as ref void+        @free(rp)+    }+    @listfree(xs)+}++fn free_objects(list: list[ref raw.RawObject]) void = trust {+    raw.free_objects(list)+}++/// Flush object batches as packs during large imports to bound peak memory.+val IMPORT_BATCH_BYTES: usize = 268435456++fn should_flush(ctx: ImportCtx) bool = {+    return ctx.object_bytes >= IMPORT_BATCH_BYTES+}++fn flush_batch(ctx: mut ImportCtx, repo: layout.Repo) bool = {+    if @len(ctx.objects) == 0 {+        return true+    }+    val wrote: bool = store.write_pack(repo, ctx.objects)+    raw.free_objects(ctx.objects)+    ctx.objects = raw.empty_list()+    ctx.object_bytes = 0+    return wrote+}++pub fn run(repo: layout.Repo) i32 = trust {+    val git_path: str.StringView = layout.git_dir(repo)+    val git_opt = object.open(git_path)+    val git: mut object.GitRepo = @zeroed+    match git_opt {+        ok g => {+            git = g+        }+        err _ => {+            files.free_path(git_path)+            stdio.eprint("vn: cannot open git mirror: {s}\n", {git_path})+            return 1+        }+    }++    val commits_map_opt = gitmap.load_map(repo, str.from_cstr(c"commits"))+    val trees_map_opt = gitmap.load_map(repo, str.from_cstr(c"trees"))+    val blobs_map_opt = gitmap.load_map(repo, str.from_cstr(c"blobs"))+    val commits_map: mut oidmap.OidMap = oidmap.new(64)+    val trees_map: mut oidmap.OidMap = oidmap.new(64)+    val blobs_map: mut oidmap.OidMap = oidmap.new(64)+    val maps_ok: mut bool = true+    match commits_map_opt {+        ok m => {+            commits_map = m+        }+        err _ => {+            maps_ok = false+        }+    }+    match trees_map_opt {+        ok m2 => {+            trees_map = m2+        }+        err _ => {+            maps_ok = false+        }+    }+    match blobs_map_opt {+        ok m3 => {+            blobs_map = m3+        }+        err _ => {+            maps_ok = false+        }+    }+    if !maps_ok {+        stdio.eprint("vn: corrupt git mapping table\n", {})+        object.free(git)+        return 1+    }++    val refset: refs.RefSet = refs.read(git.git_dir)+    val ctx: mut ImportCtx = ImportCtx{+        git: git,+        commits_map: commits_map,+        trees_map: trees_map,+        blobs_map: blobs_map,+        objects: raw.empty_list(),+        raw_saves: lists.new[ref ImportRawSave](),+        new_commits: 0,+        new_trees: 0,+        new_blobs: 0,+        object_bytes: 0+    }++    val branches: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()+    val tags: mut list[ref ImportNamedTarget] = lists.new[ref ImportNamedTarget]()+    val tips: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    for b in refset.branches {+        val peeled = peel_to_commit(ctx.git, b.oid)+        match peeled {+            some c => {+                add_branch_target(branches, b.name, c)+                @append(tips, bytes.Bytes.dup(c))+            }+            none => {+            }+        }+    }+    for t in refset.tags {+        val peeled2 = peel_to_commit(ctx.git, t.oid)+        match peeled2 {+            some c2 => {+                add_branch_target(tags, t.name, c2)+                @append(tips, bytes.Bytes.dup(c2))+            }+            none => {+            }+        }+    }+    val head_commit: mut option[bytes.Bytes] = none+    if refset.head.len > 0 {+        val head_peeled = peel_to_commit(ctx.git, refset.head)+        head_commit = head_peeled+        match head_peeled {+            some h => {+                @append(tips, bytes.Bytes.dup(h))+            }+            none => {+            }+        }+    }++    val seen: mut oidmap.OidMap = oidmap.new(64)+    val records: mut list[ref ImportCommitRec] = lists.new[ref ImportCommitRec]()+    val stack: mut list[bytes.Bytes] = lists.new[bytes.Bytes]()+    for t in tips {+        @append(stack, t)+    }+    @listfree(tips)+    val collect_failed: mut bool = false+    for @len(stack) > 0 {+        val last: usize = @len(stack) - 1+        val oid: bytes.Bytes = @remove(stack, last)+        if oidmap.contains(ctx.commits_map, oid) || oidmap.contains(seen, oid) {+            val cp: mut ref void = oid.ptr as ref void+            @free(cp)+            continue+        }+        oidmap.put(seen, oid, bytes.empty())+        val obj_opt = object.read(ctx.git, oid)+        val obj: mut object.Object = object.Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+        match obj_opt {+            ok o => {+                obj = o+            }+            err _ => {+                collect_failed = true+                val cp2: mut ref void = oid.ptr as ref void+                @free(cp2)+                continue+            }+        }+        if obj.kind != object.KIND_COMMIT {+            object.free_object(obj)+            val cp3: mut ref void = oid.ptr as ref void+            @free(cp3)+            continue+        }+        val body: bytes.Bytes = bytes.Bytes.dup(obj.body)+        object.free_object(obj)+        val parsed_opt = format.parse_commit(body)+        val parsed: mut ref format.ParsedCommit = none+        match parsed_opt {+            some p => {+                parsed = p+            }+            none => {+                collect_failed = true+                val bp: mut ref void = body.ptr as ref void+                @free(bp)+                val cp4: mut ref void = oid.ptr as ref void+                @free(cp4)+                continue+            }+        }+        val rec: mut ref ImportCommitRec = @alloc(@sizeof(ImportCommitRec)) as ref ImportCommitRec+        rec.oid = oid+        rec.body = body+        rec.parsed = parsed+        @append(records, rec)+        for parent in parsed.parents {+            @append(stack, bytes.Bytes.dup(parent))+        }+    }+    @listfree(stack)+    oidmap.free(seen)++    val n: usize = @len(records)+    val indegree: ref u32 = @alloc(n * 4 + 1) as ref u32+    @memset(indegree as ref void, 0, n * 4 + 1)+    val children: mut list[list[usize]] = lists.new[list[usize]]()+    val i0: mut usize = 0+    for i0 < n {+        @append(children, lists.new[usize]())+        i0+++    }+    val index_map: mut oidmap.OidMap = oidmap.new(64)+    val i1: mut usize = 0+    for i1 < n {+        val rec_opt = @get(records, i1)+        if rec_opt is some rec2 {+            put_usize(index_map, rec2.oid, i1)+        }+        i1+++    }+    val topo_failed: mut bool = false+    val i2: mut usize = 0+    for i2 < n {+        val rec_opt2 = @get(records, i2)+        if rec_opt2 is some rec3 {+            for parent in rec3.parsed.parents {+                if oidmap.contains(ctx.commits_map, parent) {+                    continue+                }+                val idx_opt = get_usize(index_map, parent)+                match idx_opt {+                    some pidx => {+                        if pidx < n {+                            val deg_ptr: ref u32 = @ptradd(indegree as ref void, (i2 * 4) as i64) as ref u32+                            @store32(deg_ptr, (@load32(deg_ptr) + 1) as i32)+                            val child_list = @get(children, pidx)+                            if child_list is some cl {+                                @append(cl, i2)+                            }+                        }+                    }+                    none => {+                        topo_failed = true+                    }+                }+            }+        }+        i2+++    }+    val queue: mut list[usize] = lists.new[usize]()+    val order: mut list[usize] = lists.new[usize]()+    val i3: mut usize = 0+    for i3 < n {+        val deg_ptr2: ref u32 = @ptradd(indegree as ref void, (i3 * 4) as i64) as ref u32+        if @load32(deg_ptr2) == 0 {+            @append(queue, i3)+        }+        i3+++    }+    val qhead: mut usize = 0+    for qhead < @len(queue) {+        val cur_opt = @get(queue, qhead)+        val cur: mut usize = 0+        if cur_opt is some cv {+            cur = cv+        }+        qhead+++        @append(order, cur)+        val child_list_opt = @get(children, cur)+        if child_list_opt is some cl2 {+            for child in cl2 {+                val dp: ref u32 = @ptradd(indegree as ref void, (child * 4) as i64) as ref u32+                val d: u32 = @load32(dp) as u32+                if d > 0 {+                    @store32(dp, (d - 1) as i32)+                    if d - 1 == 0 {+                        @append(queue, child)+                    }+                }+            }+        }+    }+    @listfree(queue)+    if topo_failed || @len(order) != n {+        stdio.eprint("vn: git commit graph is incomplete or cyclic\n", {})+        for cl3 in children {+            @listfree(cl3)+        }+        @listfree(children)+        @free(indegree as ref void)+        oidmap.free(index_map)+        free_commit_records(records)+        free_named_targets(branches)+        free_named_targets(tags)+        if head_commit is some h2 {+            val hp: mut ref void = h2.ptr as ref void+            @free(hp)+        }+        refs.free(refset)+        free_objects(ctx.objects)+        free_raw_saves(ctx.raw_saves)+        oidmap.free(ctx.commits_map)+        oidmap.free(ctx.trees_map)+        oidmap.free(ctx.blobs_map)+        object.free(ctx.git)+        return 1+    }++    val build_failed: mut bool = false+    // Import all trees and blobs reachable from the new commits.+    val ci: mut usize = 0+    for ci < @len(records) {+        val rec_opt4 = @get(records, ci)+        if rec_opt4 is some rec4 {+            val tr = import_tree(ctx, rec4.parsed.tree)+            if tr is none {+                build_failed = true+                break+            }+            if should_flush(ctx) {+                if !flush_batch(ctx, repo) {+                    build_failed = true+                    break+                }+            }+        }+        ci+++    }++    val oi: mut usize = 0+    for oi < @len(order) {+        val idx_opt = @get(order, oi)+        val idx: mut usize = 0+        if idx_opt is some v {+            idx = v+        }+        val rec_opt3 = @get(records, idx)+        val rec: mut ref ImportCommitRec = none+        if rec_opt3 is some v2 {+            rec = v2+        }+        val tree_map = get_id(ctx.trees_map, rec.parsed.tree)+        val root_tree: mut objid.Id = objid.id_none()+        match tree_map {+            some t => {+                root_tree = t+            }+            none => {+                build_failed = true+            }+        }+        val parents: mut list[objid.Id] = lists.new[objid.Id]()+        for p in rec.parsed.parents {+            val pid = get_id(ctx.commits_map, p)+            match pid {+                some id => {+                    @append(parents, id)+                }+                none => {+                    build_failed = true+                }+            }+        }+        if build_failed {+            @listfree(parents)+            break+        }+        val cid: mut objid.ChangeId = objid.change_id(none)+        if rec.parsed.change_id.ptr != none {+            cid = objid.change_id(rec.parsed.change_id.ptr)+        } else {+            cid = derive_change_id(rec.oid)+        }+        val renames: list[ref commit.Rename] = lists.new[ref commit.Rename]()+        val c: mut ref commit.Commit = @alloc(@sizeof(commit.Commit)) as ref commit.Commit+        c.version = 1+        c.parents = parents+        c.root_tree = root_tree+        c.change_id = cid+        c.author = rec.parsed.author+        c.committer = rec.parsed.committer+        c.message = rec.parsed.message+        c.renames_state = commit.RENAMES_UNKNOWN+        c.renames = renames+        c.extra = rec.parsed.extras+        val cbody: bytes.Bytes = commit.encode(c)+        val cid_out: objid.Id = append_object(ctx, types.COMMIT, cbody)+        @listfree(c.parents)+        @listfree(c.renames)+        @free(c as ref void)+        put_id(ctx.commits_map, rec.oid, cid_out)+        ctx.new_commits+++        val serialized: bytes.Bytes = format.serialize_commit(rec.parsed)+        val is_canonical: bool = rec.parsed.canonical && bytes.Bytes.eql(serialized, rec.body)+        if serialized.ptr != none {+            val sp: mut ref void = serialized.ptr as ref void+            @free(sp)+        }+        if !is_canonical {+            val rsave: mut ref ImportRawSave = @alloc(@sizeof(ImportRawSave)) as ref ImportRawSave+            rsave.id = dup_id(cid_out)+            rsave.body = bytes.Bytes.dup(rec.body)+            @append(ctx.raw_saves, rsave)+        }+        if cid.ptr != none && rec.parsed.change_id.ptr == none {+            val cp5: mut ref void = cid.ptr as ref void+            @free(cp5)+        }+        oi+++    }+    @listfree(order)+    for cl4 in children {+        @listfree(cl4)+    }+    @listfree(children)+    @free(indegree as ref void)+    oidmap.free(index_map)++    if build_failed {+        stdio.eprint("vn: referenced git object is missing\n", {})+        free_commit_records(records)+        free_named_targets(branches)+        free_named_targets(tags)+        if head_commit is some h3 {+            val hp2: mut ref void = h3.ptr as ref void+            @free(hp2)+        }+        refs.free(refset)+        free_objects(ctx.objects)+        free_raw_saves(ctx.raw_saves)+        oidmap.free(ctx.commits_map)+        oidmap.free(ctx.trees_map)+        oidmap.free(ctx.blobs_map)+        object.free(ctx.git)+        return 1+    }++    if build_failed {+        stdio.eprint("vn: failed to import a tree or blob\n", {})+        free_commit_records(records)+        free_named_targets(branches)+        free_named_targets(tags)+        if head_commit is some h4 {+            val hp3: mut ref void = h4.ptr as ref void+            @free(hp3)+        }+        refs.free(refset)+        free_objects(ctx.objects)+        free_raw_saves(ctx.raw_saves)+        oidmap.free(ctx.commits_map)+        oidmap.free(ctx.trees_map)+        oidmap.free(ctx.blobs_map)+        object.free(ctx.git)+        return 1+    }++    // Load the current view and store.+    val store_handle: store.Store = store.open_all(repo)+    val current = state.current_view(repo, store_handle.handles)+    val v: mut ref view.View = none+    val old_encoded: mut bytes.Bytes = bytes.empty()+    match current {+        some cv => {+            v = cv+            old_encoded = view.encode(v)+        }+        none => {+            v = state.empty_view()+        }+    }++    for b in branches {+        val id = get_id(ctx.commits_map, b.oid)+        match id {+            some bid => {+                set_bookmark(v, b.name, bid)+            }+            none => {+            }+        }+    }+    for t in tags {+        val id = get_id(ctx.commits_map, t.oid)+        match id {+            some tid => {+                set_tag(v, t.name, tid)+            }+            none => {+            }+        }+    }+    sort_bookmarks(v.bookmarks)+    sort_tags(v.tags)++    @listfree(v.heads)+    val new_heads: mut list[objid.Id] = lists.new[objid.Id]()+    for b in branches {+        val id = get_id(ctx.commits_map, b.oid)+        match id {+            some bid => {+                add_unique_head(new_heads, bid)+            }+            none => {+            }+        }+    }+    if @len(new_heads) == 0 {+        for t in tags {+            val id = get_id(ctx.commits_map, t.oid)+            match id {+                some tid => {+                    add_unique_head(new_heads, tid)+                }+                none => {+                }+            }+        }+    }+    val head_id: mut objid.Id = objid.id_none()+    if head_commit is some hc {+        val hcid = get_id(ctx.commits_map, hc)+        if hcid is some hv {+            head_id = hv+        }+    }+    if @len(new_heads) == 0 && !objid.Id.is_none(head_id) {+        add_unique_head(new_heads, head_id)+    }+    sort_head_ids(new_heads)+    v.heads = new_heads+    if !objid.Id.is_none(head_id) {+        set_workspace(v, bytes.bytes(c"default", 7), head_id)+    } elif @len(new_heads) > 0 {+        val first = @get(new_heads, 0)+        if first is some fid {+            set_workspace(v, bytes.bytes(c"default", 7), fid)+        }+    }++    val new_encoded: bytes.Bytes = view.encode(v)+    val unchanged: bool = bytes.Bytes.eql(old_encoded, new_encoded)+    val has_new_objects: bool = ctx.new_commits > 0 || ctx.new_trees > 0 || ctx.new_blobs > 0+    if unchanged && !has_new_objects {+        if old_encoded.ptr != none {+            val op: mut ref void = old_encoded.ptr as ref void+            @free(op)+        }+        if new_encoded.ptr != none {+            val np: mut ref void = new_encoded.ptr as ref void+            @free(np)+        }+        clear_view_view(v)+        free_commit_records(records)+        free_named_targets(branches)+        free_named_targets(tags)+        if head_commit is some h5 {+            val hp4: mut ref void = h5.ptr as ref void+            @free(hp4)+        }+        refs.free(refset)+        free_objects(ctx.objects)+        free_raw_saves(ctx.raw_saves)+        oidmap.free(ctx.commits_map)+        oidmap.free(ctx.trees_map)+        oidmap.free(ctx.blobs_map)+        store.close(store_handle)+        object.free(ctx.git)+        stdio.eprint("vn: already up to date\n", {})+        return 0+    }++    val view_id: objid.Id = append_object(ctx, types.VIEW, new_encoded)+    val parent_heads: list[objid.Id] = state.heads(repo)+    val op_parents: mut list[objid.Id] = lists.new[objid.Id]()+    for ph in parent_heads {+        @append(op_parents, ph)+    }+    @listfree(parent_heads)+    val now: i64 = time.unix_now_millis()+    val tm: prim.TimeMs = prim.TimeMs{ms: now, tz_min: 0}+    val hostname: bytes.Bytes = host_from_env()+    val username: bytes.Bytes = user_from_env()+    val op_tags: mut list[ref prim.KeyValue] = lists.new[ref prim.KeyValue]()+    val cmd_kv: mut ref prim.KeyValue = @alloc(@sizeof(prim.KeyValue)) as ref prim.KeyValue+    cmd_kv.key = bytes.bytes(c"command", 7)+    cmd_kv.value = bytes.bytes(c"git import", 10)+    @append(op_tags, cmd_kv)+    val op: mut ref operation.Operation = @alloc(@sizeof(operation.Operation)) as ref operation.Operation+    op.parents = op_parents+    op.view = view_id+    op.start = tm+    op.end = tm+    op.hostname = hostname+    op.username = username+    op.description = bytes.bytes(c"git import", 10)+    op.tags = op_tags+    val op_body: bytes.Bytes = operation.encode(op)+    val op_id: objid.Id = append_object(ctx, types.OPERATION, op_body)+    @listfree(op.tags)+    @free(op as ref void)+    if hostname.ptr != none {+        val hp5: mut ref void = hostname.ptr as ref void+        @free(hp5)+    }+    if username.ptr != none {+        val up: mut ref void = username.ptr as ref void+        @free(up)+    }++    val wrote: bool = store.write_pack(repo, ctx.objects)+    if !wrote {+        stdio.eprint("vn: failed to write object pack\n", {})+        if old_encoded.ptr != none {+            val op2: mut ref void = old_encoded.ptr as ref void+            @free(op2)+        }+        clear_view_view(v)+        for ph2 in op_parents {+            if ph2.ptr != none {+                val pp: mut ref void = ph2.ptr as ref void+                @free(pp)+            }+        }+        @listfree(op_parents)+        free_commit_records(records)+        free_named_targets(branches)+        free_named_targets(tags)+        if head_commit is some h6 {+            val hp6: mut ref void = h6.ptr as ref void+            @free(hp6)+        }+        refs.free(refset)+        free_objects(ctx.objects)+        free_raw_saves(ctx.raw_saves)+        oidmap.free(ctx.commits_map)+        oidmap.free(ctx.trees_map)+        oidmap.free(ctx.blobs_map)+        store.close(store_handle)+        object.free(ctx.git)+        return 1+    }++    for rs in ctx.raw_saves {+        val _ = gitmap.save_raw(repo, rs.id, rs.body)+    }+    val saved_commits: bool = gitmap.save_map(repo, str.from_cstr(c"commits"), ctx.commits_map)+    val saved_trees: bool = gitmap.save_map(repo, str.from_cstr(c"trees"), ctx.trees_map)+    val saved_blobs: bool = gitmap.save_map(repo, str.from_cstr(c"blobs"), ctx.blobs_map)+    if !saved_commits || !saved_trees || !saved_blobs {+        stdio.eprint("vn: failed to write git mapping tables\n", {})+    }+    val head_ok: bool = state.write_head(repo, op_id)+    if head_ok {+        for ph3 in op_parents {+            if !objid.Id.is_none(ph3) {+                val _ = state.delete_head(repo, ph3)+            }+        }+    }++    stdio.eprint("vn: imported {d} commits, {d} trees, {d} blobs\n", {ctx.new_commits, ctx.new_trees, ctx.new_blobs})++    if old_encoded.ptr != none {+        val op3: mut ref void = old_encoded.ptr as ref void+        @free(op3)+    }+    clear_view_view(v)+    for ph4 in op_parents {+        if ph4.ptr != none {+            val pp2: mut ref void = ph4.ptr as ref void+            @free(pp2)+        }+    }+    @listfree(op_parents)+    free_commit_records(records)+    free_named_targets(branches)+    free_named_targets(tags)+    if head_commit is some h7 {+        val hp7: mut ref void = h7.ptr as ref void+        @free(hp7)+    }+    refs.free(refset)+    free_objects(ctx.objects)+    free_raw_saves(ctx.raw_saves)+    oidmap.free(ctx.commits_map)+    oidmap.free(ctx.trees_map)+    oidmap.free(ctx.blobs_map)+    store.close(store_handle)+    object.free(ctx.git)+    if !head_ok {+        return 1+    }+    return 0+}++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))+        }+    }+}+--- /dev/null+++ b/src/src/git/map.sx@@ -0,0 +1,146 @@+/// Persistent git ID mapping tables and raw-object storage.++val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val buf    = use("../core/buf.sx")+val objid  = use("../object/id.sx")+val layout = use("../store/layout.sx")+val files  = use("../io/files.sx")+val native = use("../io/native.sx")+val oidmap = use("oidmap.sx")+val object = use("object.sx")++pub fn map_path(repo: layout.Repo, name: str.StringView) str.StringView = {+    val dir: str.StringView = layout.git_map_dir(repo)+    val p: str.StringView = files.join(dir, name)+    files.free_path(dir)+    return p+}++fn map_name(base: str.StringView, suffix: str.StringView) str.StringView = {+    return files.with_suffix(base, suffix)+}++pub fn load_map(repo: layout.Repo, name: str.StringView) result[oidmap.OidMap, object.GitError] = trust {+    val base: str.StringView = layout.git_map_dir(repo)+    val suffix: str.StringView = str.from_cstr(c".map")+    val fname: str.StringView = files.with_suffix(name, suffix)+    val path: str.StringView = files.join(base, fname)+    files.free_path(base)+    files.free_path(fname)+    val data_opt = files.read_all(path)+    files.free_path(path)+    val map: mut oidmap.OidMap = oidmap.new(64)+    val data: mut bytes.Bytes = bytes.empty()+    match data_opt {+        some d => {+            data = d+        }+        none => {+            return ok map+        }+    }+    if data.len < 9 || !bytes.Bytes.eql(bytes.Bytes.slice(data, 0, 5), bytes.bytes(c"VMAP1", 5)) {+        files.free_buffer(data)+        oidmap.free(map)+        return err object.GitError.Corrupt+    }+    val count: u32 = (bytes.Bytes.at(data, 5) as u32)+        | ((bytes.Bytes.at(data, 6) as u32) << 8)+        | ((bytes.Bytes.at(data, 7) as u32) << 16)+        | ((bytes.Bytes.at(data, 8) as u32) << 24)+    val need: u64 = 9 as u64 + (count as u64) * 52 as u64+    if need != data.len as u64 {+        files.free_buffer(data)+        oidmap.free(map)+        return err object.GitError.Corrupt+    }+    val i: mut usize = 0+    for i < count as usize {+        val off: usize = 9 + i * 52+        oidmap.put(+            map,+            bytes.Bytes.slice(data, off, off + 20),+            bytes.Bytes.slice(data, off + 20, off + 52)+        )+        i+++    }+    files.free_buffer(data)+    return ok map+}++pub fn save_map(repo: layout.Repo, name: str.StringView, map: oidmap.OidMap) bool = trust {+    val b: mut buf.Buf = buf.new(map.len * 52 + 16)+    buf.Buf.put_raw(b, c"VMAP1", 5)+    buf.Buf.put_u32_le(b, map.len as u32)+    val i: mut usize = 0+    for i < map.cap {+        if oidmap.slot_used(map, i) {+            buf.Buf.put_bytes(b, oidmap.slot_oid(map, i))+            buf.Buf.put_bytes(b, oidmap.slot_value(map, i))+        }+        i+++    }+    val base: str.StringView = layout.git_map_dir(repo)+    val suffix: str.StringView = str.from_cstr(c".map")+    val fname: str.StringView = files.with_suffix(name, suffix)+    val final: str.StringView = files.join(base, fname)+    val tmpd: str.StringView = layout.tmp_dir(repo)+    val tmpname: str.StringView = map_name(fname, str.from_cstr(c".tmp"))+    val tmp: str.StringView = files.join(tmpd, tmpname)+    val success: bool = native.write_atomic(tmp, final, tmpd, base, buf.Buf.view(b))+    files.free_path(base)+    files.free_path(tmpd)+    files.free_path(fname)+    files.free_path(final)+    files.free_path(tmpname)+    files.free_path(tmp)+    buf.Buf.free(b)+    return success+}++fn vein_hex(id: objid.Id) ref u8 = {+    return objid.Id.hex(id)+}++pub fn save_raw(repo: layout.Repo, id: objid.Id, body: bytes.Bytes) bool = trust {+    val hex: ref u8 = vein_hex(id)+    val base: str.StringView = layout.raw_dir(repo)+    val name: str.StringView = str.from_cstr(hex)+    val final: str.StringView = files.join(base, name)+    val tmpd: str.StringView = layout.tmp_dir(repo)+    val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))+    val tmp: str.StringView = files.join(tmpd, tmpname)+    val success: bool = native.write_atomic(tmp, final, tmpd, base, body)+    files.free_path(base)+    files.free_path(tmpd)+    files.free_path(final)+    files.free_path(tmpname)+    files.free_path(tmp)+    @free(hex as ref void)+    return success+}++pub fn has_raw(repo: layout.Repo, id: objid.Id) bool = trust {+    val hex: ref u8 = vein_hex(id)+    val base: str.StringView = layout.raw_dir(repo)+    val name: str.StringView = str.from_cstr(hex)+    val path: str.StringView = files.join(base, name)+    val found: bool = files.exists_file(path)+    files.free_path(base)+    files.free_path(path)+    @free(hex as ref void)+    return found+}++pub fn load_raw(repo: layout.Repo, id: objid.Id) option[bytes.Bytes] = trust {+    val hex: ref u8 = vein_hex(id)+    val base: str.StringView = layout.raw_dir(repo)+    val name: str.StringView = str.from_cstr(hex)+    val path: str.StringView = files.join(base, name)+    val data = files.read_all(path)+    files.free_path(base)+    files.free_path(path)+    @free(hex as ref void)+    return data+}--- /dev/null+++ b/src/src/git/mirror.sx@@ -0,0 +1,155 @@+/// Prepare the `.vein/git` mirror from an existing git repository.++val str    = use("std/string")+val bytes  = use("../core/bytes.sx")+val layout = use("../store/layout.sx")+val files  = use("../io/files.sx")++extern (C) fn c_link(oldpath: ref u8, newpath: ref u8) i32 = "link"++fn has_git_dir(path: str.StringView) bool = {+    val marker: str.StringView = files.join(path, str.from_cstr(c".git"))+    val dir: bool = files.exists_dir(marker)+    files.free_path(marker)+    return dir+}++fn is_bare(path: str.StringView) bool = {+    val head: str.StringView = files.join(path, str.from_cstr(c"HEAD"))+    val objects: str.StringView = files.join(path, str.from_cstr(c"objects"))+    val success: bool = files.exists_file(head) && files.exists_dir(objects)+    files.free_path(head)+    files.free_path(objects)+    return success+}++fn gitdir_from_file(path: str.StringView) option[str.StringView] = {+    val data_opt = files.read_all(path)+    match data_opt {+        some data => {+            val prefix: bytes.Bytes = bytes.bytes(c"gitdir: ", 8)+            if !bytes.Bytes.starts_with(data, prefix) {+                files.free_buffer(data)+                return none+            }+            val raw: bytes.Bytes = bytes.Bytes.slice(data, 8, data.len)+            val end: mut usize = raw.len+            for end > 0 && (bytes.Bytes.at(raw, end - 1) == 10 || bytes.Bytes.at(raw, end - 1) == 13) {+                end--+            }+            val value: bytes.Bytes = bytes.Bytes.slice(raw, 0, end)+            val view: str.StringView = str.view(value.ptr, value.len as i64)+            val out: mut str.StringView = str.view(none, 0)+            if view.len > 0 && trust @load8(view.ptr) == 47 {+                out = files.with_suffix(view, str.view(none, 0))+            } else {+                val parent: str.StringView = files.basename(path)+                val parent_path: str.StringView = str.view(path.ptr, path.len - parent.len)+                out = files.join(parent_path, view)+            }+            files.free_buffer(data)+            return some out+        }+        none => {+            return none+        }+    }+}++/// Resolve a user-supplied path to the git directory it names.+pub fn resolve_source(source: str.StringView) option[str.StringView] = {+    if has_git_dir(source) {+        val dotgit: str.StringView = files.join(source, str.from_cstr(c".git"))+        if files.exists_dir(dotgit) {+            return some dotgit+        }+        val from_file = gitdir_from_file(dotgit)+        files.free_path(dotgit)+        return from_file+    }+    if is_bare(source) {+        return some files.with_suffix(source, str.view(none, 0))+    }+    return none+}++fn try_link(src: str.StringView, dst: str.StringView) bool = trust {+    val s: ref u8 = src.ptr+    val d: ref u8 = dst.ptr+    return c_link(s, d) == 0+}++fn copy_file_fallback(src: str.StringView, dst: str.StringView) bool = {+    val data_opt = files.read_all(src)+    match data_opt {+        some data => {+            val wrote: bool = files.write_all(dst, data)+            files.free_buffer(data)+            return wrote+        }+        none => {+            return false+        }+    }+}++fn copy_tree(src: str.StringView, dst: str.StringView) bool = trust {+    if !files.exists_dir(dst) {+        if !files.mkdir_all(dst) {+            return false+        }+    }+    val names: list[ref u8] = files.list_dir(src)+    val failed: mut bool = false+    for n in names {+        val name: str.StringView = str.from_cstr(n)+        val s: str.StringView = files.join(src, name)+        val d: str.StringView = files.join(dst, name)+        if files.exists_dir(s) {+            if !copy_tree(s, d) {+                failed = true+            }+        } elif files.exists_file(s) {+            if !try_link(s, d) {+                if !copy_file_fallback(s, d) {+                    failed = true+                }+            }+        }+        files.free_path(s)+        files.free_path(d)+    }+    files.free_names(names)+    return !failed+}++/// Copy the source git directory into `.vein/git`. Existing mirrors are left+/// untouched and treated as already prepared.+pub fn prepare(repo: layout.Repo, source: str.StringView) i32 = trust {+    val target: str.StringView = layout.git_dir(repo)+    val head: str.StringView = files.join(target, str.from_cstr(c"HEAD"))+    val already: bool = files.exists_file(head)+    files.free_path(head)+    if already {+        files.free_path(target)+        return 0+    }+    val src_opt = resolve_source(source)+    val src: mut str.StringView = str.view(none, 0)+    match src_opt {+        some s => {+            src = s+        }+        none => {+            files.free_path(target)+            return 2+        }+    }+    val success: bool = copy_tree(src, target)+    files.free_path(src)+    files.free_path(target)+    if success {+        return 0+    }+    return 3+}--- /dev/null+++ b/src/src/git/object.sx@@ -0,0 +1,967 @@+/// Read-only access to a git object database.+///+/// Supports loose objects, pack v2/v3 files with OFS/REF deltas, and both v1+/// and v2 pack indexes. The importer uses this instead of shelling out to git.++lib "z"+lib "crypto"++val str        = use("std/string")+val bytes      = use("../core/bytes.sx")+val buf        = use("../core/buf.sx")+val lists      = use("../core/lists.sx")+val files      = use("../io/files.sx")++pub enum GitError = {+    NotFound+    Corrupt+    Unsupported+    Io+    HashMismatch+    OutOfMemory+}++pub fn error_name(e: GitError) str.StringView = {+    match e {+        GitError.NotFound => {+            return "object not found"+        }+        GitError.Corrupt => {+            return "corrupt git object data"+        }+        GitError.Unsupported => {+            return "unsupported git format"+        }+        GitError.Io => {+            return "git object I/O error"+        }+        GitError.HashMismatch => {+            return "git object hash mismatch"+        }+        GitError.OutOfMemory => {+            return "out of memory"+        }+    }+    return "git error"+}++pub val KIND_COMMIT: u8 = 1+pub val KIND_TREE: u8 = 2+pub val KIND_BLOB: u8 = 3+pub val KIND_TAG: u8 = 4+pub val KIND_OFS_DELTA: u8 = 6+pub val KIND_REF_DELTA: u8 = 7++pub type Object = {+    kind: u8+    body: bytes.Bytes+    alloc: bytes.Bytes+}++pub fn free_object(o: Object) void= trust {+    if o.alloc.ptr != none {+        val p: mut ref void = o.alloc.ptr as ref void+        @free(p)+    }+}++type GitPack = {+    path: mut str.StringView+    data: mut bytes.Bytes+    count: mut usize+    oids: mut ref u8+    offsets: mut ref u8+}++pub type GitRepo = {+    git_dir: mut str.StringView+    packs: list[ref GitPack]+}++extern (C) fn uncompress(dest: ref u8, dest_len: ref u64, source: ref u8, source_len: u64) i32 = "uncompress"+++fn be32_at(data: bytes.Bytes, off: usize) u32 = trust {+    val p: ref u8 = @ptradd(data.ptr, off as i64)+    return ((@load8(p) as u32) << 24) | ((@load8(@ptradd(p, 1)) as u32) << 16)+        | ((@load8(@ptradd(p, 2)) as u32) << 8) | (@load8(@ptradd(p, 3)) as u32)+}++fn be64_at(data: bytes.Bytes, off: usize) u64= trust {+    val p: ref u8 = @ptradd(data.ptr, off as i64)+    val hi: u64 = ((@load8(p) as u64) << 56) | ((@load8(@ptradd(p, 1)) as u64) << 48)+        | ((@load8(@ptradd(p, 2)) as u64) << 40) | ((@load8(@ptradd(p, 3)) as u64) << 32)+    val lo: u64 = ((@load8(@ptradd(p, 4)) as u64) << 24) | ((@load8(@ptradd(p, 5)) as u64) << 16)+        | ((@load8(@ptradd(p, 6)) as u64) << 8) | (@load8(@ptradd(p, 7)) as u64)+    return hi | lo+}++extern (C) fn SHA1(data: ref u8, len: usize, out: ref u8) ref u8 = "SHA1"++fn sha1_of(data: bytes.Bytes) option[bytes.Bytes]= trust {+    val out: ref u8 = @alloc(20) as ref u8+    val r: ref u8 = SHA1(data.ptr, data.len, out)+    if r == none {+        @free(out as ref void)+        return none+    }+    return some bytes.bytes(out, 20)+}++pub fn free_digest(d: bytes.Bytes) void= trust {+    if d.ptr != none {+        val p: mut ref void = d.ptr as ref void+        @free(p)+    }+}++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) str.StringView = {+    if kind == KIND_COMMIT {+        return "commit"+    }+    if kind == KIND_TREE {+        return "tree"+    }+    if kind == KIND_BLOB {+        return "blob"+    }+    if kind == KIND_TAG {+        return "tag"+    }+    return "unknown"+}++fn kind_from_name(name: bytes.Bytes) u8 = {+    if bytes.Bytes.eql(name, bytes.bytes(c"commit", 6)) {+        return KIND_COMMIT+    }+    if bytes.Bytes.eql(name, bytes.bytes(c"tree", 4)) {+        return KIND_TREE+    }+    if bytes.Bytes.eql(name, bytes.bytes(c"blob", 4)) {+        return KIND_BLOB+    }+    if bytes.Bytes.eql(name, bytes.bytes(c"tag", 3)) {+        return KIND_TAG+    }+    return 0+}++/// Git object hash: SHA-1("<kind> <length>\0" || body).+pub fn object_hash(kind: u8, body: bytes.Bytes) option[bytes.Bytes]= trust {+    val b: mut buf.Buf = buf.new(body.len + 32)+    buf.Buf.put_bytes(b, bytes.from_cstr(kind_name(kind).ptr))+    buf.Buf.put_u8(b, 32)+    put_decimal(b, body.len as u64)+    buf.Buf.put_u8(b, 0)+    buf.Buf.put_bytes(b, body)+    val out = sha1_of(buf.Buf.view(b))+    buf.Buf.free(b)+    return out+}++fn verify_hash(oid: bytes.Bytes, kind: u8, body: bytes.Bytes) bool= trust {+    val got = object_hash(kind, body)+    match got {+        some h => {+            val same: bool = bytes.Bytes.eql(h, oid)+            free_digest(h)+            return same+        }+        none => {+            return false+        }+    }+}++fn inflate_exact(input: bytes.Bytes, expected: usize) option[bytes.Bytes]= trust {+    val cap: usize = expected + 1+    val dst: ref u8 = @alloc(cap) as ref u8+    @memset(dst as ref void, 0, cap)+    val dest_len: ref u64 = @alloc(8) as ref u64+    @store64(dest_len as ref void, expected as u64)+    val rc: i32 = uncompress(+        dst,+        dest_len,+        input.ptr,+        input.len as u64+    )+    val got: u64 = @load64(dest_len as ref void) as u64+    @free(dest_len as ref void)+    if rc != 0 || got != expected as u64 {+        @free(dst as ref void)+        return none+    }+    return some bytes.bytes(dst, expected)+}++fn inflate_unknown(input: bytes.Bytes) option[bytes.Bytes]= trust {+    val base: mut usize = input.len * 3 + 4096+    for base <= 1073741824 {+        val dst: ref u8 = @alloc(base + 1) as ref u8+        val dest_len: ref u64 = @alloc(8) as ref u64+        @store64(dest_len as ref void, base as u64)+        val rc: i32 = uncompress(dst, dest_len, input.ptr, input.len as u64)+        val got: u64 = @load64(dest_len as ref void) as u64+        @free(dest_len as ref void)+        if rc == 0 {+            return some bytes.bytes(dst, got as usize)+        }+        @free(dst as ref void)+        if rc != -5 {+            return none+        }+        base = base * 2+    }+    return none+}++fn hex_digit(n: u8) u8 = {+    if n < 10 {+        return (48 + n) as u8+    }+    return (87 + n) as u8+}++fn oid_hex(oid: bytes.Bytes) ref u8= trust {+    val out: ref u8 = @alloc(41) as ref u8+    val i: mut usize = 0+    for i < 20 {+        val v: u8 = bytes.Bytes.at(oid, i)+        @store8(@ptradd(out, (i * 2) as i64), hex_digit(v >> 4))+        @store8(@ptradd(out, (i * 2 + 1) as i64), hex_digit(v & 15))+        i+++    }+    @store8(@ptradd(out, 40), 0)+    return out+}++type GitVarint = {+    value: u64+    next: usize+}++fn read_be_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {+    if start >= data.len {+        return none+    }+    val c0: u8 = bytes.Bytes.at(data, start)+    val size: mut u64 = (c0 & 0x0f) as u64+    val shift: mut u64 = 4+    val i: mut usize = start + 1+    val more: mut bool = (c0 & 0x80) != 0+    for more {+        if i >= data.len {+            return none+        }+        val c: u8 = bytes.Bytes.at(data, i)+        i+++        size = size | (((c & 0x7f) as u64) << shift)+        shift = shift + 7+        more = (c & 0x80) != 0+    }+    return some GitVarint{value: size, next: i}+}++fn read_delta_varint(data: bytes.Bytes, start: usize) option[GitVarint] = {+    val v: mut u64 = 0+    val shift: mut u64 = 0+    val i: mut usize = start+    for {+        if i >= data.len || shift > 63 {+            return none+        }+        val c: u8 = bytes.Bytes.at(data, i)+        i+++        v = v | (((c & 0x7f) as u64) << shift)+        shift = shift + 7+        if (c & 0x80) == 0 {+            return some GitVarint{value: v, next: i}+        }+    }+    return none+}++fn apply_delta(base: bytes.Bytes, delta: bytes.Bytes) option[bytes.Bytes]= trust {+    val src_opt = read_delta_varint(delta, 0)+    val src_size: mut u64 = 0+    val p: mut usize = 0+    match src_opt {+        some r => {+            src_size = r.value+            p = r.next+        }+        none => {+            return none+        }+    }+    if src_size != base.len as u64 {+        return none+    }+    val dst_opt = read_delta_varint(delta, p)+    val dst_size: mut u64 = 0+    match dst_opt {+        some r => {+            dst_size = r.value+            p = r.next+        }+        none => {+            return none+        }+    }+    if dst_size > 2147483648 {+        return none+    }+    val cap: usize = dst_size as usize+    val out: ref u8 = @alloc(cap + 1) as ref u8+    val written: mut usize = 0+    for p < delta.len {+        val op: u8 = bytes.Bytes.at(delta, p)+        p+++        if (op & 0x80) != 0 {+            val off: mut u64 = 0+            val size: mut u64 = 0+            if (op & 0x01) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                off = off | (bytes.Bytes.at(delta, p) as u64)+                p+++            }+            if (op & 0x02) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                off = off | ((bytes.Bytes.at(delta, p) as u64) << 8)+                p+++            }+            if (op & 0x04) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                off = off | ((bytes.Bytes.at(delta, p) as u64) << 16)+                p+++            }+            if (op & 0x08) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                off = off | ((bytes.Bytes.at(delta, p) as u64) << 24)+                p+++            }+            if (op & 0x10) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                size = size | (bytes.Bytes.at(delta, p) as u64)+                p+++            }+            if (op & 0x20) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                size = size | ((bytes.Bytes.at(delta, p) as u64) << 8)+                p+++            }+            if (op & 0x40) != 0 {+                if p >= delta.len {+                    @free(out as ref void)+                    return none+                }+                size = size | ((bytes.Bytes.at(delta, p) as u64) << 16)+                p+++            }+            if size == 0 {+                size = 65536+            }+            if off > base.len as u64 || size > (base.len as u64) - off {+                @free(out as ref void)+                return none+            }+            if size > (cap as u64) - (written as u64) {+                @free(out as ref void)+                return none+            }+            if size > 0 {+                @memcpy(+                    @ptradd(out, written as i64) as ref void,+                    @ptradd(base.ptr, off as i64) as ref void,+                    size as usize+                )+            }+            written = written + size as usize+        } else {+            if op == 0 {+                @free(out as ref void)+                return none+            }+            val n: usize = op as usize+            if p + n > delta.len || n > cap - written {+                @free(out as ref void)+                return none+            }+            @memcpy(@ptradd(out, written as i64) as ref void, @ptradd(delta.ptr, p as i64) as ref void, n)+            p = p + n+            written = written + n+        }+    }+    if written != cap {+        @free(out as ref void)+        return none+    }+    return some bytes.bytes(out, cap)+}++fn find_oid(pack: ref GitPack, oid: bytes.Bytes) option[usize] = trust {+    pre {+        oid_len: oid.len == 20+    }+    val lo: mut usize = 0+    val hi: mut usize = pack.count+    for lo < hi {+        val mid: usize = lo + (hi - lo) / 2+        val cur: bytes.Bytes = bytes.bytes(@ptradd(pack.oids, (mid * 20) as i64), 20)+        val c: i64 = bytes.Bytes.cmp(cur, oid)+        if c == 0 {+            return some mid+        }+        if c < 0 {+            lo = mid + 1+        } else {+            hi = mid+        }+    }+    return none+}++fn offset_at(pack: ref GitPack, i: usize) u64= trust {+    return @load64(@ptradd(pack.offsets, (i * 8) as i64)) as u64+}++fn read_at(repo: GitRepo, pack: ref GitPack, start: u64) result[Object, GitError]= trust {+    val data: bytes.Bytes = pack.data+    val pos: mut usize = start as usize+    if pos >= data.len {+        return err GitError.Corrupt+    }+    val c0: u8 = bytes.Bytes.at(data, pos)+    val kind: u8 = (c0 >> 4) & 7+    val size_opt = read_be_varint(data, start as usize)+    val size: mut u64 = 0+    match size_opt {+        some v => {+            size = v.value+            pos = v.next+        }+        none => {+            return err GitError.Corrupt+        }+    }+    if size > 2147483648 {+        return err GitError.Unsupported+    }++    val base_oid: mut bytes.Bytes = bytes.empty()+    val base_off: mut u64 = 0+    val has_base_off: mut bool = false+    if kind == KIND_OFS_DELTA {+        if pos >= data.len {+            return err GitError.Corrupt+        }+        val c: u8 = bytes.Bytes.at(data, pos)+        pos+++        val acc: mut u64 = (c & 0x7f) as u64+        val more: mut bool = (c & 0x80) != 0+        for more {+            if pos >= data.len {+                return err GitError.Corrupt+            }+            val c2: u8 = bytes.Bytes.at(data, pos)+            pos+++            acc = ((acc + 1) << 7) | ((c2 & 0x7f) as u64)+            more = (c2 & 0x80) != 0+        }+        has_base_off = true+        base_off = start - acc+    } elif kind == KIND_REF_DELTA {+        if pos + 20 > data.len {+            return err GitError.Corrupt+        }+        base_oid = bytes.Bytes.slice(data, pos, pos + 20)+        pos = pos + 20+    }++    val comp: bytes.Bytes = bytes.Bytes.slice(data, pos, data.len)+    val inflated_opt = inflate_exact(comp, size as usize)+    val inflated: mut bytes.Bytes = bytes.empty()+    match inflated_opt {+        some x => {+            inflated = x+        }+        none => {+            return err GitError.Corrupt+        }+    }++    if kind >= KIND_COMMIT && kind <= KIND_TAG {+        return ok Object{kind: kind, body: inflated, alloc: inflated}+    }+    if kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA {+        @free(inflated.ptr as ref void)+        return err GitError.Corrupt+    }++    val base: mut Object = Object{kind: 0, body: bytes.empty(), alloc: bytes.empty()}+    if has_base_off {+        if base_off >= start {+            @free(inflated.ptr as ref void)+            return err GitError.Corrupt+        }+        val br = read_at(repo, pack, base_off)+        match br {+            ok b => {+                base = b+            }+            err e => {+                @free(inflated.ptr as ref void)+                return err e+            }+        }+    } else {+        val br2 = read(repo, base_oid)+        match br2 {+            ok b => {+                base = b+            }+            err e => {+                @free(inflated.ptr as ref void)+                return err e+            }+        }+    }++    val merged_opt = apply_delta(base.body, inflated)+    val merged: mut bytes.Bytes = bytes.empty()+    match merged_opt {+        some x => {+            merged = x+        }+        none => {+            free_object(base)+            @free(inflated.ptr as ref void)+            return err GitError.Corrupt+        }+    }+    val base_kind: u8 = base.kind+    free_object(base)+    @free(inflated.ptr as ref void)+    return ok Object{kind: base_kind, body: merged, alloc: merged}+}++fn read_loose(repo: GitRepo, oid: bytes.Bytes) option[Object]= trust {+    val hex: ref u8 = oid_hex(oid)+    val objroot: str.StringView = files.join(repo.git_dir, str.from_cstr(c"objects"))+    val dirname: str.StringView = str.view(hex, 2)+    val rest: str.StringView = str.view(@ptradd(hex, 2), 38)+    val dir: str.StringView = files.join(objroot, dirname)+    val path: str.StringView = files.join(dir, rest)+    files.free_path(objroot)+    files.free_path(dir)+    @free(hex as ref void)+    val exists: bool = files.exists_file(path)+    if !exists {+        files.free_path(path)+        return none+    }+    val data_opt = files.read_all(path)+    files.free_path(path)+    val compressed: mut bytes.Bytes = bytes.empty()+    match data_opt {+        some d => {+            compressed = d+        }+        none => {+            return none+        }+    }+    val inflated_opt = inflate_unknown(compressed)+    files.free_buffer(compressed)+    val inflated: mut bytes.Bytes = bytes.empty()+    match inflated_opt {+        some x => {+            inflated = x+        }+        none => {+            return none+        }+    }+    val space: mut usize = 0+    for space < inflated.len && bytes.Bytes.at(inflated, space) != 32 {+        space+++    }+    val nul: mut usize = space+    for nul < inflated.len && bytes.Bytes.at(inflated, nul) != 0 {+        nul+++    }+    if space == 0 || nul >= inflated.len {+        @free(inflated.ptr as ref void)+        return none+    }+    val kind: u8 = kind_from_name(bytes.Bytes.slice(inflated, 0, space))+    if kind == 0 {+        @free(inflated.ptr as ref void)+        return none+    }+    val size_text: bytes.Bytes = bytes.Bytes.slice(inflated, space + 1, nul)+    val declared: mut u64 = 0+    val i: mut usize = 0+    for i < size_text.len {+        val c: u8 = bytes.Bytes.at(size_text, i)+        if c < 48 || c > 57 {+            @free(inflated.ptr as ref void)+            return none+        }+        declared = declared * 10 + (c - 48) as u64+        i+++    }+    val body: bytes.Bytes = bytes.Bytes.slice(inflated, nul + 1, inflated.len)+    if body.len as u64 != declared {+        @free(inflated.ptr as ref void)+        return none+    }+    val o = Object{kind: kind, body: body, alloc: inflated}+    if !verify_hash(oid, kind, body) {+        free_object(o)+        return none+    }+    return some o+}++pub fn read(repo: GitRepo, oid: bytes.Bytes) result[Object, GitError]= trust {+    pre {+        oid_len: oid.len == 20+    }+    val loose = read_loose(repo, oid)+    match loose {+        some o => {+            return ok o+        }+        none => {+        }+    }+    val i: mut usize = 0+    for i < @len(repo.packs) {+        val p = pack_at(repo.packs, i)+        val found = find_oid(p, oid)+        if found is some idx {+            val r = read_at(repo, p, offset_at(p, idx))+            match r {+                ok o => {+                    if !verify_hash(oid, o.kind, o.body) {+                        free_object(o)+                        return err GitError.HashMismatch+                    }+                    return ok o+                }+                err e => {+                    return err e+                }+            }+        }+        i+++    }+    return err GitError.NotFound+}++fn pack_at(packs: list[ref GitPack], i: usize) ref GitPack = {+    val o = @get(packs, i)+    if o is some p {+        return p+    }+    assert false+    return none+}++fn parse_idx(data: bytes.Bytes, pack_count: usize, pack_trailer: bytes.Bytes) result[ref GitPack, GitError]= trust {+    if data.len < 40 {+        return err GitError.Corrupt+    }+    val trailer_off: usize = data.len - 20+    val check_opt = sha1_of(bytes.Bytes.slice(data, 0, trailer_off))+    val check: mut bytes.Bytes = bytes.empty()+    match check_opt {+        some d => {+            check = d+        }+        none => {+            return err GitError.OutOfMemory+        }+    }+    val check_ok: bool = bytes.Bytes.eql(check, bytes.Bytes.slice(data, trailer_off, data.len))+    free_digest(check)+    if !check_ok {+        return err GitError.Corrupt+    }+    if !bytes.Bytes.eql(+        bytes.Bytes.slice(data, data.len - 40, data.len - 20),+        pack_trailer+    ) {+        return err GitError.Corrupt+    }++    val is_v2: bool = data.len >= 8+        && bytes.Bytes.at(data, 0) == 255+        && bytes.Bytes.at(data, 1) == 116+        && bytes.Bytes.at(data, 2) == 79+        && bytes.Bytes.at(data, 3) == 99+    val fanout_off: mut usize = 0+    if is_v2 {+        fanout_off = 8+    }+    if is_v2 {+        val version: u32 = be32_at(data, 4)+        if version != 2 {+            return err GitError.Unsupported+        }+    }+    if data.len < fanout_off + 1024 + 40 {+        return err GitError.Corrupt+    }+    val n: usize = be32_at(data, fanout_off + 255 * 4) as usize+    if n != pack_count {+        return err GitError.Corrupt+    }+    val oids: ref u8 = @alloc(n * 20 + 1) as ref u8+    val offsets: ref u8 = @alloc(n * 8 + 1) as ref u8+    if is_v2 {+        val names_off: usize = fanout_off + 1024+        val crcs_off: usize = names_off + n * 20+        val offs_off: usize = crcs_off + n * 4+        val large_off: usize = offs_off + n * 4+        if large_off + 40 > data.len {+            @free(oids as ref void)+            @free(offsets as ref void)+            return err GitError.Corrupt+        }+        val large_bytes: usize = data.len - 40 - large_off+        if large_bytes % 8 != 0 {+            @free(oids as ref void)+            @free(offsets as ref void)+            return err GitError.Corrupt+        }+        val i: mut usize = 0+        for i < n {+            @memcpy(+                @ptradd(oids, (i * 20) as i64) as ref void,+                @ptradd(data.ptr, (names_off + i * 20) as i64) as ref void,+                20+            )+            val raw_off: u32 = be32_at(data, offs_off + i * 4)+            val resolved: mut u64 = raw_off as u64+            if (raw_off & 2147483648) != 0 {+                val idx: usize = (raw_off & 2147483647) as usize+                if idx * 8 + 8 > large_bytes {+                    @free(oids as ref void)+                    @free(offsets as ref void)+                    return err GitError.Corrupt+                }+                resolved = be64_at(data, large_off + idx * 8)+            }+            @store64(@ptradd(offsets, (i * 8) as i64), resolved as i64)+            i+++        }+    } else {+        val records_off: usize = 1024+        if records_off + n * 24 + 40 > data.len {+            @free(oids as ref void)+            @free(offsets as ref void)+            return err GitError.Corrupt+        }+        val j: mut usize = 0+        for j < n {+            val rec: usize = records_off + j * 24+            val off: u64 = be32_at(data, rec) as u64+            @store64(@ptradd(offsets, (j * 8) as i64), off as i64)+            @memcpy(+                @ptradd(oids, (j * 20) as i64) as ref void,+                @ptradd(data.ptr, (rec + 4) as i64) as ref void,+                20+            )+            j+++        }+    }++    val p: mut ref GitPack = @alloc(@sizeof(GitPack)) as ref GitPack+    p.path = str.view(none, 0)+    p.data = bytes.empty()+    p.count = n+    p.oids = oids+    p.offsets = offsets+    return ok p+}++fn open_pack(pack_path: str.StringView, idx_path: str.StringView) result[ref GitPack, GitError]= trust {+    val pdata_opt = files.read_all(pack_path)+    val pdata: mut bytes.Bytes = bytes.empty()+    match pdata_opt {+        some d => {+            pdata = d+        }+        none => {+            return err GitError.Io+        }+    }+    if pdata.len < 32 || !bytes.Bytes.eql(bytes.Bytes.slice(pdata, 0, 4), bytes.bytes(c"PACK", 4)) {+        files.free_buffer(pdata)+        return err GitError.Corrupt+    }+    val version: u32 = be32_at(pdata, 4)+    if version != 2 && version != 3 {+        files.free_buffer(pdata)+        return err GitError.Unsupported+    }+    val count: usize = be32_at(pdata, 8) as usize+    val trailer_off: usize = pdata.len - 20+    val pack_trailer: bytes.Bytes = bytes.Bytes.slice(pdata, trailer_off, pdata.len)+    val hash_opt = sha1_of(bytes.Bytes.slice(pdata, 0, trailer_off))+    val hash: mut bytes.Bytes = bytes.empty()+    match hash_opt {+        some d => {+            hash = d+        }+        none => {+            files.free_buffer(pdata)+            return err GitError.OutOfMemory+        }+    }+    val hash_ok: bool = bytes.Bytes.eql(hash, pack_trailer)+    free_digest(hash)+    if !hash_ok {+        files.free_buffer(pdata)+        return err GitError.Corrupt+    }++    val idata_opt = files.read_all(idx_path)+    val idata: mut bytes.Bytes = bytes.empty()+    match idata_opt {+        some d => {+            idata = d+        }+        none => {+            files.free_buffer(pdata)+            return err GitError.Io+        }+    }+    val pr = parse_idx(idata, count, pack_trailer)+    files.free_buffer(idata)+    val p: mut ref GitPack = none+    match pr {+        ok x => {+            p = x+        }+        err e => {+            files.free_buffer(pdata)+            return err e+        }+    }+    p.path = pack_path+    p.data = pdata+    return ok p+}++pub fn open(git_dir: str.StringView) result[GitRepo, GitError]= trust {+    val packs: mut list[ref GitPack] = lists.new[ref GitPack]()+    val pack_dir: str.StringView = files.join(git_dir, str.from_cstr(c"objects/pack"))+    if files.exists_dir(pack_dir) {+        val names: list[ref u8] = files.list_dir(pack_dir)+        for n in names {+            if files.name_ends_with(n, c".idx") {+                val iv: str.StringView = str.from_cstr(n)+                val base: str.StringView = str.view(iv.ptr, iv.len - 4)+                val pack_name: str.StringView = files.with_suffix(base, ".pack")+                val pack_path: str.StringView = files.join(pack_dir, pack_name)+                val idx_path: str.StringView = files.join(pack_dir, iv)+                files.free_path(pack_name)+                if files.exists_file(pack_path) {+                    val r = open_pack(pack_path, idx_path)+                    match r {+                        ok p => {+                            @append(packs, p)+                            files.free_path(idx_path)+                        }+                        err e => {+                            files.free_path(pack_path)+                            files.free_path(idx_path)+                            files.free_names(names)+                            files.free_path(pack_dir)+                            for x in packs {+                                free_pack(x)+                            }+                            @listfree(packs)+                            return err e+                        }+                    }+                } else {+                    files.free_path(pack_path)+                    files.free_path(idx_path)+                }+            }+        }+        files.free_names(names)+    }+    files.free_path(pack_dir)+    return ok GitRepo{git_dir: git_dir, packs: packs}+}++pub fn free_pack(p: ref GitPack) void= trust {+    files.free_buffer(p.data)+    if p.oids != none {+        @free(p.oids as ref void)+    }+    if p.offsets != none {+        @free(p.offsets as ref void)+    }+    if p.path.ptr != none {+        files.free_path(p.path)+    }+    @free(p as ref void)+}++pub fn free(repo: mut GitRepo) void= trust {+    for p in repo.packs {+        free_pack(p)+    }+    @listfree(repo.packs)+    if repo.git_dir.ptr != none {+        files.free_path(repo.git_dir)+    }+    repo.git_dir = str.view(none, 0)+}+--- /dev/null+++ b/src/src/git/oidmap.sx@@ -0,0 +1,195 @@+/// A small open-addressed map keyed by 20-byte git object IDs.+///+/// Slots store the key, a 32-byte payload, and a used flag. This is used for+/// reachability sets and for the in-memory git-to-vein ID maps during import.++val bytes = use("../core/bytes.sx")++pub val OID_LEN: usize = 20+pub val VALUE_LEN: usize = 32+pub val SLOT_LEN: usize = 56++pub type OidMap = {+    slots: mut ref u8+    cap: mut usize+    len: mut usize+}++fn round_cap(n: usize) usize = trust {+    val c: mut usize = 16+    for c < n {+        c = c * 2+    }+    return c+}++fn oid_ptr(map: OidMap, i: usize) ref u8 = trust {+    return @ptradd(map.slots, (i * SLOT_LEN + 1) as i64)+}++fn value_ptr(map: OidMap, i: usize) ref u8 = trust {+    return @ptradd(map.slots, (i * SLOT_LEN + 1 + OID_LEN) as i64)+}++fn used_at(map: OidMap, i: usize) bool = trust {+    return @load8(@ptradd(map.slots, (i * SLOT_LEN) as i64)) != 0+}++fn set_used(map: OidMap, i: usize) void = trust {+    @store8(@ptradd(map.slots, (i * SLOT_LEN) as i64), 1)+}++fn hash_oid(oid: bytes.Bytes) u64 = trust {+    val h: mut u64 = 1469598103934665603+    val k: mut usize = 0+    for k < OID_LEN {+        h = (h ^ (bytes.Bytes.at(oid, k) as u64)) * 1099511628211+        k+++    }+    return h+}++fn slot_eql(map: OidMap, i: usize, oid: bytes.Bytes) bool = trust {+    return bytes.Bytes.eql(bytes.bytes(oid_ptr(map, i), OID_LEN), oid)+}++fn copy_key(map: OidMap, i: usize, oid: bytes.Bytes) void = trust {+    @memcpy(oid_ptr(map, i) as ref void, oid.ptr as ref void, OID_LEN)+}++fn copy_value(map: OidMap, i: usize, value: bytes.Bytes) void = trust {+    @memset(value_ptr(map, i) as ref void, 0, VALUE_LEN)+    if value.len > 0 {+        val n: mut usize = value.len+        if n > VALUE_LEN {+            n = VALUE_LEN+        }+        @memcpy(value_ptr(map, i) as ref void, value.ptr as ref void, n)+    }+}++pub fn new(initial: usize) OidMap = trust {+    val cap: usize = round_cap(initial)+    val p: ref u8 = @alloc(cap * SLOT_LEN) as ref u8+    @memset(p as ref void, 0, cap * SLOT_LEN)+    return OidMap{slots: p, cap: cap, len: 0}+}++pub fn free(map: mut OidMap) void = trust {+    if map.slots != none {+        @free(map.slots as ref void)+    }+    map.slots = none+    map.cap = 0+    map.len = 0+}++pub fn count(map: OidMap) usize = trust {+    return map.len+}++fn insert_slot(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {+    val mask: usize = map.cap - 1+    val h: u64 = hash_oid(oid)+    val idx: mut usize = (h as usize) & mask+    for {+        if !used_at(map, idx) {+            set_used(map, idx)+            copy_key(map, idx, oid)+            copy_value(map, idx, value)+            map.len+++            return+        }+        if slot_eql(map, idx, oid) {+            copy_value(map, idx, value)+            return+        }+        idx = (idx + 1) & mask+    }+}++fn grow(map: mut OidMap) void = trust {+    val old_slots: mut ref u8 = map.slots+    val old_cap: usize = map.cap+    val new_cap: usize = old_cap * 2+    val p: ref u8 = @alloc(new_cap * SLOT_LEN) as ref u8+    @memset(p as ref void, 0, new_cap * SLOT_LEN)+    map.slots = p+    map.cap = new_cap+    map.len = 0+    val i: mut usize = 0+    for i < old_cap {+        if @load8(@ptradd(old_slots, (i * SLOT_LEN) as i64)) != 0 {+            val op: bytes.Bytes = bytes.bytes(@ptradd(old_slots, (i * SLOT_LEN + 1) as i64), OID_LEN)+            val vp: bytes.Bytes = bytes.bytes(+                @ptradd(old_slots, (i * SLOT_LEN + 1 + OID_LEN) as i64),+                VALUE_LEN+            )+            insert_slot(map, op, vp)+        }+        i+++    }+    @free(old_slots as ref void)+}++/// Insert or replace an entry. An empty `value` records membership only.+pub fn put(map: mut OidMap, oid: bytes.Bytes, value: bytes.Bytes) void = trust {+    pre {+        oid_len: oid.len == OID_LEN+        value_len: value.len == 0 || value.len <= VALUE_LEN+    }+    if (map.len + 1) * 10 >= map.cap * 7 {+        grow(map)+    }+    insert_slot(map, oid, value)+}++pub fn get(map: OidMap, oid: bytes.Bytes) option[bytes.Bytes] = trust {+    pre {+        oid_len: oid.len == OID_LEN+    }+    if map.cap == 0 {+        return none+    }+    val mask: usize = map.cap - 1+    val h: u64 = hash_oid(oid)+    val idx: mut usize = (h as usize) & mask+    for {+        if !used_at(map, idx) {+            return none+        }+        if slot_eql(map, idx, oid) {+            return some bytes.bytes(value_ptr(map, idx), VALUE_LEN)+        }+        idx = (idx + 1) & mask+    }+    return none+}++pub fn contains(map: OidMap, oid: bytes.Bytes) bool = trust {+    if get(map, oid) is some _ {+        return true+    }+    return false+}++pub fn slot_used(map: OidMap, i: usize) bool = trust {+    pre {+        in_bounds: i < map.cap+    }+    return used_at(map, i)+}++pub fn slot_oid(map: OidMap, i: usize) bytes.Bytes = trust {+    pre {+        in_bounds: i < map.cap+    }+    return bytes.bytes(oid_ptr(map, i), OID_LEN)+}++pub fn slot_value(map: OidMap, i: usize) bytes.Bytes = trust {+    pre {+        in_bounds: i < map.cap+    }+    return bytes.bytes(value_ptr(map, i), VALUE_LEN)+}--- /dev/null+++ b/src/src/git/refs.sx@@ -0,0 +1,300 @@+/// Read refs and HEAD directly from a git directory.++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 Ref = {+    name: mut bytes.Bytes+    oid: mut bytes.Bytes+}++pub type RefSet = {+    branches: mut list[ref Ref]+    tags: mut list[ref Ref]+    head: mut bytes.Bytes+}++fn new_ref(name: bytes.Bytes, oid: bytes.Bytes) ref Ref = trust {+    val r: mut ref Ref = @alloc(@sizeof(Ref)) as ref Ref+    r.name = name+    r.oid = oid+    return r+}++fn hex_value(c: u8) i32 = trust {+    if c >= 48 && c <= 57 {+        return (c - 48) as i32+    }+    if c >= 97 && c <= 102 {+        return (c - 87) as i32+    }+    if c >= 65 && c <= 70 {+        return (c - 55) as i32+    }+    return -1+}++pub fn parse_hex_oid(text: bytes.Bytes) option[bytes.Bytes] = trust {+    if text.len != 40 {+        return none+    }+    val out: ref u8 = @alloc(20) as ref u8+    val i: mut usize = 0+    for i < 20 {+        val hi: i32 = hex_value(bytes.Bytes.at(text, i * 2))+        val lo: i32 = hex_value(bytes.Bytes.at(text, i * 2 + 1))+        if hi < 0 || lo < 0 {+            @free(out as ref void)+            return none+        }+        @store8(@ptradd(out, i as i64), ((hi * 16 + lo) as u8))+        i+++    }+    return some bytes.bytes(out, 20)+}++fn trim_eol(data: bytes.Bytes) bytes.Bytes = trust {+    val end: mut usize = data.len+    for end > 0 && (bytes.Bytes.at(data, end - 1) == 10 || bytes.Bytes.at(data, end - 1) == 13) {+        end--+    }+    return bytes.Bytes.slice(data, 0, end)+}++fn read_line_file(path: str.StringView) option[bytes.Bytes] = trust {+    val data_opt = files.read_all(path)+    match data_opt {+        some d => {+            return some trim_eol(d)+        }+        none => {+            return none+        }+    }+}++fn starts_with(data: bytes.Bytes, prefix: bytes.Bytes) bool = trust {+    return bytes.Bytes.starts_with(data, prefix)+}++fn find_ref(refs: list[ref Ref], name: bytes.Bytes) option[bytes.Bytes] = trust {+    for r in refs {+        if bytes.Bytes.eql(r.name, name) {+            return some r.oid+        }+    }+    return none+}++fn replace_ref(refs: mut list[ref Ref], name: bytes.Bytes, oid: bytes.Bytes) void = trust {+    val i: mut usize = 0+    for i < @len(refs) {+        val o = @get(refs, i)+        if o is some r {+            if bytes.Bytes.eql(r.name, name) {+                r.oid = oid+                return+            }+        }+        i+++    }+    @append(refs, new_ref(bytes.Bytes.dup(name), oid))+}++fn short_name(full: bytes.Bytes, prefix_len: usize) bytes.Bytes = trust {+    return bytes.Bytes.slice(full, prefix_len, full.len)+}++fn read_packed_refs(+    git_dir: str.StringView,+    branches: mut list[ref Ref],+    tags: mut list[ref Ref]+) void = trust {+    val path: str.StringView = files.join(git_dir, str.from_cstr(c"packed-refs"))+    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+        }+    }+    val pos: mut usize = 0+    for pos < data.len {+        val end: mut usize = pos+        for end < data.len && bytes.Bytes.at(data, end) != 10 {+            end+++        }+        val line: bytes.Bytes = bytes.Bytes.slice(data, pos, end)+        pos = end + 1+        if line.len == 0 || bytes.Bytes.at(line, 0) == 35 || bytes.Bytes.at(line, 0) == 94 {+            continue+        }+        val space: mut usize = 0+        for space < line.len && bytes.Bytes.at(line, space) != 32 {+            space+++        }+        if space == 0 || space >= line.len {+            continue+        }+        val hex: bytes.Bytes = bytes.Bytes.slice(line, 0, space)+        val name: bytes.Bytes = bytes.Bytes.slice(line, space + 1, line.len)+        val oid_opt = parse_hex_oid(hex)+        match oid_opt {+            some oid => {+                if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {+                    replace_ref(branches, short_name(name, 11), oid)+                } elif starts_with(name, bytes.bytes(c"refs/tags/", 10)) {+                    replace_ref(tags, short_name(name, 10), oid)+                }+            }+            none => {+            }+        }+    }+    files.free_buffer(data)+}++fn read_ref_dir(+    base: str.StringView,+    rel: str.StringView,+    refs: mut list[ref Ref]+) void = trust {+    val dir: mut str.StringView = base+    if rel.len != 0 {+        dir = files.join(base, rel)+    }+    val names: list[ref u8] = files.list_dir(dir)+    for n in names {+        val nv: str.StringView = str.from_cstr(n)+        val child_rel: mut str.StringView = files.with_suffix(nv, str.view(none, 0))+        if rel.len != 0 {+            files.free_path(child_rel)+            child_rel = files.join3(rel, str.from_cstr(c"/"), nv)+        }+        val child_path: str.StringView = files.join(base, child_rel)+        if files.exists_dir(child_path) {+            read_ref_dir(base, child_rel, refs)+        } else {+            val content_opt = read_line_file(child_path)+            match content_opt {+                some content => {+                    val oid_opt = parse_hex_oid(content)+                    match oid_opt {+                        some oid => {+                            replace_ref(refs, bytes.Bytes.dup(bytes.from_cstr(child_rel.ptr)), oid)+                        }+                        none => {+                        }+                    }+                }+                none => {+                }+            }+        }+        files.free_path(child_rel)+        files.free_path(child_path)+    }+    files.free_names(names)+    if rel.len != 0 {+        files.free_path(dir)+    }+}++fn resolve_head(git_dir: str.StringView, branches: list[ref Ref], tags: list[ref Ref]) bytes.Bytes = trust {+    val path: str.StringView = files.join(git_dir, str.from_cstr(c"HEAD"))+    val data_opt = read_line_file(path)+    files.free_path(path)+    val data: mut bytes.Bytes = bytes.empty()+    match data_opt {+        some d => {+            data = d+        }+        none => {+            return bytes.empty()+        }+    }+    if starts_with(data, bytes.bytes(c"ref: ", 5)) {+        val name: bytes.Bytes = bytes.Bytes.slice(data, 5, data.len)+        if starts_with(name, bytes.bytes(c"refs/heads/", 11)) {+            val short: bytes.Bytes = short_name(name, 11)+            val found = find_ref(branches, short)+            match found {+                some oid => {+                    files.free_buffer(data)+                    return bytes.Bytes.dup(oid)+                }+                none => {+                }+            }+        }+        if starts_with(name, bytes.bytes(c"refs/tags/", 10)) {+            val short2: bytes.Bytes = short_name(name, 10)+            val found2 = find_ref(tags, short2)+            match found2 {+                some oid => {+                    files.free_buffer(data)+                    return bytes.Bytes.dup(oid)+                }+                none => {+                }+            }+        }+        files.free_buffer(data)+        return bytes.empty()+    }+    val oid_opt = parse_hex_oid(data)+    files.free_buffer(data)+    match oid_opt {+        some oid => {+            return oid+        }+        none => {+            return bytes.empty()+        }+    }+}++pub fn read(git_dir: str.StringView) RefSet = trust {+    val branches: mut list[ref Ref] = lists.new[ref Ref]()+    val tags: mut list[ref Ref] = lists.new[ref Ref]()+    read_packed_refs(git_dir, branches, tags)+    val heads_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/heads"))+    read_ref_dir(heads_base, str.view(none, 0), branches)+    files.free_path(heads_base)+    val tags_base: str.StringView = files.join(git_dir, str.from_cstr(c"refs/tags"))+    read_ref_dir(tags_base, str.view(none, 0), tags)+    files.free_path(tags_base)+    val head: bytes.Bytes = resolve_head(git_dir, branches, tags)+    return RefSet{branches: branches, tags: tags, head: head}+}++fn free_refs(refs: list[ref Ref]) void = trust {+    for r in refs {+        if r.name.ptr != none {+            val np: mut ref void = r.name.ptr as ref void+            @free(np)+        }+        if r.oid.ptr != none {+            val op: mut ref void = r.oid.ptr as ref void+            @free(op)+        }+        val rp: mut ref void = r as ref void+        @free(rp)+    }+    @listfree(refs)+}++pub fn free(set: RefSet) void = trust {+    free_refs(set.branches)+    free_refs(set.tags)+    if set.head.ptr != none {+        val hp: mut ref void = set.head.ptr as ref void+        @free(hp)+    }+}--- a/src/src/io/native.sx+++ b/src/src/io/native.sx@@ -42,6 +42,11 @@         off = off + n as usize     }     return true+}++/// Write all of `data` to an already-open descriptor.+pub fn write_fd_all(fd: i32, data: bytes.Bytes) bool = trust {+    return write_all_fd(fd, data) }  fn sync_dir(dir: str.StringView) bool = {--- a/src/src/main.sx+++ b/src/src/main.sx@@ -1,3 +1,6 @@+lib "z"+lib "crypto"+ val stdio        = use("std/stdio") val str          = use("std/string") val bytes        = use("core/bytes.sx")@@ -4,6 +7,8 @@ val init_cmd     = use("cli/init_cmd.sx") val fsck_cmd     = use("cli/fsck_cmd.sx") val selftest_cmd = use("cli/selftest_cmd.sx")+val git_cmd      = use("cli/git_cmd.sx")+val checkout_cmd = use("cli/checkout_cmd.sx")  fn cmd_is(a: ref u8, text: ref u8, len: usize) bool = {     if a == none {@@ -18,19 +23,42 @@     stdio.puts("usage: vn <command> [arguments]")     stdio.puts("")     stdio.puts("commands:")-    stdio.puts("  init [path]          create a repository")+    stdio.puts("  init [path] [--git-import <gitdir>]")+    stdio.puts("                       create a repository, optionally importing git")+    stdio.puts("  git import [--source <gitdir>] [path]")+    stdio.puts("                       import reachable git commits and refs")+    stdio.puts("  checkout [rev]       write a revision into the working directory")     stdio.puts("  fsck [path] [-v]     verify pack, index, object, and op-log integrity")-    stdio.puts("  self-test            run the M0 format self-tests")+    stdio.puts("  self-test            run the format self-tests")     stdio.puts("  version              print version information") } -fn run_init(args: list[ref u8], start: usize) i32 = {-    val path_opt = @get(args, start)+fn run_init(args: list[ref u8], start: usize) i32 = trust {     val mut_path: mut str.StringView = str.from_cstr(c".")-    if path_opt is some p {-        mut_path = str.from_cstr(p)+    val source: mut option[str.StringView] = none+    val i: mut usize = start+    for i < @len(args) {+        val o = @get(args, i)+        if o is some a {+            if cmd_is(a, c"--git-import", 12) {+                if i + 1 >= @len(args) {+                    stdio.eprint("vn: --git-import requires a path\n", {})+                    return 1+                }+                val s_opt = @get(args, i + 1)+                if s_opt is some s {+                    source = some str.from_cstr(s)+                }+                i = i + 2+            } else {+                mut_path = str.from_cstr(a)+                i+++            }+        } else {+            i+++        }     }-    return init_cmd.run(mut_path)+    return init_cmd.run(mut_path, source) }  fn run_fsck(args: list[ref u8], start: usize) i32 = trust {@@ -71,6 +99,12 @@      if cmd_is(cmd, c"init", 4) {         return run_init(args, 2)+    }+    if cmd_is(cmd, c"git", 3) {+        return git_cmd.run(args, 2)+    }+    if cmd_is(cmd, c"checkout", 8) {+        return checkout_cmd.run(args, 2)     }     if cmd_is(cmd, c"fsck", 4) {         return run_fsck(args, 2)--- a/src/src/object/blob.sx+++ b/src/src/object/blob.sx@@ -251,7 +251,7 @@         val n: usize = fastcdc.next_len(trust @ptradd(data, off as i64), len - off)         val chunk: bytes.Bytes = bytes.Bytes.slice(bytes.bytes(data, len), off, off + n)         val cid: objid.Id = objid.object_id(types.CHUNK, chunk)-        @append(objects, raw.raw(types.CHUNK, chunk))+        @append(objects, raw.raw(types.CHUNK, bytes.Bytes.dup(chunk)))         @append(level, new_node(cid, n as u64))         off = off + n     }--- a/src/src/object/raw.sx+++ b/src/src/object/raw.sx@@ -17,7 +17,7 @@  pub fn free_objects(objects: list[ref RawObject]) void = {     for o in objects {-        if o.type_byte != 1 {+        if o.body.ptr != none {             val body_ptr: mut ref void = o.body.ptr as ref void             trust @free(body_ptr)         }--- a/src/src/store/layout.sx+++ b/src/src/store/layout.sx@@ -89,6 +89,22 @@  pub fn op_heads_dir(r: Repo) str.StringView = {     return files.join(root_view(r), ".vein/op-heads")+}++pub fn git_dir(r: Repo) str.StringView = {+    return files.join(root_view(r), ".vein/git")+}++pub fn git_map_dir(r: Repo) str.StringView = {+    return files.join(root_view(r), ".vein/git-map")+}++pub fn raw_dir(r: Repo) str.StringView = {+    return files.join(root_view(r), ".vein/git-map/raw")+}++pub fn working_copy_dir(r: Repo) str.StringView = {+    return files.join(root_view(r), ".vein/working-copy") }  pub fn config_path(r: Repo) str.StringView = {@@ -147,6 +163,9 @@         return false     }     if !mkdirs_under(r, ".vein/git-map") {+        return false+    }+    if !mkdirs_under(r, ".vein/git-map/raw") {         return false     }     if !mkdirs_under(r, ".vein/working-copy") {--- a/src/src/store/pack.sx+++ b/src/src/store/pack.sx@@ -330,7 +330,7 @@         pack_bytes.len - 32,         pack_bytes.len     )-    records.sort_by_id(metas)+    trust records.sort_by_id(metas)     val index_bytes: bytes.Bytes = index.encode(metas, pack_trailer)      val name_hex: ref u8 = @alloc(65) as ref u8--- a/src/src/store/records.sx+++ b/src/src/store/records.sx@@ -1,6 +1,7 @@ /// Metadata kept per object while a pack and its index are built.  val objid = use("../object/id.sx")+val lists = use("../core/lists.sx")  pub type RecordMeta = {     id: mut objid.Id@@ -23,49 +24,94 @@     return r } -fn at(records: list[ref RecordMeta], i: usize) ref RecordMeta = {-    val o = @get(records, i)-    if o is some v {-        return v+++fn ref_at(xs: list[ref RecordMeta], i: usize) ref RecordMeta = {+    val o = @get(xs, i)+    if o is some r {+        return r     }     assert false     return none } -fn swap(a: mut ref RecordMeta, b: mut ref RecordMeta) void = {-    val id: objid.Id = a.id-    val off: u64 = a.offset-    val ty: u8 = a.type_byte-    val rl: u64 = a.raw_len-    a.id = b.id-    a.offset = b.offset-    a.type_byte = b.type_byte-    a.raw_len = b.raw_len-    b.id = id-    b.offset = off-    b.type_byte = ty-    b.raw_len = rl+fn merge_run(+    src: list[ref RecordMeta],+    dst: mut list[ref RecordMeta],+    left: usize,+    mid: usize,+    right: usize+) void = {+    val i: mut usize = left+    val j: mut usize = mid+    val k: mut usize = left+    for k < right {+        val take_left: mut bool = false+        if i >= mid {+            take_left = false+        } elif j >= right {+            take_left = true+        } else {+            take_left = objid.Id.cmp(ref_at(src, i).id, ref_at(src, j).id) <= 0+        }+        if take_left {+            @set(dst, k, ref_at(src, i))+            i+++        } else {+            @set(dst, k, ref_at(src, j))+            j+++        }+        k+++    } } -/// Selection sort by object ID. Record counts per pack are modest in M0; the-/// sort is allocation-free.-pub fn sort_by_id(records: list[ref RecordMeta]) void = {+/// Stable bottom-up merge sort by object ID.+pub fn sort_by_id(records: mut list[ref RecordMeta]) void = trust {     val n: usize = @len(records)+    if n < 2 {+        return+    }+    val src: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()+    val dst: mut list[ref RecordMeta] = lists.new[ref RecordMeta]()     val i: mut usize = 0     for i < n {-        val min: mut usize = i-        val j: mut usize = i + 1-        for j < n {-            val rj = at(records, j)-            val rmin = at(records, min)-            if objid.Id.cmp(rj.id, rmin.id) < 0 {-                min = j-            }-            j++-        }-        if min != i {-            swap(at(records, i), at(records, min))+        val o = @get(records, i)+        if o is some r {+            @append(src, r)+            @append(dst, r)+        } else {+            @append(src, none)+            @append(dst, none)         }         i+++    }+    val mut_a: mut list[ref RecordMeta] = src+    val mut_b: mut list[ref RecordMeta] = dst+    val width: mut usize = 1+    for width < n {+        val left: mut usize = 0+        for left < n {+            val mid: mut usize = n+            if left + width < n {+                mid = left + width+            }+            val right: mut usize = n+            if left + 2 * width < n {+                right = left + 2 * width+            }+            merge_run(mut_a, mut_b, left, mid, right)+            left = left + 2 * width+        }+        val tmp: list[ref RecordMeta] = mut_a+        mut_a = mut_b+        mut_b = tmp+        width = width * 2+    }+    val j: mut usize = 0+    for j < n {+        @set(records, j, ref_at(mut_a, j))+        j++     }+    @listfree(src)+    @listfree(dst) }--- /dev/null+++ b/src/src/store/state.sx@@ -0,0 +1,263 @@+/// Read the current operation/view state and advance operation heads.++val str       = use("std/string")+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 operation = use("../object/operation.sx")+val view      = use("../object/view.sx")+val store     = use("../store/store.sx")+val layout    = use("../store/layout.sx")+val files     = use("../io/files.sx")+val native    = use("../io/native.sx")++pub fn read_body(+    handles: list[ref store.Handle],+    id: objid.Id,+    expected: u8+) option[bytes.Bytes] = trust {+    val loc: mut store.Loc = store.Loc{pack_index: 0, record_index: 0, kind: 0}+    if !store.find_handles(handles, id, loc) {+        return none+    }+    if loc.kind != expected {+        return none+    }+    val body_opt = store.get_handles(handles, loc)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        ok b => {+            body = b+        }+        err _ => {+            return none+        }+    }+    val computed: objid.Id = objid.object_id(expected, body)+    val same: bool = objid.Id.eql(computed, id)+    if computed.ptr != none {+        val cp: mut ref void = computed.ptr as ref void+        @free(cp)+    }+    if !same {+        files.free_buffer(body)+        return none+    }+    return some body+}++pub fn read_view(handles: list[ref store.Handle], id: objid.Id) option[ref view.View] = trust {+    val body_opt = read_body(handles, id, types.VIEW)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        some b => {+            body = b+        }+        none => {+            return none+        }+    }+    val decoded = view.decode(body)+    match decoded {+        ok v => {+            return some v+        }+        err _ => {+            files.free_buffer(body)+            return none+        }+    }+}++pub fn read_operation(handles: list[ref store.Handle], id: objid.Id) option[ref operation.Operation] = trust {+    val body_opt = read_body(handles, id, types.OPERATION)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        some b => {+            body = b+        }+        none => {+            return none+        }+    }+    val decoded = operation.decode(body)+    match decoded {+        ok op => {+            return some op+        }+        err _ => {+            files.free_buffer(body)+            return none+        }+    }+}++fn parse_head_name(name: ref u8) option[objid.Id] = trust {+    val n: i64 = @strlen(name)+    if n != 64 {+        return none+    }+    val raw: ref u8 = @alloc(32) as ref u8+    val i: mut usize = 0+    for i < 32 {+        val hex: bytes.Bytes = bytes.bytes(name, 64)+        val hi_c: u8 = bytes.Bytes.at(hex, i * 2)+        val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)+        val hi: mut i32 = -1+        val lo: mut i32 = -1+        if hi_c >= 48 && hi_c <= 57 {+            hi = (hi_c - 48) as i32+        } elif hi_c >= 97 && hi_c <= 102 {+            hi = (hi_c - 87) as i32+        } elif hi_c >= 65 && hi_c <= 70 {+            hi = (hi_c - 55) as i32+        }+        if lo_c >= 48 && lo_c <= 57 {+            lo = (lo_c - 48) as i32+        } elif lo_c >= 97 && lo_c <= 102 {+            lo = (lo_c - 87) as i32+        } elif lo_c >= 65 && lo_c <= 70 {+            lo = (lo_c - 55) as i32+        }+        if hi < 0 || lo < 0 {+            @free(raw as ref void)+            return none+        }+        @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))+        i+++    }+    return some objid.id(raw)+}++fn sort_ids(ids: mut list[objid.Id]) void = trust {+    val n: usize = @len(ids)+    val i: mut usize = 1+    for i < n {+        val cur = @get(ids, i)+        val cid: mut objid.Id = objid.id_none()+        if cur is some v {+            cid = v+        }+        val j: mut usize = i+        for j > 0 {+            val prev_opt = @get(ids, j - 1)+            val prev: mut objid.Id = objid.id_none()+            if prev_opt is some v2 {+                prev = v2+            }+            if objid.Id.cmp(prev, cid) <= 0 {+                break+            }+            @set(ids, j, prev)+            j--+        }+        @set(ids, j, cid)+        i+++    }+}++pub fn heads(repo: layout.Repo) list[objid.Id] = trust {+    val out: mut list[objid.Id] = lists.new[objid.Id]()+    val dir: str.StringView = layout.op_heads_dir(repo)+    if !files.exists_dir(dir) {+        files.free_path(dir)+        return out+    }+    val names: list[ref u8] = files.list_dir(dir)+    for n in names {+        val parsed = parse_head_name(n)+        match parsed {+            some id => {+                @append(out, id)+            }+            none => {+            }+        }+    }+    files.free_names(names)+    files.free_path(dir)+    sort_ids(out)+    return out+}++pub fn current_view(repo: layout.Repo, handles: list[ref store.Handle]) option[ref view.View] = trust {+    val hs: list[objid.Id] = heads(repo)+    if @len(hs) == 0 {+        return none+    }+    val first = @get(hs, 0)+    val op_id: mut objid.Id = objid.id_none()+    if first is some v {+        op_id = v+    }+    val op_opt = read_operation(handles, op_id)+    match op_opt {+        some op => {+            val v_opt = read_view(handles, op.view)+            operation.free_operation(op)+            for h in hs {+                if h.ptr != none {+                    val hp: mut ref void = h.ptr as ref void+                    @free(hp)+                }+            }+            @listfree(hs)+            return v_opt+        }+        none => {+            for h in hs {+                if h.ptr != none {+                    val hp2: mut ref void = h.ptr as ref void+                    @free(hp2)+                }+            }+            @listfree(hs)+            return none+        }+    }+}++pub fn empty_view() ref view.View = trust {+    val v: mut ref view.View = @alloc(@sizeof(view.View)) as ref view.View+    v.heads = lists.new[objid.Id]()+    v.bookmarks = lists.new[ref view.Bookmark]()+    v.tags = lists.new[ref view.TagRef]()+    v.remote_refs = lists.new[ref view.RemoteRef]()+    v.working_copies = lists.new[ref view.WorkspaceRef]()+    return v+}++pub fn head_name(id: objid.Id) ref u8 = trust {+    return objid.Id.hex(id)+}++pub fn write_head(repo: layout.Repo, id: objid.Id) bool = trust {+    val hex: ref u8 = head_name(id)+    val dir: str.StringView = layout.op_heads_dir(repo)+    val name: str.StringView = str.from_cstr(hex)+    val final: str.StringView = files.join(dir, name)+    val tmpd: str.StringView = layout.tmp_dir(repo)+    val tmpname: str.StringView = files.with_suffix(name, str.from_cstr(c".tmp"))+    val tmp: str.StringView = files.join(tmpd, tmpname)+    val success: bool = native.write_atomic(tmp, final, tmpd, dir, bytes.empty())+    files.free_path(dir)+    files.free_path(tmpd)+    files.free_path(final)+    files.free_path(tmpname)+    files.free_path(tmp)+    @free(hex as ref void)+    return success+}++pub fn delete_head(repo: layout.Repo, id: objid.Id) bool = trust {+    val hex: ref u8 = head_name(id)+    val dir: str.StringView = layout.op_heads_dir(repo)+    val name: str.StringView = str.from_cstr(hex)+    val path: str.StringView = files.join(dir, name)+    val success: bool = files.delete(path)+    files.free_path(dir)+    files.free_path(path)+    @free(hex as ref void)+    return success+}--- /dev/null+++ b/src/src/worktree/checkout.sx@@ -0,0 +1,783 @@+/// Parallel, path-safe checkout from a vein tree into the working directory.++val str       = use("std/string")+val stdio     = use("std/stdio")+val allocators = use("std/allocators")+val thread    = use("std/thread")+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 names     = use("../object/names.sx")+val blob      = use("../object/blob.sx")+val tree      = use("../object/tree.sx")+val commit    = use("../object/commit.sx")+val view      = use("../object/view.sx")+val store     = use("../store/store.sx")+val layout    = use("../store/layout.sx")+val state     = use("../store/state.sx")+val files     = use("../io/files.sx")+val native    = use("../io/native.sx")++extern (C) fn openat(dirfd: i32, path: ref u8, flags: i32, mode: i32) i32 = "openat"+extern (C) fn mkdirat(dirfd: i32, path: ref u8, mode: i32) i32 = "mkdirat"+extern (C) fn symlinkat(target: ref u8, newdirfd: i32, linkpath: ref u8) i32 = "symlinkat"+extern (C) fn unlinkat(dirfd: i32, path: ref u8, flags: i32) i32 = "unlinkat"+extern (C) fn close(fd: i32) i32 = "close"+extern (C) fn fchmod(fd: i32, mode: u32) i32 = "fchmod"+extern (C) fn sysconf(name: i32) i64 = "sysconf"++fn o_wronly() i32 = trust {+    return 1+}++fn o_creat() i32 = trust {+    when linux {+        return 64+    }+    when macos {+        return 512+    }+    return 64+}++fn o_trunc() i32 = trust {+    when linux {+        return 512+    }+    when macos {+        return 1024+    }+    return 512+}++fn o_nofollow() i32 = trust {+    when linux {+        return 131072+    }+    when macos {+        return 256+    }+    return 0+}++fn o_directory() i32 = trust {+    when linux {+        return 65536+    }+    when macos {+        return 1048576+    }+    return 0+}++fn o_cloexec() i32 = trust {+    when linux {+        return 524288+    }+    when macos {+        return 16777216+    }+    return 0+}++val DIR_MODE: u32 = 493+val FILE_MODE: u32 = 420+val EXEC_MODE: u32 = 493++fn cpu_count() usize = trust {+    when linux {+        val n: i64 = sysconf(84)+        if n > 0 {+            return n as usize+        }+    }+    when macos {+        val n2: i64 = sysconf(58)+        if n2 > 0 {+            return n2 as usize+        }+    }+    return 4+}++pub type CheckoutTask = {+    path: mut bytes.Bytes+    kind: mut u8+    target: mut objid.Id+}++pub type CheckoutWalk = {+    handles: list[ref store.Handle]+    tasks: mut list[ref CheckoutTask]+    dirs: mut list[bytes.Bytes]+    failed: mut bool+    error: mut bytes.Bytes+}++pub type CheckoutJob = {+    handles: mut list[ref store.Handle]+    root_fd: mut i32+    tasks: mut list[ref CheckoutTask]+    start: mut usize+    step: mut usize+    failed: mut bool+    error: mut bytes.Bytes+}++type CheckoutTarget = {+    fd: i32+    name: ref u8+    owned_fd: 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 join_bytes(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 component_cstr(path: bytes.Bytes, start: usize, end: usize) ref u8 = trust {+    val n: usize = end - start+    val out: ref u8 = @alloc(n + 1) as ref u8+    if n > 0 {+        @memcpy(out as ref void, @ptradd(path.ptr, start as i64) as ref void, n)+    }+    @store8(@ptradd(out, n as i64), 0)+    return out+}++fn next_slash(path: bytes.Bytes, start: usize) usize = trust {+    val i: mut usize = start+    for i < path.len && bytes.Bytes.at(path, i) != 47 {+        i+++    }+    return i+}++fn valid_checkout_name(name: bytes.Bytes) bool = trust {+    if !names.valid_name(name) {+        return false+    }+    if bytes.Bytes.eql_ascii_ci(name, bytes.bytes(c".git", 4)) {+        return false+    }+    return true+}++fn ensure_dir(root_fd: i32, path: bytes.Bytes) bool = trust {+    val pos: mut usize = 0+    val cur: mut i32 = root_fd+    val owned: mut bool = false+    for pos < path.len {+        val end: usize = next_slash(path, pos)+        if end == pos {+            if owned {+                close(cur)+            }+            return false+        }+        val comp: ref u8 = component_cstr(path, pos, end)+        val flags: i32 = o_directory() | o_nofollow() | o_cloexec()+        val next: mut i32 = openat(cur, comp, flags, 0)+        if next < 0 {+            val made: i32 = mkdirat(cur, comp, DIR_MODE as i32)+            if made != 0 {+                next = openat(cur, comp, flags, 0)+            } else {+                next = openat(cur, comp, flags, 0)+            }+        }+        @free(comp as ref void)+        if next < 0 {+            if owned {+                close(cur)+            }+            return false+        }+        if owned {+            close(cur)+        }+        cur = next+        owned = true+        if end == path.len {+            break+        }+        pos = end + 1+    }+    if owned {+        close(cur)+    }+    return true+}++fn open_parent(root_fd: i32, path: bytes.Bytes) option[CheckoutTarget] = trust {+    val last_slash: mut i64 = -1+    val i: mut usize = 0+    for i < path.len {+        if bytes.Bytes.at(path, i) == 47 {+            last_slash = i as i64+        }+        i+++    }+    val cur: mut i32 = root_fd+    val owned: mut bool = false+    if last_slash >= 0 {+        val pos: mut usize = 0+        val stop: usize = last_slash as usize+        for pos < stop {+            val end: usize = next_slash(path, pos)+            if end == pos || end > stop {+                if owned {+                    close(cur)+                }+                return none+            }+            val comp: ref u8 = component_cstr(path, pos, end)+            val next: i32 = openat(cur, comp, o_directory() | o_nofollow() | o_cloexec(), 0)+            @free(comp as ref void)+            if next < 0 {+                if owned {+                    close(cur)+                }+                return none+            }+            if owned {+                close(cur)+            }+            cur = next+            owned = true+            pos = end + 1+        }+    }+    val name_start: mut usize = 0+    if last_slash >= 0 {+        name_start = last_slash as usize + 1+    }+    if name_start >= path.len {+        if owned {+            close(cur)+        }+        return none+    }+    val name: ref u8 = component_cstr(path, name_start, path.len)+    return some CheckoutTarget{fd: cur, name: name, owned_fd: owned}+}++fn close_target(t: CheckoutTarget) void = trust {+    if t.owned_fd {+        close(t.fd)+    }+    val np: mut ref void = t.name as ref void+    @free(np)+}++fn write_blob_data(+    handles: list[ref store.Handle],+    fd: i32,+    blob_id: objid.Id,+    depth: usize+) bool = trust {+    if depth > 64 {+        return false+    }+    val body_opt = state.read_body(handles, blob_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 success: mut bool = true+    if b.form == blob.FORM_INLINE {+        success = native.write_fd_all(fd, 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 => {+                    if !native.write_fd_all(fd, chunk) {+                        success = false+                    }+                    files.free_buffer(chunk)+                }+                none => {+                    success = false+                }+            }+            if !success {+                break+            }+        }+    } else {+        for e in b.entries {+            if !write_blob_data(handles, fd, e.id, depth + 1) {+                success = false+                break+            }+        }+    }+    blob.free_blob(b)+    files.free_buffer(body)+    return success+}++fn write_symlink(handles: list[ref store.Handle], t: CheckoutTarget, blob_id: objid.Id) bool = trust {+    val body_opt = state.read_body(handles, blob_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 success: mut bool = false+    if b.form == blob.FORM_INLINE {+        val target: ref u8 = @alloc(b.data.len + 1) as ref u8+        if b.data.len > 0 {+            @memcpy(target as ref void, b.data.ptr as ref void, b.data.len)+        }+        @store8(@ptradd(target, b.data.len as i64), 0)+        val _ = unlinkat(t.fd, t.name, 0)+        success = symlinkat(target, t.fd, t.name) == 0+        @free(target as ref void)+    }+    blob.free_blob(b)+    files.free_buffer(body)+    return success+}++fn write_task(job: ref CheckoutJob, task: ref CheckoutTask) bool = trust {+    val target_opt = open_parent(job.root_fd, task.path)+    match target_opt {+        some t => {+            val success: mut bool = false+            if task.kind == tree.KIND_SYMLINK {+                success = write_symlink(job.handles, t, task.target)+            } else {+                val flags: i32 = o_wronly() | o_creat() | o_trunc() | o_nofollow() | o_cloexec()+                val mode: u32 = FILE_MODE+                val mut_fd: mut i32 = openat(t.fd, t.name, flags, mode as i32)+                if mut_fd < 0 {+                    val _ = unlinkat(t.fd, t.name, 0)+                    mut_fd = openat(t.fd, t.name, flags, mode as i32)+                }+                val fd: i32 = mut_fd+                if fd >= 0 {+                    success = write_blob_data(job.handles, fd, task.target, 0)+                    if success {+                        val want: mut u32 = FILE_MODE+                        if task.kind == tree.KIND_EXECUTABLE {+                            want = EXEC_MODE+                        }+                        if fchmod(fd, want) != 0 {+                            success = false+                        }+                    }+                    close(fd)+                }+            }+            close_target(t)+            return success+        }+        none => {+            return false+        }+    }+}++fn checkout_worker(arg: ref void) ref void = trust {+    val job: mut ref CheckoutJob = arg as ref CheckoutJob+    val i: mut usize = job.start+    for i < @len(job.tasks) {+        val item = @get(job.tasks, i)+        if item is some task {+            if !write_task(job, task) {+                job.failed = true+                job.error = bytes.Bytes.dup(task.path)+                break+            }+        }+        i = i + job.step+    }+    return none+}++fn add_task(+    walk: mut CheckoutWalk,+    path: bytes.Bytes,+    kind: u8,+    target: objid.Id+) void = trust {+    val t: mut ref CheckoutTask = @alloc(@sizeof(CheckoutTask)) as ref CheckoutTask+    t.path = path+    t.kind = kind+    t.target = copy_id(target)+    @append(walk.tasks, t)+}++fn walk_tree(+    walk: mut CheckoutWalk,+    tree_id: objid.Id,+    prefix: bytes.Bytes,+    depth: usize+) void = trust {+    if walk.failed {+        return+    }+    if depth > 4096 {+        walk.failed = true+        return+    }+    val body_opt = state.read_body(walk.handles, tree_id, types.TREE)+    val body: mut bytes.Bytes = bytes.empty()+    match body_opt {+        some b => {+            body = b+        }+        none => {+            walk.failed = true+            return+        }+    }+    val decoded = tree.decode(body)+    val t: mut ref tree.Tree = none+    match decoded {+        ok x => {+            t = x+        }+        err _ => {+            files.free_buffer(body)+            walk.failed = true+            return+        }+    }+    for e in t.entries {+        if walk.failed {+            break+        }+        if !valid_checkout_name(e.name) {+            walk.failed = true+            break+        }+        val path: bytes.Bytes = join_bytes(prefix, e.name)+        if e.kind == tree.KIND_SUBTREE {+            @append(walk.dirs, path)+            walk_tree(walk, e.target, path, depth + 1)+        } elif e.kind == tree.KIND_FILE+            || e.kind == tree.KIND_EXECUTABLE+            || e.kind == tree.KIND_SYMLINK {+            add_task(walk, path, e.kind, e.target)+        } elif e.kind == tree.KIND_SUBMODULE {+            @append(walk.dirs, path)+        } else {+            files.free_buffer(path)+            walk.failed = true+        }+    }+    tree.free_tree(t)+    files.free_buffer(body)+}++fn parse_vein_hex(hex: bytes.Bytes) option[objid.Id] = trust {+    if hex.len != 64 {+        return none+    }+    val raw: ref u8 = @alloc(32) as ref u8+    val i: mut usize = 0+    for i < 32 {+        val hi_c: u8 = bytes.Bytes.at(hex, i * 2)+        val lo_c: u8 = bytes.Bytes.at(hex, i * 2 + 1)+        val hi: mut i32 = -1+        val lo: mut i32 = -1+        if hi_c >= 48 && hi_c <= 57 {+            hi = (hi_c - 48) as i32+        } elif hi_c >= 97 && hi_c <= 102 {+            hi = (hi_c - 87) as i32+        } elif hi_c >= 65 && hi_c <= 70 {+            hi = (hi_c - 55) as i32+        }+        if lo_c >= 48 && lo_c <= 57 {+            lo = (lo_c - 48) as i32+        } elif lo_c >= 97 && lo_c <= 102 {+            lo = (lo_c - 87) as i32+        } elif lo_c >= 65 && lo_c <= 70 {+            lo = (lo_c - 55) as i32+        }+        if hi < 0 || lo < 0 {+            @free(raw as ref void)+            return none+        }+        @store8(@ptradd(raw, i as i64), ((hi * 16 + lo) as u8))+        i+++    }+    return some objid.id(raw)+}++fn bookmark_target(v: ref view.View, name: bytes.Bytes) option[objid.Id] = trust {+    for bm in v.bookmarks {+        if bytes.Bytes.eql(bm.name, name) {+            if @len(bm.targets.adds) == 1 {+                val a = @get(bm.targets.adds, 0)+                if a is some id {+                    return some id+                }+            }+            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 working_copy_target(v: ref view.View) option[objid.Id] = trust {+    for w in v.working_copies {+        if bytes.Bytes.eql(w.workspace, bytes.bytes(c"default", 7)) {+            return some w.target+        }+    }+    return none+}++fn resolve_revision(v: ref view.View, rev: bytes.Bytes) option[objid.Id] = trust {+    if rev.len == 0 || bytes.Bytes.eql(rev, bytes.bytes(c"@", 1)) {+        return working_copy_target(v)+    }+    val bm = bookmark_target(v, rev)+    if bm is some id {+        return some id+    }+    val tg = tag_target(v, rev)+    if tg is some id2 {+        return some id2+    }+    return parse_vein_hex(rev)+}++/// Check out `rev` (empty means the working-copy commit) into the repository.+pub fn run(repo: layout.Repo, rev: bytes.Bytes) i32 = trust {+    val store_handle: mut store.Store = store.open_all(repo)+    val mut_view = state.current_view(repo, store_handle.handles)+    val v: mut ref view.View = none+    match mut_view {+        some x => {+            v = x+        }+        none => {+            stdio.eprint("vn: no operation state; import a repository first\n", {})+            store.close(store_handle)+            return 1+        }+    }+    val target_opt = resolve_revision(v, rev)+    val commit_id: mut objid.Id = objid.id_none()+    match target_opt {+        some id => {+            commit_id = id+        }+        none => {+            stdio.eprint("vn: unknown revision: {s}\n", {str.view(rev.ptr, rev.len as i64)})+            view.free_view(v)+            store.close(store_handle)+            return 1+        }+    }+    val cbody_opt = state.read_body(store_handle.handles, commit_id, types.COMMIT)+    val cbody: mut bytes.Bytes = bytes.empty()+    match cbody_opt {+        some b => {+            cbody = b+        }+        none => {+            stdio.eprint("vn: cannot read commit\n", {})+            view.free_view(v)+            store.close(store_handle)+            return 1+        }+    }+    val cdecoded = commit.decode(cbody)+    val c: mut ref commit.Commit = none+    match cdecoded {+        ok x => {+            c = x+        }+        err _ => {+            files.free_buffer(cbody)+            stdio.eprint("vn: corrupt commit\n", {})+            view.free_view(v)+            store.close(store_handle)+            return 1+        }+    }+    val root_tree: objid.Id = copy_id(c.root_tree)+    commit.free_commit(c)+    files.free_buffer(cbody)+    view.free_view(v)++    val root: str.StringView = layout.root_view(repo)+    val root_c: ref u8 = bytes.Bytes.to_cstr(bytes.from_cstr(root.ptr))+    val root_fd: i32 = openat(-100, root_c, o_directory() | o_cloexec(), 0)+    @free(root_c as ref void)+    if root_fd < 0 {+        stdio.eprint("vn: cannot open working directory\n", {})+        store.close(store_handle)+        return 1+    }++    val tasks: list[ref CheckoutTask] = lists.new[ref CheckoutTask]()+    val dirs: list[bytes.Bytes] = lists.new[bytes.Bytes]()+    val walk: mut CheckoutWalk = CheckoutWalk{+        handles: store_handle.handles,+        tasks: tasks,+        dirs: dirs,+        failed: false,+        error: bytes.empty()+    }+    walk_tree(walk, root_tree, bytes.empty(), 0)+    if walk.failed {+        stdio.eprint("vn: checkout tree validation failed\n", {})+        close(root_fd)+        store.close(store_handle)+        return 1+    }++    val dir_failed: mut bool = false+    for d in dirs {+        if !ensure_dir(root_fd, d) {+            dir_failed = true+            stdio.eprint("vn: cannot create directory: {s}\n", {str.view(d.ptr, d.len as i64)})+            break+        }+    }+    if dir_failed {+        close(root_fd)+        store.close(store_handle)+        return 1+    }++    val ac: allocators.HeapAllocator = @zeroed+    val count: usize = cpu_count()+    val n: usize = @len(tasks)+    val workers: mut usize = count+    if workers < 1 {+        workers = 1+    }+    if workers > n && n > 0 {+        workers = n+    }+    val thread_refs: mut list[ref void] = lists.new[ref void]()+    val jobs: mut list[ref CheckoutJob] = lists.new[ref CheckoutJob]()+    if n == 0 {+        workers = 0+    }+    val w: mut usize = 0+    for w < workers {+        val job: mut ref CheckoutJob = @alloc(@sizeof(CheckoutJob)) as ref CheckoutJob+        job.handles = store_handle.handles+        job.root_fd = root_fd+        job.tasks = tasks+        job.start = w+        job.step = workers+        job.failed = false+        job.error = bytes.empty()+        @append(jobs, job)+        val tr = thread.Thread.new[allocators.HeapAllocator](ac, checkout_worker, job as ref void)+        match tr {+            ok t => {+                @append(thread_refs, t)+            }+            err _ => {+                job.failed = true+                job.error = bytes.Bytes.dup(bytes.from_cstr(c"cannot start checkout thread"))+            }+        }+        w+++    }++    val failed_path: mut bytes.Bytes = bytes.empty()+    val had_failure: mut bool = false+    val j: mut usize = 0+    for j < @len(jobs) {+        val job = @get(jobs, j)+        if job is some jb {+            val tr = @get(thread_refs, j)+            if tr is some t {+                val joined = thread.Thread.join[allocators.HeapAllocator](ac, t)+                match joined {+                    ok _ => {+                    }+                    err _ => {+                    }+                }+            }+            if jb.failed {+                had_failure = true+                if failed_path.len == 0 && jb.error.len > 0 {+                    failed_path = jb.error+                }+            }+        }+        j+++    }++    close(root_fd)+    if had_failure {+        if failed_path.len > 0 {+            stdio.eprint("vn: checkout failed at: {s}\n", {str.view(failed_path.ptr, failed_path.len as i64)})+        } else {+            stdio.eprint("vn: checkout failed\n", {})+        }+        store.close(store_handle)+        return 1+    }++    stdio.eprint("vn: checked out {d} files\n", {n})+    store.close(store_handle)+    return 0+}