╭ 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 fork = @import("fork.zig"); 11 const serve_common = @import("serve_common.zig"); 12 13 // capture an existing branch without creating a fork 14 pub fn writeBranchPatch( 15 host_kind: evt.HostKind, 16 comptime repo_kind: rp.RepoKind, 17 comptime repo_opts: rp.RepoOpts(repo_kind), 18 io: std.Io, 19 allocator: std.mem.Allocator, 20 repo: *rp.Repo(repo_kind, repo_opts), 21 id: [evt.event_id_size * 2]u8, 22 patch: evt.Patch, 23 expected_patch: ?evt.Patch, 24 author: evt.CommitAuthor, 25 ) !void { 26 var arena = std.heap.ArenaAllocator.init(allocator); 27 defer arena.deinit(); 28 if (repo_kind == .git) { 29 if (expected_patch) |expected| { 30 const current = (try evt.readFromRepo(evt.Patch, repo_kind, repo_opts, io, allocator, &arena, repo, &try evt.parseEventId(&id))) orelse return error.PatchOutOfDate; 31 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 32 } 33 const events = try branchEvents(repo_kind, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, &arena, id, patch, author); 34 try evt.consume(host_kind, .repo, repo_kind, repo_opts, io, allocator, repo, evt.events_ref, &events); 35 } else { 36 const DB = evt.EventDB(repo_opts.hash); 37 var first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8 = null; 38 if (try repo.readRef(io, evt.events_ref) == null) { 39 var remotes = try repo.listRemotes(io, allocator); 40 defer remotes.deinit(); 41 for (remotes.sections.keys()) |name| { 42 if (try repo.readRef(io, .{ .kind = .{ .remote = name }, .name = evt.events_ref.name })) |oid| { 43 first_parent = .{oid}; 44 break; 45 } 46 } 47 } 48 const Ctx = struct { 49 repo: *rp.Repo(repo_kind, repo_opts), 50 io: std.Io, 51 arena: *std.heap.ArenaAllocator, 52 id: [evt.event_id_size * 2]u8, 53 patch: evt.Patch, 54 expected_patch: ?evt.Patch, 55 author: evt.CommitAuthor, 56 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 57 58 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 59 var moment = try DB.HashMap(.read_write).init(cursor.*); 60 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 61 if (ctx.expected_patch) |expected| { 62 const events_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 63 const current = (try evt.Patch.readById(DB, repo_opts.hash, events_moment, ctx.arena, &try evt.parseEventId(&ctx.id))) orelse return error.PatchOutOfDate; 64 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 65 } 66 const events = try branchEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena, ctx.id, ctx.patch, ctx.author); 67 const parent = if (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), ctx.io, .{ .ref = evt.events_ref }) == null) ctx.first_parent else null; 68 try evt.commitEvents(repo_kind, repo_opts, state, ctx.io, ctx.arena.child_allocator, evt.events_ref, &events, parent); 69 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; 70 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "update branch patch" }); 71 } 72 }; 73 { 74 try repo.core.db_file.lock(io, .exclusive); 75 defer repo.core.db_file.unlock(io); 76 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 77 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 }); 78 } 79 if (host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, try evt.parseEventId(&id)); 80 } 81 } 82 83 fn branchEvents( 84 comptime repo_kind: rp.RepoKind, 85 comptime repo_opts: rp.RepoOpts(repo_kind), 86 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 87 io: std.Io, 88 arena: *std.heap.ArenaAllocator, 89 id: [evt.event_id_size * 2]u8, 90 patch: evt.Patch, 91 author: evt.CommitAuthor, 92 ) ![2]evt.EventWithId { 93 const branch = patch.source_branch orelse return error.InvalidSourceBranch; 94 if (!evt.Patch.fieldsValid(patch.title, patch.tags)) return error.InvalidFields; 95 if (!evt.Patch.branchValid(branch)) return error.InvalidSourceBranch; 96 if (!evt.Patch.branchValid(patch.target_branch)) return error.InvalidTargetBranch; 97 const source = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return error.InvalidSourceBranch; 98 const target = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } })) orelse return error.InvalidTargetBranch; 99 if (std.mem.eql(u8, branch, patch.target_branch)) return error.SameBranch; 100 const base = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, arena.allocator(), &target, &source) catch |err| switch (err) { 101 error.NoCommonAncestor => return error.UnrelatedBranches, 102 else => return err, 103 }; 104 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 105 const prepared = try evt.PatchRev.prepare(repo_kind, repo_opts, state, io, arena, &base, &source, patch.title, author, timestamp); 106 var updated = patch; 107 updated.revision = prepared.revision; 108 return .{ 109 prepared.event, 110 .{ .id = id, .author = author, .timestamp = timestamp, .event = .{ .patch = updated } }, 111 }; 112 } 113 114 // refresh open patches' tracked branches and, on the server, their mergeability. 115 // this runs outside the caller's transaction. 116 pub fn refreshBranches( 117 host_kind: evt.HostKind, 118 comptime repo_kind: rp.RepoKind, 119 comptime repo_opts: rp.RepoOpts(repo_kind), 120 io: std.Io, 121 allocator: std.mem.Allocator, 122 repo: *rp.Repo(repo_kind, repo_opts), 123 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 124 progress_ctx_maybe: ?repo_opts.ProgressCtx, 125 ) !void { 126 const DB = evt.EventDB(repo_opts.hash); 127 var arena = std.heap.ArenaAllocator.init(allocator); 128 defer arena.deinit(); 129 var patches: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?evt.Patch.Record) = .empty; 130 defer patches.deinit(allocator); 131 collect: { 132 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; 133 defer if (local_db) |*db| db.deinit(io, allocator); 134 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) { 135 error.NotFound => break :collect, 136 else => return err, 137 }; 138 if (repo_kind == .xit and host_kind == .server) open: { 139 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse break :open; 140 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 141 const open_cursor = try statuses.getCursor("open") orelse break :open; 142 const open_patches = try DB.SortedSet(.read_only).init(open_cursor); 143 var iter = try open_patches.iteratorFromIndex(0); 144 while (try iter.next()) |cursor| try patches.put(allocator, try evt.readOrderKeyId(DB, cursor), null); 145 } 146 const source_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.source_to_id_set_key)) orelse break :collect; 147 const sources = try DB.SortedMap(.read_only).init(source_cursor); 148 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; 149 var iter = try sources.iterator(); 150 while (try iter.next()) |cursor| { 151 const pair = try cursor.readKeyValuePair(); 152 const branch = try pair.key_cursor.readBytesAlloc(arena.allocator(), null); 153 if (updates) |changed| { 154 var found = false; 155 for (changed) |update| { 156 if (std.mem.startsWith(u8, update.ref_name, "refs/heads/") and std.mem.eql(u8, update.ref_name["refs/heads/".len..], branch)) { 157 found = true; 158 break; 159 } 160 } 161 if (!found) continue; 162 } 163 const source = (try repo.readRef(io, .{ .kind = .head, .name = branch })) orelse { 164 if (host_kind == .server) std.log.warn("patch source branch missing: {s}", .{branch}); 165 continue; 166 }; 167 const ids = try DB.CountedHashSet(.read_only).init(pair.value_cursor); 168 var ids_iter = try ids.iterator(); 169 while (try ids_iter.next()) |id_cursor| { 170 const id_pair = try id_cursor.readKeyValuePair(); 171 var id: [evt.event_id_size]u8 = undefined; 172 if ((try id_pair.key_cursor.readBytes(&id)).len != id.len) return error.InvalidPatch; 173 const record = (try evt.Patch.readById(DB, repo_opts.hash, moment, &arena, &id)) orelse continue; 174 if (record.removed or record.event.status.kind() != .open) continue; 175 if (conflicts) |map| if (try map.getCursor(&evt.orderKeyDesc(record.created_order, &id)) != null) continue; 176 if (record.event.revision) |revision| if (std.mem.eql(u8, revision.source_oid, &source)) continue; 177 try patches.put(allocator, id, record); 178 } 179 } 180 } 181 if (repo_opts.ProgressCtx != void) { 182 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .start = .{ .kind = .writing_patch, .estimated_total_items = patches.count() } }) catch {}; 183 } 184 for (patches.keys(), patches.values()) |id, record_maybe| { 185 if (record_maybe) |record| { 186 const author = evt.CommitAuthor{ .name = "haxy", .email = record.author_email orelse "user@haxy" }; 187 writeBranchPatch(host_kind, repo_kind, repo_opts, io, allocator, repo, std.fmt.bytesToHex(id, .lower), record.event, record.event, author) catch |err| { 188 if (host_kind == .server) std.log.warn("failed to refresh branch patch: {s}", .{@errorName(err)}); 189 }; 190 } 191 if (repo_kind == .xit and host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, id); 192 if (repo_opts.ProgressCtx != void) { 193 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .complete_one = .writing_patch }) catch {}; 194 } 195 } 196 if (repo_opts.ProgressCtx != void) { 197 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .end = .writing_patch }) catch {}; 198 } 199 } 200 201 pub const PublishInput = struct { 202 id: [evt.event_id_size * 2]u8, 203 user_id: [evt.event_id_size]u8, 204 repo_id: [evt.event_id_size]u8, 205 author: evt.CommitAuthor, 206 timestamp: u64, 207 }; 208 209 pub const EditDraftInput = struct { 210 id: [evt.event_id_size * 2]u8, 211 user_id: [evt.event_id_size]u8, 212 repo_id: [evt.event_id_size]u8, 213 title: []const u8, 214 tags: []const u8, 215 description: []const u8, 216 target_branch: []const u8, 217 author: evt.CommitAuthor, 218 timestamp: u64, 219 }; 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: evt.Patch.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.readFromRepo(evt.Patch, .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: evt.Patch.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 selected_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 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 658 revision: evt.Patch.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.selected_oid); 693 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 694 } 695 696 // merge the selected commit 697 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 698 { 699 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 700 .kind = .full, 701 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 702 .commit_metadata = .{ 703 .author = ctx.identity, 704 .committer = ctx.identity, 705 .message = ctx.expected_patch.title, 706 .timestamp = ctx.timestamp, 707 }, 708 }, ctx.target_ref, null); 709 defer merge_result.deinit(); 710 switch (merge_result.result) { 711 .conflict => return error.MergeConflict, 712 .success, .fast_forward, .nothing => {}, 713 .clean => unreachable, 714 } 715 } 716 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 717 718 // retain the submitted revision and snapshot the merge result 719 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; 720 721 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "merge patch" }); 722 } 723 }; 724 725 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 726 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 727 try target_repo.core.db_file.lock(io, .exclusive); 728 defer target_repo.core.db_file.unlock(io); 729 730 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 731 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 732 .core = &target_repo.core, 733 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 734 .io = io, 735 .allocator = allocator, 736 .patch_id = patch_id, 737 .expected_patch = patch_record.event, 738 .target_ref = target_ref, 739 .selected_oid = selected_oid, 740 .revision = input.revision, 741 .identity = identity, 742 .author = input.author, 743 .timestamp = input.timestamp, 744 }); 745 } 746 refreshMergeability(repo_opts, io, allocator, target_repo, null); 747 // the merge moved the target branch, so its file index follows 748 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 749 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 750 }; 751 } 752 753 // merge a published patch and remove its fork 754 pub fn mergeAndRemoveFork( 755 comptime repo_opts: rp.RepoOpts(.xit), 756 io: std.Io, 757 allocator: std.mem.Allocator, 758 repo_root_path: []const u8, 759 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 760 target_repo: *rp.Repo(.xit, repo_opts), 761 input: MergeInput, 762 ) !void { 763 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 764 var arena = std.heap.ArenaAllocator.init(allocator); 765 defer arena.deinit(); 766 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 767 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 768 } 769 770 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 771 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 772 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 773 const name = std.mem.trimEnd(u8, line[0..open], " "); 774 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 775 return .{ .name = name, .email = line[open + 1 .. close] }; 776 } 777 778 // import a revision after detecting a client-side merge 779 fn importMerged( 780 comptime repo_opts: rp.RepoOpts(.xit), 781 state: rp.Repo(.xit, repo_opts).State(.read_write), 782 db: *evt.EventDB(repo_opts.hash), 783 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 784 io: std.Io, 785 allocator: std.mem.Allocator, 786 repo_root_path: []const u8, 787 patch_id: *const [evt.event_id_size]u8, 788 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 789 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 790 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 791 ) !void { 792 var arena = std.heap.ArenaAllocator.init(allocator); 793 defer arena.deinit(); 794 795 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 796 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 797 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 798 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 799 const selected = record.event.revision orelse return; 800 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; 801 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 }); 802 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 803 804 _ = 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); 805 } 806 807 // import the revision and mark its patch merged in the current transaction 808 fn importMergedRevision( 809 comptime repo_opts: rp.RepoOpts(.xit), 810 state: rp.Repo(.xit, repo_opts).State(.read_write), 811 db: *evt.EventDB(repo_opts.hash), 812 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 813 io: std.Io, 814 allocator: std.mem.Allocator, 815 fork_repo: ?*rp.Repo(.xit, repo_opts), 816 patch_id: *const [evt.event_id_size]u8, 817 merged: struct { 818 revision: evt.Patch.MergeRevision, 819 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 820 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 821 }, 822 expected_patch: ?evt.Patch, 823 merged_author: ?evt.CommitAuthor, 824 merged_timestamp: u64, 825 ) !bool { 826 const DB = evt.EventDB(repo_opts.hash); 827 var arena = std.heap.ArenaAllocator.init(allocator); 828 defer arena.deinit(); 829 830 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 831 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 832 const selected = patch_record.event.revision orelse return false; 833 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 834 if (expected_patch) |expected| { 835 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 836 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 837 const conflicts = try DB.SortedMap(.read_only).init(cursor); 838 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 839 } 840 } 841 const revision_id = try evt.parseEventId(&selected.id); 842 843 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 844 const revision = (if (fork_repo) |repo| 845 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 846 else 847 current_revision) orelse return false; 848 if (!selected.matches(revision)) return false; 849 850 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 851 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 } }; 852 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 853 if (revision.event_oid.len != event_oid.len) return false; 854 @memcpy(&event_oid, revision.event_oid); 855 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 856 defer event_object.deinit(); 857 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 858 859 var events_buffer: [3]evt.EventWithId = undefined; 860 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 861 var tree_entries: [2]evt.EventTreeEntry = undefined; 862 const needs_import = if (current_revision) |existing| existing.removed else true; 863 if (needs_import) { 864 tree_entries = .{ 865 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 866 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 867 }; 868 events.appendAssumeCapacity(.{ 869 .id = selected.id, 870 .timestamp = event_object.content.commit.metadata.timestamp, 871 .author = original_author, 872 .tree_entries = &tree_entries, 873 .event = .{ .patchrev = revision.event }, 874 }); 875 } else { 876 const existing = current_revision orelse unreachable; 877 if (!selected.matches(existing)) return error.InvalidPatch; 878 } 879 880 const author = merged_author orelse original_author; 881 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 882 var patch = patch_record.event; 883 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 884 events.appendAssumeCapacity(result.event); 885 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 886 events.appendAssumeCapacity(.{ 887 .id = std.fmt.bytesToHex(patch_id.*, .lower), 888 .timestamp = timestamp, 889 .author = author, 890 .event = .{ .patch = patch }, 891 }); 892 893 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 894 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 895 return true; 896 } 897 898 // find patches merged by commits received in a push 899 pub fn detectMerged( 900 comptime repo_opts: rp.RepoOpts(.xit), 901 state: rp.Repo(.xit, repo_opts).State(.read_write), 902 db: *evt.EventDB(repo_opts.hash), 903 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 904 io: std.Io, 905 allocator: std.mem.Allocator, 906 repo_root_path: []const u8, 907 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 908 error_writer: *std.Io.Writer, 909 ) !void { 910 const DB = evt.EventDB(repo_opts.hash); 911 var arena = std.heap.ArenaAllocator.init(allocator); 912 defer arena.deinit(); 913 914 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 915 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 916 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 917 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 918 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 919 const heads_prefix = "refs/heads/"; 920 for (updates) |update| { 921 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 922 std.mem.eql(u8, update.ref_name, events_ref_path) or 923 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 924 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 925 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 926 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 927 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 928 @memcpy(&old_oid, update.old_oid); 929 @memcpy(&new_oid, update.new_oid); 930 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 931 932 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 933 defer commits.deinit(); 934 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 935 var targets: std.ArrayList(struct { 936 before_oid: [hash.hexLen(repo_opts.hash)]u8, 937 after_oid: [hash.hexLen(repo_opts.hash)]u8, 938 }) = .empty; 939 { 940 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 941 defer first_parents.deinit(); 942 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 943 try first_parents.include(&new_oid); 944 while (try first_parents.next(arena.allocator())) |commit| { 945 defer commit.deinit(); 946 try targets.append(arena.allocator(), .{ 947 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 948 .after_oid = commit.oid, 949 }); 950 } 951 } 952 953 // visit target commits oldest first, attributing each revision to the 954 // commit that introduced it; the shared iterator visits each ancestor once 955 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 956 while (targets.pop()) |target| { 957 try commits.include(&target.after_oid); 958 while (try commits.next(arena.allocator())) |commit| { 959 defer commit.deinit(); 960 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 961 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 962 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 963 var ids_iter = try ids.iterator(); 964 while (try ids_iter.next()) |cursor| { 965 const pair = try cursor.readKeyValuePair(); 966 var patch_id: [evt.event_id_size]u8 = undefined; 967 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 968 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 969 // a fast-forward has no recorded merge boundary; use the old ref tip 970 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 971 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 972 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 973 continue; 974 }; 975 } 976 } 977 } 978 } 979 } 980