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