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