╭ 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 MergeCheck = struct { 242 revision: evt.Patch.Revision, 243 target_branch: []const u8, 244 target_oid: []const u8, 245 result: Mergeability = .{}, 246 247 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 248 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 249 std.mem.eql(u8, self.target_branch, patch.target_branch) and 250 std.mem.eql(u8, self.target_oid, target_oid); 251 } 252 }; 253 254 fn readMergeCheck( 255 comptime repo_opts: rp.RepoOpts(.xit), 256 haxy_moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 257 arena: *std.heap.ArenaAllocator, 258 id: *const [evt.event_id_size]u8, 259 ) !?MergeCheck { 260 const DB = evt.EventDB(repo_opts.hash); 261 const map_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)) orelse return null; 262 const map = try DB.HashMap(.read_only).init(map_cursor); 263 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 264 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 265 error.InvalidEnumTag => return null, 266 else => return err, 267 }; 268 } 269 270 // reads never run a merge or refresh the cache 271 pub fn readMergeability( 272 comptime repo_opts: rp.RepoOpts(.xit), 273 state: rp.Repo(.xit, repo_opts).State(.read_only), 274 io: std.Io, 275 arena: *std.heap.ArenaAllocator, 276 id: *const [evt.event_id_size]u8, 277 patch: evt.Patch, 278 ) !Mergeability { 279 if (patch.source_branch != null and !try branchCurrent(repo_opts, state, io, arena, patch)) return .{}; 280 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 281 const haxy_moment = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*) catch |err| switch (err) { 282 error.NotFound => return .{}, 283 else => return err, 284 }; 285 const cached = try readMergeCheck(repo_opts, haxy_moment, arena, id) orelse return .{}; 286 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 287 } 288 289 // refresh after the caller's transaction and locks have finished. a check 290 // failure must not turn an accepted push or event into a failed operation. 291 pub fn refreshMergeability( 292 comptime repo_opts: rp.RepoOpts(.xit), 293 io: std.Io, 294 allocator: std.mem.Allocator, 295 target_repo: *rp.Repo(.xit, repo_opts), 296 id_maybe: ?[evt.event_id_size]u8, 297 ) void { 298 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 299 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 300 }; 301 } 302 303 fn refreshMergeChecks( 304 comptime repo_opts: rp.RepoOpts(.xit), 305 io: std.Io, 306 allocator: std.mem.Allocator, 307 target_repo: *rp.Repo(.xit, repo_opts), 308 id_maybe: ?[evt.event_id_size]u8, 309 ) !void { 310 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 311 const DB = evt.EventDB(repo_opts.hash); 312 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 313 error.NotFound => return, 314 else => return err, 315 }; 316 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 317 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 318 const open_cursor = try statuses.getCursor("open") orelse return; 319 const open = try DB.SortedSet(.read_only).init(open_cursor); 320 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 321 defer ids.deinit(allocator); 322 var iter = try open.iteratorFromIndex(0); 323 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 324 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 325 } 326 327 fn refreshMergeCheck( 328 comptime repo_opts: rp.RepoOpts(.xit), 329 io: std.Io, 330 allocator: std.mem.Allocator, 331 target_repo: *rp.Repo(.xit, repo_opts), 332 id: *const [evt.event_id_size]u8, 333 ) !void { 334 const Repo = rp.Repo(.xit, repo_opts); 335 const DB = Repo.DB; 336 var arena = std.heap.ArenaAllocator.init(allocator); 337 defer arena.deinit(); 338 const initial = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, id)) orelse return; 339 if (initial.removed or initial.event.status.kind() != .open) return; 340 const repo_root_path = std.fs.path.dirname(target_repo.core.work_path) orelse "."; 341 const path = try fork.forkPath(arena.allocator(), repo_root_path, &std.fmt.bytesToHex(id.*, .lower)); 342 const branch_backed = initial.event.source_branch != null; 343 var fork_repo_maybe: ?Repo = if (branch_backed) null else Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| blk: { 344 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 345 break :blk null; 346 }; 347 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 348 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 349 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 350 try target_repo.core.db_file.lock(io, .exclusive); 351 defer target_repo.core.db_file.unlock(io); 352 353 var target_moment = try target_repo.core.latestMoment(); 354 const target_state = Repo.State(.read_only){ .core = &target_repo.core, .extra = .{ .moment = &target_moment } }; 355 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, target_moment) catch |err| switch (err) { 356 error.NotFound => return, 357 else => return err, 358 }; 359 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, &arena, id)) orelse return; 360 if (patch_record.removed or patch_record.event.status.kind() != .open) return; 361 var newest: ?evt.PatchRev.WithId = null; 362 if (fork_repo_maybe) |*repo| { 363 if (evt.currentMoment(repo_opts, repo)) |events| { 364 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, &arena) catch |err| blk: { 365 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 366 break :blk null; 367 }; 368 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 369 } 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_events, &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 last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 425 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 426 _ = try last_object_id_cursor.readBytes(&last_object_id); 427 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 428 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 429 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 430 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 431 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, &ctx.id))); 432 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, ctx.check); 433 // discard the old repo-level cache as results are rebuilt here 434 _ = try moment.remove(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)); 435 } 436 }; 437 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 438 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Save{ .id = id.*, .check = check }); 439 } 440 441 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 { 442 const branch = patch.source_branch orelse return false; 443 const selected = patch.revision orelse return false; 444 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 445 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 446 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 447 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 448 return selected.matches(revision); 449 } 450 451 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 452 try evt.PatchRev.validateOid(hash_kind, oid); 453 var result: [hash.hexLen(hash_kind)]u8 = undefined; 454 @memcpy(&result, oid); 455 return result; 456 } 457 458 fn checkCommit( 459 comptime repo_opts: rp.RepoOpts(.xit), 460 state: rp.Repo(.xit, repo_opts).State(.read_write), 461 io: std.Io, 462 allocator: std.mem.Allocator, 463 oid: *const [hash.hexLen(repo_opts.hash)]u8, 464 target: rf.Ref, 465 ) Mergeability.Status { 466 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 467 .kind = .full, 468 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 469 .dry_run = true, 470 }, target, null) catch |err| { 471 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 472 return .unknown; 473 }; 474 defer result.deinit(); 475 return switch (result.result) { 476 .conflict => .conflict, 477 .clean, .success, .nothing, .fast_forward => .clean, 478 }; 479 } 480 481 pub const MergeInput = struct { 482 id: [evt.event_id_size * 2]u8, 483 revision: evt.Patch.MergeRevision, 484 author: evt.CommitAuthor, 485 timestamp: u64, 486 }; 487 488 pub fn publish( 489 comptime repo_opts: rp.RepoOpts(.xit), 490 io: std.Io, 491 allocator: std.mem.Allocator, 492 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 493 target_repo: *rp.Repo(.xit, repo_opts), 494 fork_path: []const u8, 495 input: PublishInput, 496 ) !void { 497 const patch_id = try evt.parseEventId(&input.id); 498 var arena = std.heap.ArenaAllocator.init(allocator); 499 defer arena.deinit(); 500 501 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 502 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 503 if (fork_record.removed or 504 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 505 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 506 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 507 if (user.removed or 508 !std.mem.eql(u8, user.event.name, input.author.name) or 509 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 510 511 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 512 defer fork_repo.deinit(io, allocator); 513 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 514 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 515 516 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 517 error.NotFound => null, 518 else => |other| return other, 519 }; 520 const existing = if (target_moment) |moment| 521 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 522 else 523 null; 524 if (existing) |record| { 525 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 526 } 527 if (local_patch.removed) { 528 if (existing == null) return error.PatchDataUnavailable; 529 } else { 530 var patch = (existing orelse local_patch).event; 531 if (local_patch.event.revision) |selected| { 532 const revision_id = try evt.parseEventId(&selected.id); 533 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 534 if (!selected.matches(revision)) return error.PatchNotPushed; 535 patch.revision = selected; 536 } 537 if (existing == null) patch.status = .open; 538 539 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 540 .id = input.id, 541 .timestamp = input.timestamp, 542 .author = input.author, 543 .event = .{ .patch = patch }, 544 }}); 545 546 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 547 .id = input.id, 548 .timestamp = input.timestamp, 549 .author = input.author, 550 .event = .{ .patch = null }, 551 }}); 552 } 553 554 if (fork_record.event.stage == .draft) { 555 var published = fork_record.event; 556 published.stage = .publish; 557 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 558 .id = input.id, 559 .timestamp = input.timestamp, 560 .author = input.author, 561 .event = .{ .fork = published }, 562 }}); 563 } 564 } 565 566 pub fn editDraft( 567 comptime repo_opts: rp.RepoOpts(.xit), 568 io: std.Io, 569 allocator: std.mem.Allocator, 570 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 571 fork_path: []const u8, 572 input: EditDraftInput, 573 ) !bool { 574 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 575 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 576 const patch_id = try evt.parseEventId(&input.id); 577 var arena = std.heap.ArenaAllocator.init(allocator); 578 defer arena.deinit(); 579 580 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 581 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 582 if (fork_record.event.stage != .draft) return false; 583 if (fork_record.removed or 584 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 585 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 586 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 587 if (user.removed or 588 !std.mem.eql(u8, user.event.name, input.author.name) or 589 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 590 591 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 592 defer fork_repo.deinit(io, allocator); 593 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 594 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 595 if (record.removed) return error.PatchDataUnavailable; 596 597 var patch = record.event; 598 patch.title = input.title; 599 patch.tags = input.tags; 600 patch.description = input.description; 601 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 602 patch.target_branch = input.target_branch; 603 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 604 .id = input.id, 605 .timestamp = input.timestamp, 606 .author = input.author, 607 .event = .{ .patch = patch }, 608 }}); 609 return true; 610 } 611 612 // merge the selected patch revision into its target branch 613 pub fn merge( 614 comptime repo_opts: rp.RepoOpts(.xit), 615 io: std.Io, 616 allocator: std.mem.Allocator, 617 repo_root_path: []const u8, 618 target_repo: *rp.Repo(.xit, repo_opts), 619 input: MergeInput, 620 ) !void { 621 const patch_id = try evt.parseEventId(&input.id); 622 errdefer |err| { 623 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 624 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 625 } 626 } 627 var arena = std.heap.ArenaAllocator.init(allocator); 628 defer arena.deinit(); 629 630 // validate the target patch 631 const target_moment = try evt.currentMoment(repo_opts, target_repo); 632 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 633 if (patch_record.removed) return error.InvalidPatch; 634 switch (patch_record.event.status) { 635 .open => {}, 636 .closed => return error.PatchClosed, 637 .merged => return error.PatchAlreadyMerged, 638 } 639 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 640 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 641 642 // open the fork 643 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 644 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; 645 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 646 // select the commit and merge identity 647 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 648 .squash => selected.squash_oid, 649 .source => selected.source_oid, 650 }) catch return error.InvalidPatch; 651 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 652 653 // merge the code and events in one target transaction 654 { 655 const DB = rp.Repo(.xit, repo_opts).DB; 656 const State = rp.Repo(.xit, repo_opts).State; 657 const Ctx = struct { 658 core: *rp.Repo(.xit, repo_opts).Core, 659 fork_repo: ?*rp.Repo(.xit, repo_opts), 660 io: std.Io, 661 allocator: std.mem.Allocator, 662 patch_id: [evt.event_id_size]u8, 663 expected_patch: evt.Patch, 664 target_ref: rf.Ref, 665 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 666 revision: evt.Patch.MergeRevision, 667 identity: []const u8, 668 author: evt.CommitAuthor, 669 timestamp: u64, 670 671 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 672 var moment = try DB.HashMap(.read_write).init(cursor.*); 673 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 674 675 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 676 defer check_arena.deinit(); 677 678 // require the fork's newest revision while both repos are locked 679 const selected_revision = ctx.expected_patch.revision orelse unreachable; 680 const revision_id = try evt.parseEventId(&selected_revision.id); 681 if (ctx.fork_repo) |repo| { 682 const fork_moment = try evt.currentMoment(repo_opts, repo); 683 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 684 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 685 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 686 687 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 688 switch (availability.get(ctx.revision)) { 689 .clean => {}, 690 .conflict => return error.MergeConflict, 691 .unknown => return error.MergeCheckUnavailable, 692 } 693 694 // copy the selected commit and its dependencies 695 if (ctx.fork_repo) |repo| { 696 var fork_repo_moment = try repo.core.latestMoment(); 697 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 698 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 699 defer objects.deinit(); 700 try objects.include(&ctx.selected_oid); 701 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 702 } 703 704 // merge the selected commit 705 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 706 { 707 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 708 .kind = .full, 709 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 710 .commit_metadata = .{ 711 .author = ctx.identity, 712 .committer = ctx.identity, 713 .message = ctx.expected_patch.title, 714 .timestamp = ctx.timestamp, 715 }, 716 }, ctx.target_ref, null); 717 defer merge_result.deinit(); 718 switch (merge_result.result) { 719 .conflict => return error.MergeConflict, 720 .success, .fast_forward, .nothing => {}, 721 .clean => unreachable, 722 } 723 } 724 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 725 726 // retain the submitted revision and snapshot the merge result 727 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; 728 729 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "merge patch" }); 730 } 731 }; 732 733 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 734 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 735 try target_repo.core.db_file.lock(io, .exclusive); 736 defer target_repo.core.db_file.unlock(io); 737 738 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 739 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 740 .core = &target_repo.core, 741 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 742 .io = io, 743 .allocator = allocator, 744 .patch_id = patch_id, 745 .expected_patch = patch_record.event, 746 .target_ref = target_ref, 747 .selected_oid = selected_oid, 748 .revision = input.revision, 749 .identity = identity, 750 .author = input.author, 751 .timestamp = input.timestamp, 752 }); 753 } 754 refreshMergeability(repo_opts, io, allocator, target_repo, null); 755 // the merge moved the target branch, so its file index follows 756 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 757 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 758 }; 759 } 760 761 // merge a published patch and remove its fork 762 pub fn mergeAndRemoveFork( 763 comptime repo_opts: rp.RepoOpts(.xit), 764 io: std.Io, 765 allocator: std.mem.Allocator, 766 repo_root_path: []const u8, 767 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 768 target_repo: *rp.Repo(.xit, repo_opts), 769 input: MergeInput, 770 ) !void { 771 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 772 var arena = std.heap.ArenaAllocator.init(allocator); 773 defer arena.deinit(); 774 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 775 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 776 } 777 778 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 779 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 780 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 781 const name = std.mem.trimEnd(u8, line[0..open], " "); 782 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 783 return .{ .name = name, .email = line[open + 1 .. close] }; 784 } 785 786 // import a revision after detecting a client-side merge 787 fn importMerged( 788 comptime repo_opts: rp.RepoOpts(.xit), 789 state: rp.Repo(.xit, repo_opts).State(.read_write), 790 db: *evt.EventDB(repo_opts.hash), 791 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 792 io: std.Io, 793 allocator: std.mem.Allocator, 794 repo_root_path: []const u8, 795 patch_id: *const [evt.event_id_size]u8, 796 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 797 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 798 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 799 ) !void { 800 var arena = std.heap.ArenaAllocator.init(allocator); 801 defer arena.deinit(); 802 803 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 804 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 805 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 806 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 807 const selected = record.event.revision orelse return; 808 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; 809 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 }); 810 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 811 812 _ = 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); 813 } 814 815 // import the revision and mark its patch merged in the current transaction 816 fn importMergedRevision( 817 comptime repo_opts: rp.RepoOpts(.xit), 818 state: rp.Repo(.xit, repo_opts).State(.read_write), 819 db: *evt.EventDB(repo_opts.hash), 820 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 821 io: std.Io, 822 allocator: std.mem.Allocator, 823 fork_repo: ?*rp.Repo(.xit, repo_opts), 824 patch_id: *const [evt.event_id_size]u8, 825 merged: struct { 826 revision: evt.Patch.MergeRevision, 827 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 828 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 829 }, 830 expected_patch: ?evt.Patch, 831 merged_author: ?evt.CommitAuthor, 832 merged_timestamp: u64, 833 ) !bool { 834 const DB = evt.EventDB(repo_opts.hash); 835 var arena = std.heap.ArenaAllocator.init(allocator); 836 defer arena.deinit(); 837 838 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 839 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 840 const selected = patch_record.event.revision orelse return false; 841 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 842 if (expected_patch) |expected| { 843 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 844 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 845 const conflicts = try DB.SortedMap(.read_only).init(cursor); 846 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 847 } 848 } 849 const revision_id = try evt.parseEventId(&selected.id); 850 851 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 852 const revision = (if (fork_repo) |repo| 853 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 854 else 855 current_revision) orelse return false; 856 if (!selected.matches(revision)) return false; 857 858 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 859 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 } }; 860 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 861 if (revision.event_oid.len != event_oid.len) return false; 862 @memcpy(&event_oid, revision.event_oid); 863 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 864 defer event_object.deinit(); 865 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 866 867 var events_buffer: [3]evt.EventWithId = undefined; 868 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 869 var tree_entries: [2]evt.EventTreeEntry = undefined; 870 const needs_import = if (current_revision) |existing| existing.removed else true; 871 if (needs_import) { 872 tree_entries = .{ 873 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 874 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 875 }; 876 events.appendAssumeCapacity(.{ 877 .id = selected.id, 878 .timestamp = event_object.content.commit.metadata.timestamp, 879 .author = original_author, 880 .tree_entries = &tree_entries, 881 .event = .{ .patchrev = revision.event }, 882 }); 883 } else { 884 const existing = current_revision orelse unreachable; 885 if (!selected.matches(existing)) return error.InvalidPatch; 886 } 887 888 const author = merged_author orelse original_author; 889 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 890 var patch = patch_record.event; 891 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 892 events.appendAssumeCapacity(result.event); 893 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 894 events.appendAssumeCapacity(.{ 895 .id = std.fmt.bytesToHex(patch_id.*, .lower), 896 .timestamp = timestamp, 897 .author = author, 898 .event = .{ .patch = patch }, 899 }); 900 901 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 902 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 903 return true; 904 } 905 906 // find patches merged by commits received in a push 907 pub fn detectMerged( 908 comptime repo_opts: rp.RepoOpts(.xit), 909 state: rp.Repo(.xit, repo_opts).State(.read_write), 910 db: *evt.EventDB(repo_opts.hash), 911 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 912 io: std.Io, 913 allocator: std.mem.Allocator, 914 repo_root_path: []const u8, 915 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 916 error_writer: *std.Io.Writer, 917 ) !void { 918 const DB = evt.EventDB(repo_opts.hash); 919 var arena = std.heap.ArenaAllocator.init(allocator); 920 defer arena.deinit(); 921 922 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 923 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 924 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 925 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 926 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 927 const heads_prefix = "refs/heads/"; 928 for (updates) |update| { 929 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 930 std.mem.eql(u8, update.ref_name, events_ref_path) or 931 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 932 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 933 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 934 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 935 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 936 @memcpy(&old_oid, update.old_oid); 937 @memcpy(&new_oid, update.new_oid); 938 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 939 940 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 941 defer commits.deinit(); 942 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 943 var targets: std.ArrayList(struct { 944 before_oid: [hash.hexLen(repo_opts.hash)]u8, 945 after_oid: [hash.hexLen(repo_opts.hash)]u8, 946 }) = .empty; 947 { 948 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 949 defer first_parents.deinit(); 950 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 951 try first_parents.include(&new_oid); 952 while (try first_parents.next(arena.allocator())) |commit| { 953 defer commit.deinit(); 954 try targets.append(arena.allocator(), .{ 955 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 956 .after_oid = commit.oid, 957 }); 958 } 959 } 960 961 // visit target commits oldest first, attributing each revision to the 962 // commit that introduced it; the shared iterator visits each ancestor once 963 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 964 while (targets.pop()) |target| { 965 try commits.include(&target.after_oid); 966 while (try commits.next(arena.allocator())) |commit| { 967 defer commit.deinit(); 968 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 969 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 970 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 971 var ids_iter = try ids.iterator(); 972 while (try ids_iter.next()) |cursor| { 973 const pair = try cursor.readKeyValuePair(); 974 var patch_id: [evt.event_id_size]u8 = undefined; 975 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 976 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 977 // a fast-forward has no recorded merge boundary; use the old ref tip 978 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 979 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 980 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 981 continue; 982 }; 983 } 984 } 985 } 986 } 987 } 988