╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const evt = @import("event.zig"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const hash = xit.hash; 6 const obj = xit.object; 7 const rf = xit.ref; 8 const mrg = xit.merge; 9 const find = @import("find.zig"); 10 const cms = @import("search_commit.zig"); 11 const fork = @import("fork.zig"); 12 const serve_common = @import("serve_common.zig"); 13 14 // the action a patch merge records 15 pub const merge_undo_action = "haxy/merge"; 16 17 // capture an existing branch without creating a fork 18 pub fn writeBranchPatch( 19 host_kind: evt.HostKind, 20 comptime repo_kind: rp.RepoKind, 21 comptime repo_opts: rp.RepoOpts(repo_kind), 22 io: std.Io, 23 allocator: std.mem.Allocator, 24 repo: *rp.Repo(repo_kind, repo_opts), 25 id: [evt.event_id_size * 2]u8, 26 patch: evt.Patch, 27 expected_patch: ?evt.Patch, 28 author: evt.CommitAuthor, 29 ) !void { 30 var arena = std.heap.ArenaAllocator.init(allocator); 31 defer arena.deinit(); 32 33 // write git events through the local event database 34 if (repo_kind == .git) { 35 // reject edits based on an outdated patch 36 if (expected_patch) |expected| { 37 const current = (try evt.readFromRepo(evt.Patch, repo_kind, repo_opts, io, allocator, &arena, repo, &try evt.parseEventId(&id))) orelse return error.PatchOutOfDate; 38 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 39 } 40 41 // capture the branch revision and consume its events 42 const events = try branchEvents(repo_kind, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, &arena, id, patch, author); 43 try evt.consume(host_kind, .repo, repo_kind, repo_opts, io, allocator, repo, evt.events_ref, &events); 44 } else { 45 const DB = evt.EventDB(repo_opts.hash); 46 47 // continue from a remote event history when the local ref is absent 48 var first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8 = null; 49 if (try repo.readRef(io, evt.events_ref) == null) { 50 var remotes = try repo.listRemotes(io, allocator); 51 defer remotes.deinit(); 52 for (remotes.sections.keys()) |name| { 53 if (try repo.readRef(io, .{ .kind = .{ .remote = name }, .name = evt.events_ref.name })) |oid| { 54 first_parent = .{oid}; 55 break; 56 } 57 } 58 } 59 60 // commit the patch, mergeability, and undo record together 61 { 62 const Ctx = struct { 63 repo: *rp.Repo(repo_kind, repo_opts), 64 io: std.Io, 65 arena: *std.heap.ArenaAllocator, 66 id: [evt.event_id_size * 2]u8, 67 patch: evt.Patch, 68 expected_patch: ?evt.Patch, 69 author: evt.CommitAuthor, 70 checks: *MergeCheckInputs(repo_opts), 71 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 72 73 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 74 var moment = try DB.HashMap(.read_write).init(cursor.*); 75 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 76 77 // recheck the expected patch under the repository lock 78 if (ctx.expected_patch) |expected| { 79 const events_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 80 const current = (try evt.Patch.readById(DB, repo_opts.hash, events_moment, ctx.arena, &try evt.parseEventId(&ctx.id))) orelse return error.PatchOutOfDate; 81 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 82 } 83 84 // capture and consume the branch revision 85 const events = try branchEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena, ctx.id, ctx.patch, ctx.author); 86 { 87 const parent = if (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), ctx.io, .{ .ref = evt.events_ref }) == null) ctx.first_parent else null; 88 try evt.commitEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena.child_allocator, evt.events_ref, &events, parent); 89 if (!try evt.consumeInTransaction(.repo, repo_kind, repo_opts, state, &ctx.repo.core.db, &moment, ctx.io, ctx.arena.child_allocator, evt.events_ref)) return error.CancelTransaction; 90 } 91 92 // save mergeability before finishing the patch transaction 93 _ = try ctx.checks.update(state, ctx.io, ctx.arena.child_allocator); 94 95 // record the user action for undo 96 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = evt.undo_action } }); 97 } 98 }; 99 100 // a branch patch has no fork, so this only names the patch to check 101 var checks: MergeCheckInputs(repo_opts) = .{}; 102 defer checks.deinit(io, allocator); 103 if (host_kind == .server) try checks.add(io, allocator, repo, try evt.parseEventId(&id), patch); 104 105 try repo.core.db_file.lock(io, .exclusive); 106 defer repo.core.db_file.unlock(io); 107 108 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 109 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ .repo = repo, .io = io, .arena = &arena, .id = id, .patch = patch, .expected_patch = expected_patch, .author = author, .checks = &checks, .first_parent = first_parent }); 110 } 111 } 112 } 113 114 fn branchEvents( 115 comptime repo_kind: rp.RepoKind, 116 comptime repo_opts: rp.RepoOpts(repo_kind), 117 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 118 io: std.Io, 119 arena: *std.heap.ArenaAllocator, 120 id: [evt.event_id_size * 2]u8, 121 patch: evt.Patch, 122 author: evt.CommitAuthor, 123 ) ![2]evt.EventWithId { 124 // validate the patch fields and branch names 125 const branch = patch.source_branch orelse return error.InvalidSourceBranch; 126 if (!evt.Patch.fieldsValid(patch.title, patch.tags)) return error.InvalidFields; 127 if (!evt.Patch.branchValid(branch)) return error.InvalidSourceBranch; 128 if (!evt.Patch.branchValid(patch.target_branch)) return error.InvalidTargetBranch; 129 130 // resolve both tips and their common ancestor 131 const source = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return error.InvalidSourceBranch; 132 const target = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } })) orelse return error.InvalidTargetBranch; 133 if (std.mem.eql(u8, branch, patch.target_branch)) return error.SameBranch; 134 const base = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, arena.allocator(), &target, &source) catch |err| switch (err) { 135 error.NoCommonAncestor => return error.UnrelatedBranches, 136 else => return err, 137 }; 138 139 // prepare the revision and attach it to the patch event 140 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 141 const prepared = try evt.PatchRev.prepare(repo_kind, repo_opts, state, io, arena, &base, &source, patch.title, author, timestamp); 142 var updated = patch; 143 updated.revision = prepared.revision; 144 return .{ 145 prepared.event, 146 .{ .id = id, .author = author, .timestamp = timestamp, .event = .{ .patch = updated } }, 147 }; 148 } 149 150 // refresh open patches' tracked branches and, on the server, their mergeability. 151 // this runs outside the caller's transaction. 152 pub fn refreshBranches( 153 host_kind: evt.HostKind, 154 comptime repo_kind: rp.RepoKind, 155 comptime repo_opts: rp.RepoOpts(repo_kind), 156 io: std.Io, 157 allocator: std.mem.Allocator, 158 repo: *rp.Repo(repo_kind, repo_opts), 159 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 160 progress_ctx_maybe: ?repo_opts.ProgressCtx, 161 ) !void { 162 const DB = evt.EventDB(repo_opts.hash); 163 var arena = std.heap.ArenaAllocator.init(allocator); 164 defer arena.deinit(); 165 var patches: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?evt.Patch.Record) = .empty; 166 defer patches.deinit(allocator); 167 168 // collect patches whose source or mergeability may have changed 169 collect: { 170 var local_db: ?evt.LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try evt.LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 171 defer if (local_db) |*db| db.deinit(io, allocator); 172 const moment = (if (local_db) |*db| evt.currentMomentFromDb(repo_opts.hash, db.db) else if (repo_kind == .git) break :collect else evt.currentMoment(repo_opts, repo)) catch |err| switch (err) { 173 error.NotFound => break :collect, 174 else => return err, 175 }; 176 177 // include all open server patches for mergeability checks 178 if (repo_kind == .xit and host_kind == .server) open: { 179 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse break :open; 180 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 181 const open_cursor = try statuses.getCursor("open") orelse break :open; 182 const open_patches = try DB.SortedSet(.read_only).init(open_cursor); 183 var iter = try open_patches.iteratorFromIndex(0); 184 while (try iter.next()) |cursor| try patches.put(allocator, try evt.readOrderKeyId(DB, cursor), null); 185 } 186 187 // find tracked source branches and skip conflicting patches 188 const source_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.source_to_id_set_key)) orelse break :collect; 189 const sources = try DB.SortedMap(.read_only).init(source_cursor); 190 const conflicts = if (try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| try DB.SortedMap(.read_only).init(cursor) else null; 191 var iter = try sources.iterator(); 192 while (try iter.next()) |cursor| { 193 const pair = try cursor.readKeyValuePair(); 194 const branch = try pair.key_cursor.readBytesAlloc(arena.allocator(), null); 195 196 // limit source refreshes to branches changed by this push 197 if (updates) |changed| { 198 var found = false; 199 for (changed) |update| { 200 if (std.mem.startsWith(u8, update.ref_name, "refs/heads/") and std.mem.eql(u8, update.ref_name["refs/heads/".len..], branch)) { 201 found = true; 202 break; 203 } 204 } 205 if (!found) continue; 206 } 207 208 // read the source tip before comparing stored revisions 209 const source = (try repo.readRef(io, .{ .kind = .head, .name = branch })) orelse { 210 if (host_kind == .server) std.log.warn("patch source branch missing: {s}", .{branch}); 211 continue; 212 }; 213 214 // collect open patches whose stored source tip is outdated 215 const ids = try DB.CountedHashSet(.read_only).init(pair.value_cursor); 216 var ids_iter = try ids.iterator(); 217 while (try ids_iter.next()) |id_cursor| { 218 const id_pair = try id_cursor.readKeyValuePair(); 219 var id: [evt.event_id_size]u8 = undefined; 220 if ((try id_pair.key_cursor.readBytes(&id)).len != id.len) return error.InvalidPatch; 221 const record = (try evt.Patch.readById(DB, repo_opts.hash, moment, &arena, &id)) orelse continue; 222 if (record.removed or record.event.status.kind() != .open) continue; 223 if (conflicts) |map| if (try map.getCursor(&evt.orderKeyDesc(record.created_order, &id)) != null) continue; 224 if (record.event.revision) |revision| if (std.mem.eql(u8, revision.source_oid, &source)) continue; 225 try patches.put(allocator, id, record); 226 } 227 } 228 } 229 230 // start progress reporting after the patch count is known 231 if (repo_opts.ProgressCtx != void) { 232 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .start = .{ .kind = .writing_patch, .estimated_total_items = patches.count() } }) catch {}; 233 } 234 235 // refresh each patch and report its completion 236 for (patches.keys(), patches.values()) |id, record_maybe| { 237 if (record_maybe) |record| { 238 const author = evt.CommitAuthor{ .name = "haxy", .email = record.author_email orelse "user@haxy" }; 239 writeBranchPatch(host_kind, repo_kind, repo_opts, io, allocator, repo, std.fmt.bytesToHex(id, .lower), record.event, record.event, author) catch |err| { 240 if (host_kind == .server) std.log.warn("failed to refresh branch patch: {s}", .{@errorName(err)}); 241 }; 242 } 243 if (repo_kind == .xit and host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, id); 244 if (repo_opts.ProgressCtx != void) { 245 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .complete_one = .writing_patch }) catch {}; 246 } 247 } 248 249 // finish progress reporting after all patches have been visited 250 if (repo_opts.ProgressCtx != void) { 251 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .end = .writing_patch }) catch {}; 252 } 253 } 254 255 pub const PublishInput = struct { 256 id: [evt.event_id_size * 2]u8, 257 user_id: [evt.event_id_size]u8, 258 repo_id: [evt.event_id_size]u8, 259 author: evt.CommitAuthor, 260 timestamp: u64, 261 }; 262 263 pub const EditDraftInput = struct { 264 id: [evt.event_id_size * 2]u8, 265 user_id: [evt.event_id_size]u8, 266 repo_id: [evt.event_id_size]u8, 267 title: []const u8, 268 tags: []const u8, 269 description: []const u8, 270 target_branch: []const u8, 271 author: evt.CommitAuthor, 272 timestamp: u64, 273 }; 274 275 pub const Mergeability = struct { 276 pub const Status = enum { clean, conflict, unknown }; 277 278 source: Status = .unknown, 279 squash: Status = .unknown, 280 281 pub fn get(self: Mergeability, revision: evt.Patch.MergeRevision) Status { 282 return switch (revision) { 283 .source => self.source, 284 .squash => self.squash, 285 }; 286 } 287 288 pub fn status(self: Mergeability) Status { 289 if (self.source == .clean or self.squash == .clean) return .clean; 290 if (self.source == .conflict and self.squash == .conflict) return .conflict; 291 return .unknown; 292 } 293 }; 294 295 const MergeCheck = struct { 296 revision: evt.Patch.Revision, 297 target_branch: []const u8, 298 target_oid: []const u8, 299 result: Mergeability = .{}, 300 301 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 302 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 303 std.mem.eql(u8, self.target_branch, patch.target_branch) and 304 std.mem.eql(u8, self.target_oid, target_oid); 305 } 306 }; 307 308 fn readMergeCheck( 309 comptime repo_opts: rp.RepoOpts(.xit), 310 haxy_moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 311 arena: *std.heap.ArenaAllocator, 312 id: *const [evt.event_id_size]u8, 313 ) !?MergeCheck { 314 const DB = evt.EventDB(repo_opts.hash); 315 316 // find the cached check for this patch 317 const map_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)) orelse return null; 318 const map = try DB.HashMap(.read_only).init(map_cursor); 319 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 320 321 // treat unrecognized cached statuses as a cache miss 322 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 323 error.InvalidEnumTag => return null, 324 else => return err, 325 }; 326 } 327 328 // reads never run a merge or refresh the cache 329 pub fn readMergeability( 330 comptime repo_opts: rp.RepoOpts(.xit), 331 state: rp.Repo(.xit, repo_opts).State(.read_only), 332 io: std.Io, 333 arena: *std.heap.ArenaAllocator, 334 id: *const [evt.event_id_size]u8, 335 patch: evt.Patch, 336 ) !Mergeability { 337 // reject checks for an outdated source revision 338 if (patch.source_branch != null and !try branchCurrent(repo_opts, state, io, arena, patch)) return .{}; 339 340 // use the cached result only when the target still matches 341 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 342 const haxy_moment = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*) catch |err| switch (err) { 343 error.NotFound => return .{}, 344 else => return err, 345 }; 346 const cached = try readMergeCheck(repo_opts, haxy_moment, arena, id) orelse return .{}; 347 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 348 } 349 350 // refresh after the caller's transaction and locks have finished. a check 351 // failure must not turn an accepted push or event into a failed operation. 352 pub fn refreshMergeability( 353 comptime repo_opts: rp.RepoOpts(.xit), 354 io: std.Io, 355 allocator: std.mem.Allocator, 356 target_repo: *rp.Repo(.xit, repo_opts), 357 id_maybe: ?[evt.event_id_size]u8, 358 ) void { 359 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 360 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 361 }; 362 } 363 364 fn refreshMergeChecks( 365 comptime repo_opts: rp.RepoOpts(.xit), 366 io: std.Io, 367 allocator: std.mem.Allocator, 368 target_repo: *rp.Repo(.xit, repo_opts), 369 id_maybe: ?[evt.event_id_size]u8, 370 ) !void { 371 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 372 373 // collect open patch ids before any refresh changes the database 374 const DB = evt.EventDB(repo_opts.hash); 375 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 376 error.NotFound => return, 377 else => return err, 378 }; 379 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 380 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 381 const open_cursor = try statuses.getCursor("open") orelse return; 382 const open = try DB.SortedSet(.read_only).init(open_cursor); 383 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 384 defer ids.deinit(allocator); 385 var iter = try open.iteratorFromIndex(0); 386 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 387 388 // refresh each collected patch independently 389 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 390 } 391 392 fn refreshMergeCheck( 393 comptime repo_opts: rp.RepoOpts(.xit), 394 io: std.Io, 395 allocator: std.mem.Allocator, 396 target_repo: *rp.Repo(.xit, repo_opts), 397 id: *const [evt.event_id_size]u8, 398 ) !void { 399 const Repo = rp.Repo(.xit, repo_opts); 400 const DB = Repo.DB; 401 var arena = std.heap.ArenaAllocator.init(allocator); 402 defer arena.deinit(); 403 404 // skip patches that no longer need mergeability checks 405 const initial = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, id)) orelse return; 406 if (initial.removed or initial.event.status.kind() != .open) return; 407 408 // acquire fork locks before the target repository lock 409 var checks: MergeCheckInputs(repo_opts) = .{}; 410 defer checks.deinit(io, allocator); 411 try checks.add(io, allocator, target_repo, id.*, initial.event); 412 413 // cancel the cache transaction when the result is unchanged 414 { 415 const Ctx = struct { 416 core: *Repo.Core, 417 checks: *MergeCheckInputs(repo_opts), 418 io: std.Io, 419 allocator: std.mem.Allocator, 420 421 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 422 var moment = try DB.HashMap(.read_write).init(cursor.*); 423 const state = Repo.State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 424 if (!try ctx.checks.update(state, ctx.io, ctx.allocator)) return error.CancelTransaction; 425 } 426 }; 427 428 try target_repo.core.db_file.lock(io, .exclusive); 429 defer target_repo.core.db_file.unlock(io); 430 431 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 432 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 433 .core = &target_repo.core, 434 .checks = &checks, 435 .io = io, 436 .allocator = allocator, 437 }) catch |err| switch (err) { 438 error.CancelTransaction => {}, 439 else => return err, 440 }; 441 } 442 } 443 444 // prepare fork handles before taking the target lock. this preserves the 445 // fork-before-target lock order used by publishing and merge operations. 446 pub fn MergeCheckInputs(comptime repo_opts: rp.RepoOpts(.xit)) type { 447 const Repo = rp.Repo(.xit, repo_opts); 448 return struct { 449 forks: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?Repo) = .empty, 450 const Self = @This(); 451 452 pub fn prepare(self: *Self, io: std.Io, allocator: std.mem.Allocator, repo: *Repo, events: []const evt.EventWithId) !void { 453 for (events) |event| { 454 if (event.event != .patch) continue; 455 const patch = event.event.patch orelse continue; 456 try self.add(io, allocator, repo, try evt.parseEventId(&event.id), patch); 457 } 458 } 459 460 fn add(self: *Self, io: std.Io, allocator: std.mem.Allocator, repo: *Repo, id: [evt.event_id_size]u8, patch: evt.Patch) !void { 461 // track each open patch once, including branch-backed patches 462 if (patch.status.kind() != .open) return; 463 const entry = try self.forks.getOrPut(allocator, id); 464 if (entry.found_existing) return; 465 entry.value_ptr.* = null; 466 if (patch.source_branch != null) return; 467 468 // open the fork before acquiring its shared lock 469 const path = try fork.forkPath(allocator, std.fs.path.dirname(repo.core.work_path) orelse ".", &std.fmt.bytesToHex(id, .lower)); 470 defer allocator.free(path); 471 var opened = Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| { 472 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 473 return; 474 }; 475 476 // transfer the locked fork to the collection for cleanup 477 errdefer opened.deinit(io, allocator); 478 try opened.core.db_file.lock(io, .shared); 479 entry.value_ptr.* = opened; 480 } 481 482 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 483 for (self.forks.values()) |*value| if (value.*) |*repo| { 484 repo.core.db_file.unlock(io); 485 repo.deinit(io, allocator); 486 }; 487 self.forks.deinit(allocator); 488 } 489 490 // optional checks may fail without rejecting a patch, but a failed 491 // restoration must abort the transaction so trial writes cannot be 492 // committed. reports whether any cached result changed. 493 pub fn update(self: *Self, state: Repo.State(.read_write), io: std.Io, allocator: std.mem.Allocator) !bool { 494 var arena = std.heap.ArenaAllocator.init(allocator); 495 defer arena.deinit(); 496 var changed = false; 497 for (self.forks.keys(), self.forks.values()) |id, *repo| { 498 const saved = updateMergeCheck(repo_opts, state, io, &arena, &id, if (repo.*) |*value| value else null) catch |err| switch (err) { 499 error.MergeCheckRestoreFailed => return err, 500 else => { 501 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 502 continue; 503 }, 504 }; 505 if (saved) changed = true; 506 } 507 return changed; 508 } 509 }; 510 } 511 512 // the caller holds the target's exclusive lock, and any fork's shared lock. 513 // this only saves the cache; it never creates a top-level history transaction. 514 fn updateMergeCheck( 515 comptime repo_opts: rp.RepoOpts(.xit), 516 state: rp.Repo(.xit, repo_opts).State(.read_write), 517 io: std.Io, 518 arena: *std.heap.ArenaAllocator, 519 id: *const [evt.event_id_size]u8, 520 fork_repo: ?*rp.Repo(.xit, repo_opts), 521 ) !bool { 522 const DB = rp.Repo(.xit, repo_opts).DB; 523 524 // read the patch from the current transaction 525 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.readOnly()) catch |err| switch (err) { 526 error.NotFound => return false, 527 else => return err, 528 }; 529 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, arena, id)) orelse return false; 530 if (patch_record.removed or patch_record.event.status.kind() != .open) return false; 531 532 // find the newest fork revision when the patch uses a fork 533 var newest: ?evt.PatchRev.WithId = null; 534 if (fork_repo) |repo| { 535 if (evt.currentMoment(repo_opts, repo)) |events| { 536 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, arena) catch |err| blk: { 537 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 538 break :blk null; 539 }; 540 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 541 } 542 543 // compare the selected revision and target against the cache 544 const patch = patch_record.event; 545 const revision = patch.revision orelse return false; 546 const target_oid = try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 547 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 548 const cached = try readMergeCheck(repo_opts, target_events, arena, id); 549 const current = if (patch.source_branch != null) 550 try branchCurrent(repo_opts, state.readOnly(), io, arena, patch) 551 else if (newest) |latest| 552 std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) 553 else 554 false; 555 556 // run trial merges only for a current revision with an unresolved check 557 if (current and target_oid != null) { 558 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return false; 559 check.result = try trialMergeCheck(repo_opts, state, io, arena.child_allocator, &check, fork_repo); 560 } 561 562 // persist the result only when it differs from the cache 563 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return false; 564 try saveMergeCheck(repo_opts, state.extra.moment.*, id, check); 565 return true; 566 } 567 568 fn trialMergeCheck( 569 comptime repo_opts: rp.RepoOpts(.xit), 570 state: rp.Repo(.xit, repo_opts).State(.read_write), 571 io: std.Io, 572 allocator: std.mem.Allocator, 573 check: *const MergeCheck, 574 fork_repo: ?*rp.Repo(.xit, repo_opts), 575 ) !Mergeability { 576 // freeze the parent state so trial writes copy its nodes 577 const moment = state.extra.moment; 578 const snapshot = moment.slot(); 579 // TODO: use an xitdb savepoint to also reclaim trial bytes on rollback. 580 // restoring the root leaves the appended data unused until gc. 581 try state.core.db.freeze(); 582 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 583 584 // keep the trial result in memory while discarding its state changes 585 const result = calculateMergeCheck(repo_opts, state, io, allocator, check, fork_repo); 586 587 // restore the parent state before handling any trial error 588 moment.cursor.write(.{ .slot = snapshot }) catch return error.MergeCheckRestoreFailed; 589 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 590 591 // report failed trials as unknown after the parent state is restored 592 return result catch |err| { 593 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 594 return .{}; 595 }; 596 } 597 598 fn calculateMergeCheck( 599 comptime repo_opts: rp.RepoOpts(.xit), 600 state: rp.Repo(.xit, repo_opts).State(.read_write), 601 io: std.Io, 602 allocator: std.mem.Allocator, 603 check: *const MergeCheck, 604 fork_repo: ?*rp.Repo(.xit, repo_opts), 605 ) !Mergeability { 606 const source = try oidArray(repo_opts.hash, check.revision.source_oid); 607 const squash = try oidArray(repo_opts.hash, check.revision.squash_oid); 608 609 // import fork objects into the temporary trial state 610 if (fork_repo) |repo| { 611 var fork_moment = try repo.core.latestMoment(); 612 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 613 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 614 defer objects.deinit(); 615 try objects.include(&source); 616 try objects.include(&squash); 617 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 618 } 619 620 // check source and squash merges against the same target 621 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 622 return .{ 623 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 624 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 625 }; 626 } 627 628 fn saveMergeCheck(comptime repo_opts: rp.RepoOpts(.xit), moment: rp.Repo(.xit, repo_opts).DB.HashMap(.read_write), id: *const [evt.event_id_size]u8, check: MergeCheck) !void { 629 const DB = rp.Repo(.xit, repo_opts).DB; 630 631 // store the check under the current event history moment 632 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 633 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 634 _ = try last_object_id_cursor.readBytes(&last_object_id); 635 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 636 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 637 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 638 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 639 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 640 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 641 } 642 643 fn branchCurrent(comptime repo_opts: rp.RepoOpts(.xit), state: rp.Repo(.xit, repo_opts).State(.read_only), io: std.Io, arena: *std.heap.ArenaAllocator, patch: evt.Patch) !bool { 644 // check that the source branch still points to the selected commit 645 const branch = patch.source_branch orelse return false; 646 const selected = patch.revision orelse return false; 647 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 648 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 649 650 // verify that the stored revision metadata also matches 651 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 652 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 653 return selected.matches(revision); 654 } 655 656 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 657 try evt.PatchRev.validateOid(hash_kind, oid); 658 var result: [hash.hexLen(hash_kind)]u8 = undefined; 659 @memcpy(&result, oid); 660 return result; 661 } 662 663 fn checkCommit( 664 comptime repo_opts: rp.RepoOpts(.xit), 665 state: rp.Repo(.xit, repo_opts).State(.read_write), 666 io: std.Io, 667 allocator: std.mem.Allocator, 668 oid: *const [hash.hexLen(repo_opts.hash)]u8, 669 target: rf.Ref, 670 ) Mergeability.Status { 671 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 672 .kind = .full, 673 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 674 .dry_run = true, 675 }, target, null) catch |err| { 676 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 677 return .unknown; 678 }; 679 defer result.deinit(); 680 681 // translate the dry-run outcome into a cached status 682 return switch (result.result) { 683 .conflict => .conflict, 684 .clean, .success, .nothing, .fast_forward => .clean, 685 }; 686 } 687 688 pub const MergeInput = struct { 689 id: [evt.event_id_size * 2]u8, 690 revision: evt.Patch.MergeRevision, 691 author: evt.CommitAuthor, 692 timestamp: u64, 693 }; 694 695 pub fn publish( 696 comptime repo_opts: rp.RepoOpts(.xit), 697 io: std.Io, 698 allocator: std.mem.Allocator, 699 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 700 target_repo: *rp.Repo(.xit, repo_opts), 701 fork_path: []const u8, 702 input: PublishInput, 703 ) !void { 704 const patch_id = try evt.parseEventId(&input.id); 705 var arena = std.heap.ArenaAllocator.init(allocator); 706 defer arena.deinit(); 707 708 // validate the fork ownership and publishing identity 709 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 710 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 711 if (fork_record.removed or 712 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 713 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 714 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 715 if (user.removed or 716 !std.mem.eql(u8, user.event.name, input.author.name) or 717 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 718 719 // read the patch staged in the fork 720 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 721 defer fork_repo.deinit(io, allocator); 722 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 723 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 724 725 // check whether this patch has already been published 726 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 727 error.NotFound => null, 728 else => |other| return other, 729 }; 730 const existing = if (target_moment) |moment| 731 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 732 else 733 null; 734 if (existing) |record| { 735 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 736 } 737 738 // publish the selected revision unless the draft was already consumed 739 if (local_patch.removed) { 740 if (existing == null) return error.PatchDataUnavailable; 741 } else { 742 var patch = (existing orelse local_patch).event; 743 if (local_patch.event.revision) |selected| { 744 const revision_id = try evt.parseEventId(&selected.id); 745 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 746 if (!selected.matches(revision)) return error.PatchNotPushed; 747 patch.revision = selected; 748 } 749 if (existing == null) patch.status = .open; 750 751 // write the published patch to the target repository 752 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 753 .id = input.id, 754 .timestamp = input.timestamp, 755 .author = input.author, 756 .event = .{ .patch = patch }, 757 }}); 758 759 // remove the consumed draft from the fork 760 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 761 .id = input.id, 762 .timestamp = input.timestamp, 763 .author = input.author, 764 .event = .{ .patch = null }, 765 }}); 766 } 767 768 // mark the fork as published in the administration repository 769 if (fork_record.event.stage == .draft) { 770 var published = fork_record.event; 771 published.stage = .publish; 772 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 773 .id = input.id, 774 .timestamp = input.timestamp, 775 .author = input.author, 776 .event = .{ .fork = published }, 777 }}); 778 } 779 } 780 781 pub fn editDraft( 782 comptime repo_opts: rp.RepoOpts(.xit), 783 io: std.Io, 784 allocator: std.mem.Allocator, 785 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 786 fork_path: []const u8, 787 input: EditDraftInput, 788 ) !bool { 789 // validate the submitted fields before opening repositories 790 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 791 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 792 const patch_id = try evt.parseEventId(&input.id); 793 var arena = std.heap.ArenaAllocator.init(allocator); 794 defer arena.deinit(); 795 796 // validate the draft ownership and editing identity 797 { 798 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 799 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 800 if (fork_record.event.stage != .draft) return false; 801 if (fork_record.removed or 802 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 803 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 804 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 805 if (user.removed or 806 !std.mem.eql(u8, user.event.name, input.author.name) or 807 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 808 } 809 810 // read the draft patch from its fork 811 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 812 defer fork_repo.deinit(io, allocator); 813 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 814 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 815 if (record.removed) return error.PatchDataUnavailable; 816 817 // apply the edits and invalidate a revision targeting another branch 818 var patch = record.event; 819 patch.title = input.title; 820 patch.tags = input.tags; 821 patch.description = input.description; 822 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 823 patch.target_branch = input.target_branch; 824 825 // commit the updated draft metadata 826 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 827 .id = input.id, 828 .timestamp = input.timestamp, 829 .author = input.author, 830 .event = .{ .patch = patch }, 831 }}); 832 return true; 833 } 834 835 // merge the selected patch revision into its target branch 836 pub fn merge( 837 comptime repo_opts: rp.RepoOpts(.xit), 838 io: std.Io, 839 allocator: std.mem.Allocator, 840 repo_root_path: []const u8, 841 target_repo: *rp.Repo(.xit, repo_opts), 842 input: MergeInput, 843 ) !void { 844 const patch_id = try evt.parseEventId(&input.id); 845 errdefer |err| { 846 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 847 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 848 } 849 } 850 var arena = std.heap.ArenaAllocator.init(allocator); 851 defer arena.deinit(); 852 853 // validate the target patch 854 const target_moment = try evt.currentMoment(repo_opts, target_repo); 855 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 856 if (patch_record.removed) return error.InvalidPatch; 857 switch (patch_record.event.status) { 858 .open => {}, 859 .closed => return error.PatchClosed, 860 .merged => return error.PatchAlreadyMerged, 861 } 862 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 863 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 864 865 // open the fork 866 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 867 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (patch_record.event.source_branch != null) null else rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 868 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 869 870 // select the commit and merge identity 871 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 872 .squash => selected.squash_oid, 873 .source => selected.source_oid, 874 }) catch return error.InvalidPatch; 875 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 876 877 // merge the code and events in one target transaction 878 { 879 const DB = rp.Repo(.xit, repo_opts).DB; 880 const State = rp.Repo(.xit, repo_opts).State; 881 const Ctx = struct { 882 core: *rp.Repo(.xit, repo_opts).Core, 883 fork_repo: ?*rp.Repo(.xit, repo_opts), 884 io: std.Io, 885 allocator: std.mem.Allocator, 886 patch_id: [evt.event_id_size]u8, 887 expected_patch: evt.Patch, 888 target_ref: rf.Ref, 889 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 890 revision: evt.Patch.MergeRevision, 891 identity: []const u8, 892 author: evt.CommitAuthor, 893 timestamp: u64, 894 895 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 896 var moment = try DB.HashMap(.read_write).init(cursor.*); 897 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 898 899 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 900 defer check_arena.deinit(); 901 902 // require the fork's newest revision while both repos are locked 903 const selected_revision = ctx.expected_patch.revision orelse unreachable; 904 const revision_id = try evt.parseEventId(&selected_revision.id); 905 if (ctx.fork_repo) |repo| { 906 const fork_moment = try evt.currentMoment(repo_opts, repo); 907 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 908 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 909 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 910 911 // require a clean cached result for the selected merge style. 912 { 913 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 914 switch (availability.get(ctx.revision)) { 915 .clean => {}, 916 .conflict => return error.MergeConflict, 917 .unknown => return error.MergeCheckUnavailable, 918 } 919 } 920 921 // copy the selected commit and its dependencies 922 if (ctx.fork_repo) |repo| { 923 var fork_repo_moment = try repo.core.latestMoment(); 924 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 925 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 926 defer objects.deinit(); 927 try objects.include(&ctx.selected_oid); 928 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 929 } 930 931 // merge the selected commit 932 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 933 { 934 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 935 .kind = .full, 936 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 937 .commit_metadata = .{ 938 .author = ctx.identity, 939 .committer = ctx.identity, 940 .message = ctx.expected_patch.title, 941 .timestamp = ctx.timestamp, 942 }, 943 }, ctx.target_ref, null); 944 defer merge_result.deinit(); 945 switch (merge_result.result) { 946 .conflict => return error.MergeConflict, 947 .success, .fast_forward, .nothing => {}, 948 .clean => unreachable, 949 } 950 } 951 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 952 953 // retain the submitted revision and snapshot the merge result 954 if (!try importMergedRevision(repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.fork_repo, &ctx.patch_id, .{ .revision = ctx.revision, .before_oid = &before_oid, .after_oid = &after_oid }, ctx.expected_patch, ctx.author, ctx.timestamp)) return error.PatchOutOfDate; 955 956 // record the merge as one undoable action. 957 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = merge_undo_action } }); 958 } 959 }; 960 961 // lock the fork before the target for the full merge transaction. 962 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 963 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 964 try target_repo.core.db_file.lock(io, .exclusive); 965 defer target_repo.core.db_file.unlock(io); 966 967 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 968 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 969 .core = &target_repo.core, 970 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 971 .io = io, 972 .allocator = allocator, 973 .patch_id = patch_id, 974 .expected_patch = patch_record.event, 975 .target_ref = target_ref, 976 .selected_oid = selected_oid, 977 .revision = input.revision, 978 .identity = identity, 979 .author = input.author, 980 .timestamp = input.timestamp, 981 }); 982 } 983 984 // refresh other patches affected by the updated target branch. 985 refreshMergeability(repo_opts, io, allocator, target_repo, null); 986 987 // the merge moved the target branch, so its indexes follow 988 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 989 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 990 }; 991 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 992 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 993 }; 994 } 995 996 // merge a published patch and remove its fork 997 pub fn mergeAndRemoveFork( 998 comptime repo_opts: rp.RepoOpts(.xit), 999 io: std.Io, 1000 allocator: std.mem.Allocator, 1001 repo_root_path: []const u8, 1002 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1003 target_repo: *rp.Repo(.xit, repo_opts), 1004 input: MergeInput, 1005 ) !void { 1006 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1007 var arena = std.heap.ArenaAllocator.init(allocator); 1008 defer arena.deinit(); 1009 1010 // remove fork data only for patches backed by a fork. 1011 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1012 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1013 } 1014 1015 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1016 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1017 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1018 const name = std.mem.trimEnd(u8, line[0..open], " "); 1019 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1020 return .{ .name = name, .email = line[open + 1 .. close] }; 1021 } 1022 1023 // import a revision after detecting a client-side merge 1024 fn importMerged( 1025 comptime repo_opts: rp.RepoOpts(.xit), 1026 state: rp.Repo(.xit, repo_opts).State(.read_write), 1027 db: *evt.EventDB(repo_opts.hash), 1028 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1029 io: std.Io, 1030 allocator: std.mem.Allocator, 1031 repo_root_path: []const u8, 1032 patch_id: *const [evt.event_id_size]u8, 1033 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1034 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1035 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1036 ) !void { 1037 var arena = std.heap.ArenaAllocator.init(allocator); 1038 defer arena.deinit(); 1039 1040 // identify which selected revision was merged by the client. 1041 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1042 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1043 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1044 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1045 const selected = record.event.revision orelse return; 1046 const revision: evt.Patch.MergeRevision = if (std.mem.eql(u8, matched_oid, selected.source_oid)) .source else if (std.mem.eql(u8, matched_oid, selected.squash_oid)) .squash else return; 1047 1048 // open the fork when the revision is not stored in the target repository. 1049 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (record.event.source_branch != null) null else try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 1050 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1051 1052 // import the revision and record the client-side merge. 1053 _ = try importMergedRevision(repo_opts, state, db, moment, io, allocator, if (fork_repo_maybe) |*repo| repo else null, patch_id, .{ .revision = revision, .before_oid = before_oid, .after_oid = after_oid }, null, null, 0); 1054 } 1055 1056 // import the revision and mark its patch merged in the current transaction 1057 fn importMergedRevision( 1058 comptime repo_opts: rp.RepoOpts(.xit), 1059 state: rp.Repo(.xit, repo_opts).State(.read_write), 1060 db: *evt.EventDB(repo_opts.hash), 1061 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1062 io: std.Io, 1063 allocator: std.mem.Allocator, 1064 fork_repo: ?*rp.Repo(.xit, repo_opts), 1065 patch_id: *const [evt.event_id_size]u8, 1066 merged: struct { 1067 revision: evt.Patch.MergeRevision, 1068 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1069 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1070 }, 1071 expected_patch: ?evt.Patch, 1072 merged_author: ?evt.CommitAuthor, 1073 merged_timestamp: u64, 1074 ) !bool { 1075 const DB = evt.EventDB(repo_opts.hash); 1076 var arena = std.heap.ArenaAllocator.init(allocator); 1077 defer arena.deinit(); 1078 1079 // read the patch and reject outdated or conflicting merge requests. 1080 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1081 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1082 const selected = patch_record.event.revision orelse return false; 1083 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1084 if (expected_patch) |expected| { 1085 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1086 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1087 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1088 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1089 } 1090 } 1091 const revision_id = try evt.parseEventId(&selected.id); 1092 1093 // resolve the selected revision from the target or its fork. 1094 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1095 const revision = (if (fork_repo) |repo| 1096 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1097 else 1098 current_revision) orelse return false; 1099 if (!selected.matches(revision)) return false; 1100 1101 // read the original revision commit and author. 1102 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1103 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = if (fork_repo) |repo| &repo.core else state.core, .extra = .{ .moment = &fork_repo_moment } }; 1104 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1105 if (revision.event_oid.len != event_oid.len) return false; 1106 @memcpy(&event_oid, revision.event_oid); 1107 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1108 defer event_object.deinit(); 1109 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1110 1111 // retain the submitted revision if the target has not imported it yet. 1112 var events_buffer: [3]evt.EventWithId = undefined; 1113 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1114 var tree_entries: [2]evt.EventTreeEntry = undefined; 1115 const needs_import = if (current_revision) |existing| existing.removed else true; 1116 if (needs_import) { 1117 tree_entries = .{ 1118 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1119 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1120 }; 1121 events.appendAssumeCapacity(.{ 1122 .id = selected.id, 1123 .timestamp = event_object.content.commit.metadata.timestamp, 1124 .author = original_author, 1125 .tree_entries = &tree_entries, 1126 .event = .{ .patchrev = revision.event }, 1127 }); 1128 } else { 1129 const existing = current_revision orelse unreachable; 1130 if (!selected.matches(existing)) return error.InvalidPatch; 1131 } 1132 1133 // snapshot the merge result and mark the patch as merged. 1134 { 1135 const author = merged_author orelse original_author; 1136 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1137 var patch = patch_record.event; 1138 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1139 events.appendAssumeCapacity(result.event); 1140 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1141 events.appendAssumeCapacity(.{ 1142 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1143 .timestamp = timestamp, 1144 .author = author, 1145 .event = .{ .patch = patch }, 1146 }); 1147 } 1148 1149 // commit and consume the revision and patch events together. 1150 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1151 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1152 return true; 1153 } 1154 1155 // find patches merged by commits received in a push 1156 pub fn detectMerged( 1157 comptime repo_opts: rp.RepoOpts(.xit), 1158 state: rp.Repo(.xit, repo_opts).State(.read_write), 1159 db: *evt.EventDB(repo_opts.hash), 1160 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1161 io: std.Io, 1162 allocator: std.mem.Allocator, 1163 repo_root_path: []const u8, 1164 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1165 error_writer: *std.Io.Writer, 1166 ) !void { 1167 const DB = evt.EventDB(repo_opts.hash); 1168 var arena = std.heap.ArenaAllocator.init(allocator); 1169 defer arena.deinit(); 1170 1171 // read the revision index used to identify merged patches. 1172 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1173 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1174 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1175 1176 // ignore event refs and inspect only changed branch tips. 1177 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1178 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1179 const heads_prefix = "refs/heads/"; 1180 for (updates) |update| { 1181 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1182 std.mem.eql(u8, update.ref_name, events_ref_path) or 1183 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1184 1185 // validate the ref tips and skip branch deletions. 1186 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1187 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1188 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1189 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1190 @memcpy(&old_oid, update.old_oid); 1191 @memcpy(&new_oid, update.new_oid); 1192 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1193 1194 // traverse commits introduced by this branch update. 1195 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1196 defer commits.deinit(); 1197 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1198 var targets: std.ArrayList(struct { 1199 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1200 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1201 }) = .empty; 1202 1203 // collect merge boundaries along the target's first-parent history. 1204 { 1205 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1206 defer first_parents.deinit(); 1207 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1208 try first_parents.include(&new_oid); 1209 while (try first_parents.next(arena.allocator())) |commit| { 1210 defer commit.deinit(); 1211 try targets.append(arena.allocator(), .{ 1212 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1213 .after_oid = commit.oid, 1214 }); 1215 } 1216 } 1217 1218 // visit target commits oldest first, attributing each revision to the 1219 // commit that introduced it; the shared iterator visits each ancestor once 1220 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1221 while (targets.pop()) |target| { 1222 try commits.include(&target.after_oid); 1223 while (try commits.next(arena.allocator())) |commit| { 1224 defer commit.deinit(); 1225 1226 // find patches whose selected revision matches this commit. 1227 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1228 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1229 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1230 var ids_iter = try ids.iterator(); 1231 while (try ids_iter.next()) |cursor| { 1232 const pair = try cursor.readKeyValuePair(); 1233 var patch_id: [evt.event_id_size]u8 = undefined; 1234 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1235 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1236 1237 // a fast-forward has no recorded merge boundary; use the old ref tip 1238 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1239 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1240 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1241 continue; 1242 }; 1243 } 1244 } 1245 } 1246 } 1247 } 1248