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