╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const evt = @import("event.zig"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const hash = xit.hash; 6 const obj = xit.object; 7 const rf = xit.ref; 8 const mrg = xit.merge; 9 const fork = @import("fork.zig"); 10 const serve_common = @import("serve_common.zig"); 11 12 pub const PublishInput = struct { 13 id: [evt.event_id_size * 2]u8, 14 user_id: [evt.event_id_size]u8, 15 repo_id: [evt.event_id_size]u8, 16 author: evt.CommitAuthor, 17 timestamp: u64, 18 }; 19 20 pub const EditDraftInput = struct { 21 id: [evt.event_id_size * 2]u8, 22 user_id: [evt.event_id_size]u8, 23 repo_id: [evt.event_id_size]u8, 24 title: []const u8, 25 tags: []const u8, 26 description: []const u8, 27 target_branch: []const u8, 28 author: evt.CommitAuthor, 29 timestamp: u64, 30 }; 31 32 pub const MergeRevision = enum { squash, source }; 33 34 pub const Mergeability = struct { 35 pub const Status = enum { clean, conflict, unknown }; 36 37 source: Status = .unknown, 38 squash: Status = .unknown, 39 40 pub fn get(self: Mergeability, revision: MergeRevision) Status { 41 return switch (revision) { 42 .source => self.source, 43 .squash => self.squash, 44 }; 45 } 46 47 pub fn status(self: Mergeability) Status { 48 if (self.source == .clean or self.squash == .clean) return .clean; 49 if (self.source == .conflict and self.squash == .conflict) return .conflict; 50 return .unknown; 51 } 52 }; 53 54 const mergeability_key = "patch-id->mergeability"; 55 56 const MergeCheck = struct { 57 revision: evt.Patch.Revision, 58 target_branch: []const u8, 59 target_oid: []const u8, 60 result: Mergeability = .{}, 61 62 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 63 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 64 std.mem.eql(u8, self.target_branch, patch.target_branch) and 65 std.mem.eql(u8, self.target_oid, target_oid); 66 } 67 }; 68 69 fn readMergeCheck( 70 comptime repo_opts: rp.RepoOpts(.xit), 71 moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 72 arena: *std.heap.ArenaAllocator, 73 id: *const [evt.event_id_size]u8, 74 ) !?MergeCheck { 75 const DB = evt.EventDB(repo_opts.hash); 76 const map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, mergeability_key)) orelse return null; 77 const map = try DB.HashMap(.read_only).init(map_cursor); 78 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 79 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 80 error.InvalidEnumTag => return null, 81 else => return err, 82 }; 83 } 84 85 // reads never run a merge or refresh the cache 86 pub fn readMergeability( 87 comptime repo_opts: rp.RepoOpts(.xit), 88 state: rp.Repo(.xit, repo_opts).State(.read_only), 89 io: std.Io, 90 arena: *std.heap.ArenaAllocator, 91 id: *const [evt.event_id_size]u8, 92 patch: evt.Patch, 93 ) !Mergeability { 94 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 95 const cached = try readMergeCheck(repo_opts, state.extra.moment.*, arena, id) orelse return .{}; 96 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 97 } 98 99 // refresh after the caller's transaction and locks have finished. a check 100 // failure must not turn an accepted push or event into a failed operation. 101 pub fn refreshMergeability( 102 comptime repo_opts: rp.RepoOpts(.xit), 103 io: std.Io, 104 allocator: std.mem.Allocator, 105 target_repo: *rp.Repo(.xit, repo_opts), 106 id_maybe: ?[evt.event_id_size]u8, 107 ) void { 108 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 109 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 110 }; 111 } 112 113 fn refreshMergeChecks( 114 comptime repo_opts: rp.RepoOpts(.xit), 115 io: std.Io, 116 allocator: std.mem.Allocator, 117 target_repo: *rp.Repo(.xit, repo_opts), 118 id_maybe: ?[evt.event_id_size]u8, 119 ) !void { 120 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 121 const DB = evt.EventDB(repo_opts.hash); 122 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 123 error.NotFound => return, 124 else => return err, 125 }; 126 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 127 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 128 const open_cursor = try statuses.getCursor("open") orelse return; 129 const open = try DB.SortedSet(.read_only).init(open_cursor); 130 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 131 defer ids.deinit(allocator); 132 var iter = try open.iteratorFromIndex(0); 133 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 134 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 135 } 136 137 fn refreshMergeCheck( 138 comptime repo_opts: rp.RepoOpts(.xit), 139 io: std.Io, 140 allocator: std.mem.Allocator, 141 target_repo: *rp.Repo(.xit, repo_opts), 142 id: *const [evt.event_id_size]u8, 143 ) !void { 144 const Repo = rp.Repo(.xit, repo_opts); 145 const DB = Repo.DB; 146 var arena = std.heap.ArenaAllocator.init(allocator); 147 defer arena.deinit(); 148 const repo_root_path = std.fs.path.dirname(target_repo.core.work_path) orelse "."; 149 const path = try fork.forkPath(arena.allocator(), repo_root_path, &std.fmt.bytesToHex(id.*, .lower)); 150 var fork_repo_maybe: ?Repo = Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| blk: { 151 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 152 break :blk null; 153 }; 154 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 155 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 156 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 157 try target_repo.core.db_file.lock(io, .exclusive); 158 defer target_repo.core.db_file.unlock(io); 159 160 var target_moment = try target_repo.core.latestMoment(); 161 const target_state = Repo.State(.read_only){ .core = &target_repo.core, .extra = .{ .moment = &target_moment } }; 162 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, target_moment) catch |err| switch (err) { 163 error.NotFound => null, 164 else => return err, 165 }; 166 var record = if (target_events) |events| try evt.Patch.readById(DB, repo_opts.hash, events, &arena, id) else null; 167 var newest: ?evt.PatchRev.WithId = null; 168 if (fork_repo_maybe) |*repo| { 169 if (evt.currentMoment(repo_opts, repo)) |events| { 170 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, &arena) catch |err| blk: { 171 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 172 break :blk null; 173 }; 174 if (record == null) record = try evt.Patch.readById(DB, repo_opts.hash, events, &arena, id); 175 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 176 } 177 const patch_record = record orelse return; 178 if (patch_record.removed or patch_record.event.status.kind() != .open) return; 179 const patch = patch_record.event; 180 const revision = patch.revision orelse return; 181 const target_oid = try rf.readRecur(.xit, repo_opts, target_state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 182 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 183 const cached = try readMergeCheck(repo_opts, target_moment, &arena, id); 184 const current = if (newest) |latest| std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) else false; 185 if (current and target_oid != null) { 186 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return; 187 const Ctx = struct { 188 repo: *Repo, 189 fork_repo: *Repo, 190 io: std.Io, 191 allocator: std.mem.Allocator, 192 check: *MergeCheck, 193 194 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 195 var moment = try DB.HashMap(.read_write).init(cursor.*); 196 const state = Repo.State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 197 var fork_moment = try ctx.fork_repo.core.latestMoment(); 198 const fork_state = Repo.State(.read_only){ .core = &ctx.fork_repo.core, .extra = .{ .moment = &fork_moment } }; 199 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 200 defer objects.deinit(); 201 const source = try oidArray(repo_opts.hash, ctx.check.revision.source_oid); 202 const squash = try oidArray(repo_opts.hash, ctx.check.revision.squash_oid); 203 try objects.include(&source); 204 try objects.include(&squash); 205 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 206 const target = rf.Ref{ .kind = .head, .name = ctx.check.target_branch }; 207 ctx.check.result.source = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &source, target); 208 ctx.check.result.squash = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &squash, target); 209 return error.CancelTransaction; 210 } 211 }; 212 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 213 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 214 .repo = target_repo, 215 .fork_repo = &fork_repo_maybe.?, 216 .io = io, 217 .allocator = allocator, 218 .check = &check, 219 }) catch |err| switch (err) { 220 error.CancelTransaction => {}, 221 else => std.log.warn("mergeability check failed: {s}", .{@errorName(err)}), 222 }; 223 } 224 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return; 225 const Save = struct { 226 id: [evt.event_id_size]u8, 227 check: MergeCheck, 228 229 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 230 const moment = try DB.HashMap(.read_write).init(cursor.*); 231 const map = try DB.HashMap(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, mergeability_key))); 232 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, &ctx.id))); 233 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, ctx.check); 234 } 235 }; 236 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 237 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Save{ .id = id.*, .check = check }); 238 } 239 240 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 241 try evt.PatchRev.validateOid(hash_kind, oid); 242 var result: [hash.hexLen(hash_kind)]u8 = undefined; 243 @memcpy(&result, oid); 244 return result; 245 } 246 247 fn checkCommit( 248 comptime repo_opts: rp.RepoOpts(.xit), 249 state: rp.Repo(.xit, repo_opts).State(.read_write), 250 io: std.Io, 251 allocator: std.mem.Allocator, 252 oid: *const [hash.hexLen(repo_opts.hash)]u8, 253 target: rf.Ref, 254 ) Mergeability.Status { 255 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 256 .kind = .full, 257 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 258 .dry_run = true, 259 }, target, null) catch |err| { 260 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 261 return .unknown; 262 }; 263 defer result.deinit(); 264 return switch (result.result) { 265 .conflict => .conflict, 266 .clean, .success, .nothing, .fast_forward => .clean, 267 }; 268 } 269 270 pub const MergeInput = struct { 271 id: [evt.event_id_size * 2]u8, 272 revision: MergeRevision, 273 author: evt.CommitAuthor, 274 timestamp: u64, 275 }; 276 277 pub fn publish( 278 comptime repo_opts: rp.RepoOpts(.xit), 279 io: std.Io, 280 allocator: std.mem.Allocator, 281 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 282 target_repo: *rp.Repo(.xit, repo_opts), 283 fork_path: []const u8, 284 input: PublishInput, 285 ) !void { 286 const patch_id = try evt.parseEventId(&input.id); 287 var arena = std.heap.ArenaAllocator.init(allocator); 288 defer arena.deinit(); 289 290 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 291 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 292 if (fork_record.removed or 293 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 294 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 295 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 296 if (user.removed or 297 !std.mem.eql(u8, user.event.name, input.author.name) or 298 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 299 300 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 301 defer fork_repo.deinit(io, allocator); 302 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 303 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 304 305 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 306 error.NotFound => null, 307 else => |other| return other, 308 }; 309 const existing = if (target_moment) |moment| 310 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 311 else 312 null; 313 if (existing) |record| { 314 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 315 } 316 if (local_patch.removed) { 317 if (existing == null) return error.PatchDataUnavailable; 318 } else { 319 var patch = (existing orelse local_patch).event; 320 if (local_patch.event.revision) |selected| { 321 const revision_id = try evt.parseEventId(&selected.id); 322 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 323 if (!selected.matches(revision)) return error.PatchNotPushed; 324 patch.revision = selected; 325 } 326 if (existing == null) patch.status = .open; 327 328 try evt.consume(.repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 329 .id = input.id, 330 .timestamp = input.timestamp, 331 .author = input.author, 332 .event = .{ .patch = patch }, 333 }}); 334 335 try evt.consume(.fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 336 .id = input.id, 337 .timestamp = input.timestamp, 338 .author = input.author, 339 .event = .{ .patch = null }, 340 }}); 341 } 342 343 if (fork_record.event.stage == .draft) { 344 var published = fork_record.event; 345 published.stage = .publish; 346 try evt.consume(.admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 347 .id = input.id, 348 .timestamp = input.timestamp, 349 .author = input.author, 350 .event = .{ .fork = published }, 351 }}); 352 } 353 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 354 } 355 356 pub fn editDraft( 357 comptime repo_opts: rp.RepoOpts(.xit), 358 io: std.Io, 359 allocator: std.mem.Allocator, 360 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 361 fork_path: []const u8, 362 input: EditDraftInput, 363 ) !bool { 364 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 365 const patch_id = try evt.parseEventId(&input.id); 366 var arena = std.heap.ArenaAllocator.init(allocator); 367 defer arena.deinit(); 368 369 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 370 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 371 if (fork_record.event.stage != .draft) return false; 372 if (fork_record.removed or 373 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 374 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 375 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 376 if (user.removed or 377 !std.mem.eql(u8, user.event.name, input.author.name) or 378 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 379 380 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 381 defer fork_repo.deinit(io, allocator); 382 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 383 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 384 if (record.removed) return error.PatchDataUnavailable; 385 386 var patch = record.event; 387 patch.title = input.title; 388 patch.tags = input.tags; 389 patch.description = input.description; 390 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 391 patch.target_branch = input.target_branch; 392 try evt.consume(.fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 393 .id = input.id, 394 .timestamp = input.timestamp, 395 .author = input.author, 396 .event = .{ .patch = patch }, 397 }}); 398 return true; 399 } 400 401 // merge the selected patch revision into its target branch 402 pub fn merge( 403 comptime repo_opts: rp.RepoOpts(.xit), 404 io: std.Io, 405 allocator: std.mem.Allocator, 406 repo_root_path: []const u8, 407 target_repo: *rp.Repo(.xit, repo_opts), 408 input: MergeInput, 409 ) !void { 410 const patch_id = try evt.parseEventId(&input.id); 411 var arena = std.heap.ArenaAllocator.init(allocator); 412 defer arena.deinit(); 413 414 // validate the target patch 415 const target_moment = try evt.currentMoment(repo_opts, target_repo); 416 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 417 if (patch_record.removed) return error.InvalidPatch; 418 switch (patch_record.event.status) { 419 .open => {}, 420 .closed => return error.PatchClosed, 421 .merged => return error.PatchAlreadyMerged, 422 } 423 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 424 const revision_id = try evt.parseEventId(&selected.id); 425 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 426 427 // open and lock the fork 428 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 429 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 430 defer fork_repo.deinit(io, allocator); 431 try fork_repo.core.db_file.lock(io, .shared); 432 defer fork_repo.core.db_file.unlock(io); 433 434 // require the fork's newest revision 435 { 436 const fork_moment = try evt.currentMoment(repo_opts, &fork_repo); 437 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena)) orelse return error.PatchDataUnavailable; 438 if (!std.mem.eql(u8, &newest.id, &revision_id) or 439 !selected.matches(newest.record)) return error.PatchOutOfDate; 440 } 441 442 // select the commit and merge identity 443 const merge_oid = oidArray(repo_opts.hash, switch (input.revision) { 444 .squash => selected.squash_oid, 445 .source => selected.source_oid, 446 }) catch return error.InvalidPatch; 447 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 448 449 // merge the code and events in one target transaction 450 { 451 const DB = rp.Repo(.xit, repo_opts).DB; 452 const State = rp.Repo(.xit, repo_opts).State; 453 const Ctx = struct { 454 core: *rp.Repo(.xit, repo_opts).Core, 455 fork_repo: *rp.Repo(.xit, repo_opts), 456 io: std.Io, 457 allocator: std.mem.Allocator, 458 patch_id: [evt.event_id_size]u8, 459 expected_patch: evt.Patch, 460 target_ref: rf.Ref, 461 merge_oid: [hash.hexLen(repo_opts.hash)]u8, 462 revision: MergeRevision, 463 identity: []const u8, 464 author: evt.CommitAuthor, 465 timestamp: u64, 466 467 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 468 var moment = try DB.HashMap(.read_write).init(cursor.*); 469 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 470 471 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 472 defer check_arena.deinit(); 473 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 474 switch (availability.get(ctx.revision)) { 475 .clean => {}, 476 .conflict => return error.MergeConflict, 477 .unknown => return error.MergeCheckUnavailable, 478 } 479 480 // copy the selected commit and its dependencies 481 { 482 var fork_repo_moment = try ctx.fork_repo.core.latestMoment(); 483 const fork_state = State(.read_only){ .core = &ctx.fork_repo.core, .extra = .{ .moment = &fork_repo_moment } }; 484 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 485 defer objects.deinit(); 486 try objects.include(&ctx.merge_oid); 487 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 488 } 489 490 // import the revision and mark the patch merged 491 if (!try importMergedFromFork(repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.fork_repo, &ctx.patch_id, &ctx.merge_oid, ctx.expected_patch, ctx.author, ctx.timestamp)) return error.PatchOutOfDate; 492 493 // merge the selected commit 494 { 495 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 496 .kind = .full, 497 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.merge_oid }}, .algo = .patch } }, 498 .commit_metadata = .{ 499 .author = ctx.identity, 500 .committer = ctx.identity, 501 .message = ctx.expected_patch.title, 502 .timestamp = ctx.timestamp, 503 }, 504 }, ctx.target_ref, null); 505 defer merge_result.deinit(); 506 switch (merge_result.result) { 507 .conflict => return error.MergeConflict, 508 .success, .nothing, .fast_forward => {}, 509 .clean => unreachable, 510 } 511 } 512 513 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "merge patch" }); 514 } 515 }; 516 517 try target_repo.core.db_file.lock(io, .exclusive); 518 defer target_repo.core.db_file.unlock(io); 519 520 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 521 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 522 .core = &target_repo.core, 523 .fork_repo = &fork_repo, 524 .io = io, 525 .allocator = allocator, 526 .patch_id = patch_id, 527 .expected_patch = patch_record.event, 528 .target_ref = target_ref, 529 .merge_oid = merge_oid, 530 .revision = input.revision, 531 .identity = identity, 532 .author = input.author, 533 .timestamp = input.timestamp, 534 }); 535 } 536 } 537 538 // merge a published patch and remove its fork 539 pub fn mergeAndRemoveFork( 540 comptime repo_opts: rp.RepoOpts(.xit), 541 io: std.Io, 542 allocator: std.mem.Allocator, 543 repo_root_path: []const u8, 544 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 545 target_repo: *rp.Repo(.xit, repo_opts), 546 input: MergeInput, 547 ) !void { 548 merge(repo_opts, io, allocator, repo_root_path, target_repo, input) catch |err| { 549 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 550 const id = evt.parseEventId(&input.id) catch return err; 551 refreshMergeability(repo_opts, io, allocator, target_repo, id); 552 } 553 return err; 554 }; 555 try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 556 refreshMergeability(repo_opts, io, allocator, target_repo, null); 557 } 558 559 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 560 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 561 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 562 const name = std.mem.trimEnd(u8, line[0..open], " "); 563 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 564 return .{ .name = name, .email = line[open + 1 .. close] }; 565 } 566 567 // import a revision after detecting a client-side merge 568 fn importMerged( 569 comptime repo_opts: rp.RepoOpts(.xit), 570 state: rp.Repo(.xit, repo_opts).State(.read_write), 571 db: *evt.EventDB(repo_opts.hash), 572 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 573 io: std.Io, 574 allocator: std.mem.Allocator, 575 repo_root_path: []const u8, 576 patch_id: *const [evt.event_id_size]u8, 577 merged_oid: *const [hash.hexLen(repo_opts.hash)]u8, 578 ) !void { 579 var arena = std.heap.ArenaAllocator.init(allocator); 580 defer arena.deinit(); 581 582 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 583 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 584 var fork_repo = try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 585 defer fork_repo.deinit(io, allocator); 586 587 _ = try importMergedFromFork(repo_opts, state, db, moment, io, allocator, &fork_repo, patch_id, merged_oid, null, null, 0); 588 } 589 590 // import the revision and mark its patch merged in the current transaction 591 fn importMergedFromFork( 592 comptime repo_opts: rp.RepoOpts(.xit), 593 state: rp.Repo(.xit, repo_opts).State(.read_write), 594 db: *evt.EventDB(repo_opts.hash), 595 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 596 io: std.Io, 597 allocator: std.mem.Allocator, 598 fork_repo: *rp.Repo(.xit, repo_opts), 599 patch_id: *const [evt.event_id_size]u8, 600 merged_oid: *const [hash.hexLen(repo_opts.hash)]u8, 601 expected_patch: ?evt.Patch, 602 merged_author: ?evt.CommitAuthor, 603 merged_timestamp: u64, 604 ) !bool { 605 const DB = evt.EventDB(repo_opts.hash); 606 var arena = std.heap.ArenaAllocator.init(allocator); 607 defer arena.deinit(); 608 609 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 610 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 611 const selected = patch_record.event.revision orelse return false; 612 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 613 if (expected_patch) |expected| { 614 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 615 } 616 const revision_id = try evt.parseEventId(&selected.id); 617 if (!selected.includesOid(merged_oid)) return false; 618 619 const fork_moment = try evt.currentMoment(repo_opts, fork_repo); 620 const revision = (try evt.PatchRev.readById(DB, repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return false; 621 if (!selected.matches(revision)) return false; 622 623 var fork_repo_moment = try fork_repo.core.latestMoment(); 624 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &fork_repo.core, .extra = .{ .moment = &fork_repo_moment } }; 625 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 626 if (revision.event_oid.len != event_oid.len) return false; 627 @memcpy(&event_oid, revision.event_oid); 628 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 629 defer event_object.deinit(); 630 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 631 632 var events: [2]evt.EventWithId = undefined; 633 var event_count: usize = 0; 634 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 635 var tree_entries: [2]evt.EventTreeEntry = undefined; 636 const needs_import = if (current_revision) |existing| existing.removed else true; 637 if (needs_import) { 638 tree_entries = .{ 639 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 640 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 641 }; 642 events[event_count] = .{ 643 .id = selected.id, 644 .timestamp = event_object.content.commit.metadata.timestamp, 645 .author = original_author, 646 .tree_entries = &tree_entries, 647 .event = .{ .patchrev = revision.event }, 648 }; 649 event_count += 1; 650 } else { 651 const existing = current_revision orelse unreachable; 652 if (!selected.matches(existing)) return error.InvalidPatch; 653 } 654 655 var patch = patch_record.event; 656 patch.status = .{ .merged = merged_oid }; 657 events[event_count] = .{ 658 .id = std.fmt.bytesToHex(patch_id.*, .lower), 659 .timestamp = if (merged_author != null) merged_timestamp else @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 660 .author = merged_author orelse original_author, 661 .event = .{ .patch = patch }, 662 }; 663 event_count += 1; 664 665 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events[0..event_count], null); 666 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 667 return true; 668 } 669 670 // find patches merged by commits received in a push 671 pub fn detectMerged( 672 comptime repo_opts: rp.RepoOpts(.xit), 673 state: rp.Repo(.xit, repo_opts).State(.read_write), 674 db: *evt.EventDB(repo_opts.hash), 675 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 676 io: std.Io, 677 allocator: std.mem.Allocator, 678 repo_root_path: []const u8, 679 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 680 error_writer: *std.Io.Writer, 681 ) !void { 682 const DB = evt.EventDB(repo_opts.hash); 683 var arena = std.heap.ArenaAllocator.init(allocator); 684 defer arena.deinit(); 685 686 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 687 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 688 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 689 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 690 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 691 const heads_prefix = "refs/heads/"; 692 for (updates) |update| { 693 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 694 std.mem.eql(u8, update.ref_name, events_ref_path) or 695 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 696 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 697 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 698 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 699 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 700 @memcpy(&old_oid, update.old_oid); 701 @memcpy(&new_oid, update.new_oid); 702 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 703 704 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 705 defer commits.deinit(); 706 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 707 try commits.include(&new_oid); 708 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 709 while (try commits.next(arena.allocator())) |commit| { 710 defer commit.deinit(); 711 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 712 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 713 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 714 var ids_iter = try ids.iterator(); 715 while (try ids_iter.next()) |cursor| { 716 const pair = try cursor.readKeyValuePair(); 717 var patch_id: [evt.event_id_size]u8 = undefined; 718 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 719 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 720 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid) catch |err| { 721 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 722 continue; 723 }; 724 } 725 } 726 } 727 } 728