╭ 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 if (repo_kind == .git) { 30 if (expected_patch) |expected| { 31 const current = (try evt.readFromRepo(evt.Patch, repo_kind, repo_opts, io, allocator, &arena, repo, &try evt.parseEventId(&id))) orelse return error.PatchOutOfDate; 32 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 33 } 34 const events = try branchEvents(repo_kind, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, &arena, id, patch, author); 35 try evt.consume(host_kind, .repo, repo_kind, repo_opts, io, allocator, repo, evt.events_ref, &events); 36 } else { 37 const DB = evt.EventDB(repo_opts.hash); 38 var first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8 = null; 39 if (try repo.readRef(io, evt.events_ref) == null) { 40 var remotes = try repo.listRemotes(io, allocator); 41 defer remotes.deinit(); 42 for (remotes.sections.keys()) |name| { 43 if (try repo.readRef(io, .{ .kind = .{ .remote = name }, .name = evt.events_ref.name })) |oid| { 44 first_parent = .{oid}; 45 break; 46 } 47 } 48 } 49 const Ctx = struct { 50 repo: *rp.Repo(repo_kind, repo_opts), 51 io: std.Io, 52 arena: *std.heap.ArenaAllocator, 53 id: [evt.event_id_size * 2]u8, 54 patch: evt.Patch, 55 expected_patch: ?evt.Patch, 56 author: evt.CommitAuthor, 57 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 58 59 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 60 var moment = try DB.HashMap(.read_write).init(cursor.*); 61 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 62 if (ctx.expected_patch) |expected| { 63 const events_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 64 const current = (try evt.Patch.readById(DB, repo_opts.hash, events_moment, ctx.arena, &try evt.parseEventId(&ctx.id))) orelse return error.PatchOutOfDate; 65 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 66 } 67 const events = try branchEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena, ctx.id, ctx.patch, ctx.author); 68 const parent = if (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), ctx.io, .{ .ref = evt.events_ref }) == null) ctx.first_parent else null; 69 try evt.commitEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena.child_allocator, evt.events_ref, &events, parent); 70 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; 71 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "update branch patch" }); 72 } 73 }; 74 { 75 try repo.core.db_file.lock(io, .exclusive); 76 defer repo.core.db_file.unlock(io); 77 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 78 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, .first_parent = first_parent }); 79 } 80 if (host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, try evt.parseEventId(&id)); 81 } 82 } 83 84 fn branchEvents( 85 comptime repo_kind: rp.RepoKind, 86 comptime repo_opts: rp.RepoOpts(repo_kind), 87 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 88 io: std.Io, 89 arena: *std.heap.ArenaAllocator, 90 id: [evt.event_id_size * 2]u8, 91 patch: evt.Patch, 92 author: evt.CommitAuthor, 93 ) ![2]evt.EventWithId { 94 const branch = patch.source_branch orelse return error.InvalidSourceBranch; 95 if (!evt.Patch.fieldsValid(patch.title, patch.tags)) return error.InvalidFields; 96 if (!evt.Patch.branchValid(branch)) return error.InvalidSourceBranch; 97 if (!evt.Patch.branchValid(patch.target_branch)) return error.InvalidTargetBranch; 98 const source = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return error.InvalidSourceBranch; 99 const target = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } })) orelse return error.InvalidTargetBranch; 100 if (std.mem.eql(u8, branch, patch.target_branch)) return error.SameBranch; 101 const base = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, arena.allocator(), &target, &source) catch |err| switch (err) { 102 error.NoCommonAncestor => return error.UnrelatedBranches, 103 else => return err, 104 }; 105 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 106 const prepared = try evt.PatchRev.prepare(repo_kind, repo_opts, state, io, arena, &base, &source, patch.title, author, timestamp); 107 var updated = patch; 108 updated.revision = prepared.revision; 109 return .{ 110 prepared.event, 111 .{ .id = id, .author = author, .timestamp = timestamp, .event = .{ .patch = updated } }, 112 }; 113 } 114 115 // refresh open patches' tracked branches and, on the server, their mergeability. 116 // this runs outside the caller's transaction. 117 pub fn refreshBranches( 118 host_kind: evt.HostKind, 119 comptime repo_kind: rp.RepoKind, 120 comptime repo_opts: rp.RepoOpts(repo_kind), 121 io: std.Io, 122 allocator: std.mem.Allocator, 123 repo: *rp.Repo(repo_kind, repo_opts), 124 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 125 progress_ctx_maybe: ?repo_opts.ProgressCtx, 126 ) !void { 127 const DB = evt.EventDB(repo_opts.hash); 128 var arena = std.heap.ArenaAllocator.init(allocator); 129 defer arena.deinit(); 130 var patches: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?evt.Patch.Record) = .empty; 131 defer patches.deinit(allocator); 132 collect: { 133 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; 134 defer if (local_db) |*db| db.deinit(io, allocator); 135 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) { 136 error.NotFound => break :collect, 137 else => return err, 138 }; 139 if (repo_kind == .xit and host_kind == .server) open: { 140 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse break :open; 141 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 142 const open_cursor = try statuses.getCursor("open") orelse break :open; 143 const open_patches = try DB.SortedSet(.read_only).init(open_cursor); 144 var iter = try open_patches.iteratorFromIndex(0); 145 while (try iter.next()) |cursor| try patches.put(allocator, try evt.readOrderKeyId(DB, cursor), null); 146 } 147 const source_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.source_to_id_set_key)) orelse break :collect; 148 const sources = try DB.SortedMap(.read_only).init(source_cursor); 149 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; 150 var iter = try sources.iterator(); 151 while (try iter.next()) |cursor| { 152 const pair = try cursor.readKeyValuePair(); 153 const branch = try pair.key_cursor.readBytesAlloc(arena.allocator(), null); 154 if (updates) |changed| { 155 var found = false; 156 for (changed) |update| { 157 if (std.mem.startsWith(u8, update.ref_name, "refs/heads/") and std.mem.eql(u8, update.ref_name["refs/heads/".len..], branch)) { 158 found = true; 159 break; 160 } 161 } 162 if (!found) continue; 163 } 164 const source = (try repo.readRef(io, .{ .kind = .head, .name = branch })) orelse { 165 if (host_kind == .server) std.log.warn("patch source branch missing: {s}", .{branch}); 166 continue; 167 }; 168 const ids = try DB.CountedHashSet(.read_only).init(pair.value_cursor); 169 var ids_iter = try ids.iterator(); 170 while (try ids_iter.next()) |id_cursor| { 171 const id_pair = try id_cursor.readKeyValuePair(); 172 var id: [evt.event_id_size]u8 = undefined; 173 if ((try id_pair.key_cursor.readBytes(&id)).len != id.len) return error.InvalidPatch; 174 const record = (try evt.Patch.readById(DB, repo_opts.hash, moment, &arena, &id)) orelse continue; 175 if (record.removed or record.event.status.kind() != .open) continue; 176 if (conflicts) |map| if (try map.getCursor(&evt.orderKeyDesc(record.created_order, &id)) != null) continue; 177 if (record.event.revision) |revision| if (std.mem.eql(u8, revision.source_oid, &source)) continue; 178 try patches.put(allocator, id, record); 179 } 180 } 181 } 182 if (repo_opts.ProgressCtx != void) { 183 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .start = .{ .kind = .writing_patch, .estimated_total_items = patches.count() } }) catch {}; 184 } 185 for (patches.keys(), patches.values()) |id, record_maybe| { 186 if (record_maybe) |record| { 187 const author = evt.CommitAuthor{ .name = "haxy", .email = record.author_email orelse "user@haxy" }; 188 writeBranchPatch(host_kind, repo_kind, repo_opts, io, allocator, repo, std.fmt.bytesToHex(id, .lower), record.event, record.event, author) catch |err| { 189 if (host_kind == .server) std.log.warn("failed to refresh branch patch: {s}", .{@errorName(err)}); 190 }; 191 } 192 if (repo_kind == .xit and host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, id); 193 if (repo_opts.ProgressCtx != void) { 194 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .complete_one = .writing_patch }) catch {}; 195 } 196 } 197 if (repo_opts.ProgressCtx != void) { 198 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .end = .writing_patch }) catch {}; 199 } 200 } 201 202 pub const PublishInput = struct { 203 id: [evt.event_id_size * 2]u8, 204 user_id: [evt.event_id_size]u8, 205 repo_id: [evt.event_id_size]u8, 206 author: evt.CommitAuthor, 207 timestamp: u64, 208 }; 209 210 pub const EditDraftInput = struct { 211 id: [evt.event_id_size * 2]u8, 212 user_id: [evt.event_id_size]u8, 213 repo_id: [evt.event_id_size]u8, 214 title: []const u8, 215 tags: []const u8, 216 description: []const u8, 217 target_branch: []const u8, 218 author: evt.CommitAuthor, 219 timestamp: u64, 220 }; 221 222 pub const Mergeability = struct { 223 pub const Status = enum { clean, conflict, unknown }; 224 225 source: Status = .unknown, 226 squash: Status = .unknown, 227 228 pub fn get(self: Mergeability, revision: evt.Patch.MergeRevision) Status { 229 return switch (revision) { 230 .source => self.source, 231 .squash => self.squash, 232 }; 233 } 234 235 pub fn status(self: Mergeability) Status { 236 if (self.source == .clean or self.squash == .clean) return .clean; 237 if (self.source == .conflict and self.squash == .conflict) return .conflict; 238 return .unknown; 239 } 240 }; 241 242 const MergeCheck = struct { 243 revision: evt.Patch.Revision, 244 target_branch: []const u8, 245 target_oid: []const u8, 246 result: Mergeability = .{}, 247 248 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 249 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 250 std.mem.eql(u8, self.target_branch, patch.target_branch) and 251 std.mem.eql(u8, self.target_oid, target_oid); 252 } 253 }; 254 255 fn readMergeCheck( 256 comptime repo_opts: rp.RepoOpts(.xit), 257 haxy_moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 258 arena: *std.heap.ArenaAllocator, 259 id: *const [evt.event_id_size]u8, 260 ) !?MergeCheck { 261 const DB = evt.EventDB(repo_opts.hash); 262 const map_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)) orelse return null; 263 const map = try DB.HashMap(.read_only).init(map_cursor); 264 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 265 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 266 error.InvalidEnumTag => return null, 267 else => return err, 268 }; 269 } 270 271 // reads never run a merge or refresh the cache 272 pub fn readMergeability( 273 comptime repo_opts: rp.RepoOpts(.xit), 274 state: rp.Repo(.xit, repo_opts).State(.read_only), 275 io: std.Io, 276 arena: *std.heap.ArenaAllocator, 277 id: *const [evt.event_id_size]u8, 278 patch: evt.Patch, 279 ) !Mergeability { 280 if (patch.source_branch != null and !try branchCurrent(repo_opts, state, io, arena, patch)) return .{}; 281 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 282 const haxy_moment = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*) catch |err| switch (err) { 283 error.NotFound => return .{}, 284 else => return err, 285 }; 286 const cached = try readMergeCheck(repo_opts, haxy_moment, arena, id) orelse return .{}; 287 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 288 } 289 290 // refresh after the caller's transaction and locks have finished. a check 291 // failure must not turn an accepted push or event into a failed operation. 292 pub fn refreshMergeability( 293 comptime repo_opts: rp.RepoOpts(.xit), 294 io: std.Io, 295 allocator: std.mem.Allocator, 296 target_repo: *rp.Repo(.xit, repo_opts), 297 id_maybe: ?[evt.event_id_size]u8, 298 ) void { 299 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 300 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 301 }; 302 } 303 304 fn refreshMergeChecks( 305 comptime repo_opts: rp.RepoOpts(.xit), 306 io: std.Io, 307 allocator: std.mem.Allocator, 308 target_repo: *rp.Repo(.xit, repo_opts), 309 id_maybe: ?[evt.event_id_size]u8, 310 ) !void { 311 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 312 const DB = evt.EventDB(repo_opts.hash); 313 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 314 error.NotFound => return, 315 else => return err, 316 }; 317 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 318 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 319 const open_cursor = try statuses.getCursor("open") orelse return; 320 const open = try DB.SortedSet(.read_only).init(open_cursor); 321 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 322 defer ids.deinit(allocator); 323 var iter = try open.iteratorFromIndex(0); 324 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 325 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 326 } 327 328 fn refreshMergeCheck( 329 comptime repo_opts: rp.RepoOpts(.xit), 330 io: std.Io, 331 allocator: std.mem.Allocator, 332 target_repo: *rp.Repo(.xit, repo_opts), 333 id: *const [evt.event_id_size]u8, 334 ) !void { 335 const Repo = rp.Repo(.xit, repo_opts); 336 const DB = Repo.DB; 337 var arena = std.heap.ArenaAllocator.init(allocator); 338 defer arena.deinit(); 339 const initial = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, id)) orelse return; 340 if (initial.removed or initial.event.status.kind() != .open) return; 341 const repo_root_path = std.fs.path.dirname(target_repo.core.work_path) orelse "."; 342 const path = try fork.forkPath(arena.allocator(), repo_root_path, &std.fmt.bytesToHex(id.*, .lower)); 343 const branch_backed = initial.event.source_branch != null; 344 var fork_repo_maybe: ?Repo = if (branch_backed) null else Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| blk: { 345 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 346 break :blk null; 347 }; 348 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 349 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 350 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 351 try target_repo.core.db_file.lock(io, .exclusive); 352 defer target_repo.core.db_file.unlock(io); 353 354 var target_moment = try target_repo.core.latestMoment(); 355 const target_state = Repo.State(.read_only){ .core = &target_repo.core, .extra = .{ .moment = &target_moment } }; 356 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, target_moment) catch |err| switch (err) { 357 error.NotFound => return, 358 else => return err, 359 }; 360 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, &arena, id)) orelse return; 361 if (patch_record.removed or patch_record.event.status.kind() != .open) return; 362 var newest: ?evt.PatchRev.WithId = null; 363 if (fork_repo_maybe) |*repo| { 364 if (evt.currentMoment(repo_opts, repo)) |events| { 365 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, &arena) catch |err| blk: { 366 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 367 break :blk null; 368 }; 369 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 370 } 371 const patch = patch_record.event; 372 const revision = patch.revision orelse return; 373 const target_oid = try rf.readRecur(.xit, repo_opts, target_state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 374 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 375 const cached = try readMergeCheck(repo_opts, target_events, &arena, id); 376 const current = if (patch.source_branch != null) try branchCurrent(repo_opts, target_state, io, &arena, patch) else if (newest) |latest| std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) else false; 377 if (current and target_oid != null) { 378 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return; 379 const Ctx = struct { 380 repo: *Repo, 381 fork_repo: ?*Repo, 382 io: std.Io, 383 allocator: std.mem.Allocator, 384 check: *MergeCheck, 385 386 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 387 var moment = try DB.HashMap(.read_write).init(cursor.*); 388 const state = Repo.State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 389 const source = try oidArray(repo_opts.hash, ctx.check.revision.source_oid); 390 const squash = try oidArray(repo_opts.hash, ctx.check.revision.squash_oid); 391 if (ctx.fork_repo) |repo| { 392 var fork_moment = try repo.core.latestMoment(); 393 const fork_state = Repo.State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 394 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 395 defer objects.deinit(); 396 try objects.include(&source); 397 try objects.include(&squash); 398 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 399 } 400 const target = rf.Ref{ .kind = .head, .name = ctx.check.target_branch }; 401 ctx.check.result.source = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &source, target); 402 ctx.check.result.squash = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &squash, target); 403 return error.CancelTransaction; 404 } 405 }; 406 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 407 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 408 .repo = target_repo, 409 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 410 .io = io, 411 .allocator = allocator, 412 .check = &check, 413 }) catch |err| switch (err) { 414 error.CancelTransaction => {}, 415 else => std.log.warn("mergeability check failed: {s}", .{@errorName(err)}), 416 }; 417 } 418 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return; 419 const Save = struct { 420 id: [evt.event_id_size]u8, 421 check: MergeCheck, 422 423 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 424 const moment = try DB.HashMap(.read_write).init(cursor.*); 425 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 426 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 427 _ = try last_object_id_cursor.readBytes(&last_object_id); 428 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 429 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 430 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 431 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 432 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, &ctx.id))); 433 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, ctx.check); 434 // discard the old repo-level cache as results are rebuilt here 435 _ = try moment.remove(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)); 436 } 437 }; 438 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 439 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Save{ .id = id.*, .check = check }); 440 } 441 442 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 { 443 const branch = patch.source_branch orelse return false; 444 const selected = patch.revision orelse return false; 445 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 446 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 447 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 448 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 449 return selected.matches(revision); 450 } 451 452 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 453 try evt.PatchRev.validateOid(hash_kind, oid); 454 var result: [hash.hexLen(hash_kind)]u8 = undefined; 455 @memcpy(&result, oid); 456 return result; 457 } 458 459 fn checkCommit( 460 comptime repo_opts: rp.RepoOpts(.xit), 461 state: rp.Repo(.xit, repo_opts).State(.read_write), 462 io: std.Io, 463 allocator: std.mem.Allocator, 464 oid: *const [hash.hexLen(repo_opts.hash)]u8, 465 target: rf.Ref, 466 ) Mergeability.Status { 467 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 468 .kind = .full, 469 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 470 .dry_run = true, 471 }, target, null) catch |err| { 472 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 473 return .unknown; 474 }; 475 defer result.deinit(); 476 return switch (result.result) { 477 .conflict => .conflict, 478 .clean, .success, .nothing, .fast_forward => .clean, 479 }; 480 } 481 482 pub const MergeInput = struct { 483 id: [evt.event_id_size * 2]u8, 484 revision: evt.Patch.MergeRevision, 485 author: evt.CommitAuthor, 486 timestamp: u64, 487 }; 488 489 pub fn publish( 490 comptime repo_opts: rp.RepoOpts(.xit), 491 io: std.Io, 492 allocator: std.mem.Allocator, 493 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 494 target_repo: *rp.Repo(.xit, repo_opts), 495 fork_path: []const u8, 496 input: PublishInput, 497 ) !void { 498 const patch_id = try evt.parseEventId(&input.id); 499 var arena = std.heap.ArenaAllocator.init(allocator); 500 defer arena.deinit(); 501 502 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 503 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 504 if (fork_record.removed or 505 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 506 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 507 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 508 if (user.removed or 509 !std.mem.eql(u8, user.event.name, input.author.name) or 510 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 511 512 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 513 defer fork_repo.deinit(io, allocator); 514 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 515 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 516 517 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 518 error.NotFound => null, 519 else => |other| return other, 520 }; 521 const existing = if (target_moment) |moment| 522 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 523 else 524 null; 525 if (existing) |record| { 526 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 527 } 528 if (local_patch.removed) { 529 if (existing == null) return error.PatchDataUnavailable; 530 } else { 531 var patch = (existing orelse local_patch).event; 532 if (local_patch.event.revision) |selected| { 533 const revision_id = try evt.parseEventId(&selected.id); 534 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 535 if (!selected.matches(revision)) return error.PatchNotPushed; 536 patch.revision = selected; 537 } 538 if (existing == null) patch.status = .open; 539 540 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 541 .id = input.id, 542 .timestamp = input.timestamp, 543 .author = input.author, 544 .event = .{ .patch = patch }, 545 }}); 546 547 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 548 .id = input.id, 549 .timestamp = input.timestamp, 550 .author = input.author, 551 .event = .{ .patch = null }, 552 }}); 553 } 554 555 if (fork_record.event.stage == .draft) { 556 var published = fork_record.event; 557 published.stage = .publish; 558 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 559 .id = input.id, 560 .timestamp = input.timestamp, 561 .author = input.author, 562 .event = .{ .fork = published }, 563 }}); 564 } 565 } 566 567 pub fn editDraft( 568 comptime repo_opts: rp.RepoOpts(.xit), 569 io: std.Io, 570 allocator: std.mem.Allocator, 571 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 572 fork_path: []const u8, 573 input: EditDraftInput, 574 ) !bool { 575 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 576 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 577 const patch_id = try evt.parseEventId(&input.id); 578 var arena = std.heap.ArenaAllocator.init(allocator); 579 defer arena.deinit(); 580 581 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 582 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 583 if (fork_record.event.stage != .draft) return false; 584 if (fork_record.removed or 585 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 586 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 587 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 588 if (user.removed or 589 !std.mem.eql(u8, user.event.name, input.author.name) or 590 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 591 592 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 593 defer fork_repo.deinit(io, allocator); 594 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 595 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 596 if (record.removed) return error.PatchDataUnavailable; 597 598 var patch = record.event; 599 patch.title = input.title; 600 patch.tags = input.tags; 601 patch.description = input.description; 602 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 603 patch.target_branch = input.target_branch; 604 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 605 .id = input.id, 606 .timestamp = input.timestamp, 607 .author = input.author, 608 .event = .{ .patch = patch }, 609 }}); 610 return true; 611 } 612 613 // merge the selected patch revision into its target branch 614 pub fn merge( 615 comptime repo_opts: rp.RepoOpts(.xit), 616 io: std.Io, 617 allocator: std.mem.Allocator, 618 repo_root_path: []const u8, 619 target_repo: *rp.Repo(.xit, repo_opts), 620 input: MergeInput, 621 ) !void { 622 const patch_id = try evt.parseEventId(&input.id); 623 errdefer |err| { 624 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 625 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 626 } 627 } 628 var arena = std.heap.ArenaAllocator.init(allocator); 629 defer arena.deinit(); 630 631 // validate the target patch 632 const target_moment = try evt.currentMoment(repo_opts, target_repo); 633 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 634 if (patch_record.removed) return error.InvalidPatch; 635 switch (patch_record.event.status) { 636 .open => {}, 637 .closed => return error.PatchClosed, 638 .merged => return error.PatchAlreadyMerged, 639 } 640 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 641 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 642 643 // open the fork 644 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 645 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; 646 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 647 // select the commit and merge identity 648 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 649 .squash => selected.squash_oid, 650 .source => selected.source_oid, 651 }) catch return error.InvalidPatch; 652 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 653 654 // merge the code and events in one target transaction 655 { 656 const DB = rp.Repo(.xit, repo_opts).DB; 657 const State = rp.Repo(.xit, repo_opts).State; 658 const Ctx = struct { 659 core: *rp.Repo(.xit, repo_opts).Core, 660 fork_repo: ?*rp.Repo(.xit, repo_opts), 661 io: std.Io, 662 allocator: std.mem.Allocator, 663 patch_id: [evt.event_id_size]u8, 664 expected_patch: evt.Patch, 665 target_ref: rf.Ref, 666 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 667 revision: evt.Patch.MergeRevision, 668 identity: []const u8, 669 author: evt.CommitAuthor, 670 timestamp: u64, 671 672 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 673 var moment = try DB.HashMap(.read_write).init(cursor.*); 674 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 675 676 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 677 defer check_arena.deinit(); 678 679 // require the fork's newest revision while both repos are locked 680 const selected_revision = ctx.expected_patch.revision orelse unreachable; 681 const revision_id = try evt.parseEventId(&selected_revision.id); 682 if (ctx.fork_repo) |repo| { 683 const fork_moment = try evt.currentMoment(repo_opts, repo); 684 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 685 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 686 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 687 688 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 689 switch (availability.get(ctx.revision)) { 690 .clean => {}, 691 .conflict => return error.MergeConflict, 692 .unknown => return error.MergeCheckUnavailable, 693 } 694 695 // copy the selected commit and its dependencies 696 if (ctx.fork_repo) |repo| { 697 var fork_repo_moment = try repo.core.latestMoment(); 698 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 699 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 700 defer objects.deinit(); 701 try objects.include(&ctx.selected_oid); 702 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 703 } 704 705 // merge the selected commit 706 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 707 { 708 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 709 .kind = .full, 710 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 711 .commit_metadata = .{ 712 .author = ctx.identity, 713 .committer = ctx.identity, 714 .message = ctx.expected_patch.title, 715 .timestamp = ctx.timestamp, 716 }, 717 }, ctx.target_ref, null); 718 defer merge_result.deinit(); 719 switch (merge_result.result) { 720 .conflict => return error.MergeConflict, 721 .success, .fast_forward, .nothing => {}, 722 .clean => unreachable, 723 } 724 } 725 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 726 727 // retain the submitted revision and snapshot the merge result 728 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; 729 730 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "merge patch" }); 731 } 732 }; 733 734 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 735 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 736 try target_repo.core.db_file.lock(io, .exclusive); 737 defer target_repo.core.db_file.unlock(io); 738 739 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 740 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 741 .core = &target_repo.core, 742 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 743 .io = io, 744 .allocator = allocator, 745 .patch_id = patch_id, 746 .expected_patch = patch_record.event, 747 .target_ref = target_ref, 748 .selected_oid = selected_oid, 749 .revision = input.revision, 750 .identity = identity, 751 .author = input.author, 752 .timestamp = input.timestamp, 753 }); 754 } 755 refreshMergeability(repo_opts, io, allocator, target_repo, null); 756 // the merge moved the target branch, so its indexes follow 757 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 758 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 759 }; 760 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 761 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 762 }; 763 } 764 765 // merge a published patch and remove its fork 766 pub fn mergeAndRemoveFork( 767 comptime repo_opts: rp.RepoOpts(.xit), 768 io: std.Io, 769 allocator: std.mem.Allocator, 770 repo_root_path: []const u8, 771 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 772 target_repo: *rp.Repo(.xit, repo_opts), 773 input: MergeInput, 774 ) !void { 775 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 776 var arena = std.heap.ArenaAllocator.init(allocator); 777 defer arena.deinit(); 778 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 779 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 780 } 781 782 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 783 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 784 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 785 const name = std.mem.trimEnd(u8, line[0..open], " "); 786 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 787 return .{ .name = name, .email = line[open + 1 .. close] }; 788 } 789 790 // import a revision after detecting a client-side merge 791 fn importMerged( 792 comptime repo_opts: rp.RepoOpts(.xit), 793 state: rp.Repo(.xit, repo_opts).State(.read_write), 794 db: *evt.EventDB(repo_opts.hash), 795 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 796 io: std.Io, 797 allocator: std.mem.Allocator, 798 repo_root_path: []const u8, 799 patch_id: *const [evt.event_id_size]u8, 800 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 801 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 802 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 803 ) !void { 804 var arena = std.heap.ArenaAllocator.init(allocator); 805 defer arena.deinit(); 806 807 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 808 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 809 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 810 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 811 const selected = record.event.revision orelse return; 812 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; 813 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 }); 814 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 815 816 _ = 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); 817 } 818 819 // import the revision and mark its patch merged in the current transaction 820 fn importMergedRevision( 821 comptime repo_opts: rp.RepoOpts(.xit), 822 state: rp.Repo(.xit, repo_opts).State(.read_write), 823 db: *evt.EventDB(repo_opts.hash), 824 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 825 io: std.Io, 826 allocator: std.mem.Allocator, 827 fork_repo: ?*rp.Repo(.xit, repo_opts), 828 patch_id: *const [evt.event_id_size]u8, 829 merged: struct { 830 revision: evt.Patch.MergeRevision, 831 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 832 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 833 }, 834 expected_patch: ?evt.Patch, 835 merged_author: ?evt.CommitAuthor, 836 merged_timestamp: u64, 837 ) !bool { 838 const DB = evt.EventDB(repo_opts.hash); 839 var arena = std.heap.ArenaAllocator.init(allocator); 840 defer arena.deinit(); 841 842 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 843 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 844 const selected = patch_record.event.revision orelse return false; 845 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 846 if (expected_patch) |expected| { 847 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 848 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 849 const conflicts = try DB.SortedMap(.read_only).init(cursor); 850 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 851 } 852 } 853 const revision_id = try evt.parseEventId(&selected.id); 854 855 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 856 const revision = (if (fork_repo) |repo| 857 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 858 else 859 current_revision) orelse return false; 860 if (!selected.matches(revision)) return false; 861 862 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 863 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 } }; 864 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 865 if (revision.event_oid.len != event_oid.len) return false; 866 @memcpy(&event_oid, revision.event_oid); 867 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 868 defer event_object.deinit(); 869 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 870 871 var events_buffer: [3]evt.EventWithId = undefined; 872 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 873 var tree_entries: [2]evt.EventTreeEntry = undefined; 874 const needs_import = if (current_revision) |existing| existing.removed else true; 875 if (needs_import) { 876 tree_entries = .{ 877 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 878 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 879 }; 880 events.appendAssumeCapacity(.{ 881 .id = selected.id, 882 .timestamp = event_object.content.commit.metadata.timestamp, 883 .author = original_author, 884 .tree_entries = &tree_entries, 885 .event = .{ .patchrev = revision.event }, 886 }); 887 } else { 888 const existing = current_revision orelse unreachable; 889 if (!selected.matches(existing)) return error.InvalidPatch; 890 } 891 892 const author = merged_author orelse original_author; 893 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 894 var patch = patch_record.event; 895 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 896 events.appendAssumeCapacity(result.event); 897 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 898 events.appendAssumeCapacity(.{ 899 .id = std.fmt.bytesToHex(patch_id.*, .lower), 900 .timestamp = timestamp, 901 .author = author, 902 .event = .{ .patch = patch }, 903 }); 904 905 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 906 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 907 return true; 908 } 909 910 // find patches merged by commits received in a push 911 pub fn detectMerged( 912 comptime repo_opts: rp.RepoOpts(.xit), 913 state: rp.Repo(.xit, repo_opts).State(.read_write), 914 db: *evt.EventDB(repo_opts.hash), 915 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 916 io: std.Io, 917 allocator: std.mem.Allocator, 918 repo_root_path: []const u8, 919 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 920 error_writer: *std.Io.Writer, 921 ) !void { 922 const DB = evt.EventDB(repo_opts.hash); 923 var arena = std.heap.ArenaAllocator.init(allocator); 924 defer arena.deinit(); 925 926 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 927 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 928 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 929 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 930 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 931 const heads_prefix = "refs/heads/"; 932 for (updates) |update| { 933 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 934 std.mem.eql(u8, update.ref_name, events_ref_path) or 935 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 936 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 937 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 938 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 939 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 940 @memcpy(&old_oid, update.old_oid); 941 @memcpy(&new_oid, update.new_oid); 942 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 943 944 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 945 defer commits.deinit(); 946 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 947 var targets: std.ArrayList(struct { 948 before_oid: [hash.hexLen(repo_opts.hash)]u8, 949 after_oid: [hash.hexLen(repo_opts.hash)]u8, 950 }) = .empty; 951 { 952 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 953 defer first_parents.deinit(); 954 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 955 try first_parents.include(&new_oid); 956 while (try first_parents.next(arena.allocator())) |commit| { 957 defer commit.deinit(); 958 try targets.append(arena.allocator(), .{ 959 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 960 .after_oid = commit.oid, 961 }); 962 } 963 } 964 965 // visit target commits oldest first, attributing each revision to the 966 // commit that introduced it; the shared iterator visits each ancestor once 967 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 968 while (targets.pop()) |target| { 969 try commits.include(&target.after_oid); 970 while (try commits.next(arena.allocator())) |commit| { 971 defer commit.deinit(); 972 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 973 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 974 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 975 var ids_iter = try ids.iterator(); 976 while (try ids_iter.next()) |cursor| { 977 const pair = try cursor.readKeyValuePair(); 978 var patch_id: [evt.event_id_size]u8 = undefined; 979 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 980 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 981 // a fast-forward has no recorded merge boundary; use the old ref tip 982 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 983 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 984 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 985 continue; 986 }; 987 } 988 } 989 } 990 } 991 } 992