╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
624 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 625 }; 626 } 627 628 fn saveMergeCheck(comptime repo_opts: rp.RepoOpts(.xit), moment: rp.Repo(.xit, repo_opts).DB.HashMap(.read_write), id: *const [evt.event_id_size]u8, check: MergeCheck) !void { 629 const DB = rp.Repo(.xit, repo_opts).DB; 630 631 // store the check under the current event history moment 632 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 633 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 634 _ = try last_object_id_cursor.readBytes(&last_object_id); 635 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 636 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 637 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 638 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 639 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 640 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 641 } 642 643 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 { 644 // check that the source branch still points to the selected commit 645 const branch = patch.source_branch orelse return false; 646 const selected = patch.revision orelse return false; 647 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 648 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 649 650 // verify that the stored revision metadata also matches 651 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 652 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 653 return selected.matches(revision); 654 } 655 656 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 657 try evt.PatchRev.validateOid(hash_kind, oid); 658 var result: [hash.hexLen(hash_kind)]u8 = undefined; 659 @memcpy(&result, oid); 660 return result; 661 } 662 663 fn checkCommit( 664 comptime repo_opts: rp.RepoOpts(.xit), 665 state: rp.Repo(.xit, repo_opts).State(.read_write), 666 io: std.Io, 667 allocator: std.mem.Allocator, 668 oid: *const [hash.hexLen(repo_opts.hash)]u8, 669 target: rf.Ref, 670 ) Mergeability.Status { 671 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 672 .kind = .full, 673 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 674 .dry_run = true, 675 }, target, null) catch |err| { 676 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 677 return .unknown; 678 }; 679 defer result.deinit(); 680 681 // translate the dry-run outcome into a cached status 682 return switch (result.result) { 683 .conflict => .conflict, 684 .clean, .success, .nothing, .fast_forward => .clean, 685 }; 686 } 687 688 pub const MergeInput = struct { 689 id: [evt.event_id_size * 2]u8, 690 revision: evt.Patch.MergeRevision, 691 author: evt.CommitAuthor, 692 timestamp: u64, 693 }; 694 695 pub fn publish( 696 comptime repo_opts: rp.RepoOpts(.xit), 697 io: std.Io, 698 allocator: std.mem.Allocator, 699 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 700 target_repo: *rp.Repo(.xit, repo_opts), 701 fork_path: []const u8, 702 input: PublishInput, 703 ) !void { 704 const patch_id = try evt.parseEventId(&input.id); 705 var arena = std.heap.ArenaAllocator.init(allocator); 706 defer arena.deinit(); 707 708 // validate the fork ownership and publishing identity 709 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 710 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 711 if (fork_record.removed or 712 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 713 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 714 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 715 if (user.removed or 716 !std.mem.eql(u8, user.event.name, input.author.name) or 717 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 718 719 // read the patch staged in the fork 720 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 721 defer fork_repo.deinit(io, allocator); 722 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 723 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 724 725 // check whether this patch has already been published 726 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 727 error.NotFound => null, 728 else => |other| return other, 729 }; 730 const existing = if (target_moment) |moment| 731 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 732 else 733 null; 734 if (existing) |record| { 735 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 736 } 737 738 // publish the selected revision unless the draft was already consumed 739 if (local_patch.removed) { 740 if (existing == null) return error.PatchDataUnavailable; 741 } else { 742 var patch = (existing orelse local_patch).event; 743 if (local_patch.event.revision) |selected| { 744 const revision_id = try evt.parseEventId(&selected.id); 745 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 746 if (!selected.matches(revision)) return error.PatchNotPushed; 747 patch.revision = selected; 748 } 749 if (existing == null) patch.status = .open; 750 751 // write the published patch to the target repository 752 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 753 .id = input.id, 754 .timestamp = input.timestamp, 755 .author = input.author, 756 .event = .{ .patch = patch }, 757 }}); 758 759 // remove the consumed draft from the fork 760 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 761 .id = input.id, 762 .timestamp = input.timestamp, 763 .author = input.author, 764 .event = .{ .patch = null }, 765 }}); 766 } 767 768 // mark the fork as published in the administration repository 769 if (fork_record.event.stage == .draft) { 770 var published = fork_record.event; 771 published.stage = .publish; 772 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 773 .id = input.id, 774 .timestamp = input.timestamp, 775 .author = input.author, 776 .event = .{ .fork = published }, 777 }}); 778 } 779 } 780 781 pub fn editDraft( 782 comptime repo_opts: rp.RepoOpts(.xit), 783 io: std.Io, 784 allocator: std.mem.Allocator, 785 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 786 fork_path: []const u8, 787 input: EditDraftInput, 788 ) !bool { 789 // validate the submitted fields before opening repositories 790 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 791 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 792 const patch_id = try evt.parseEventId(&input.id); 793 var arena = std.heap.ArenaAllocator.init(allocator); 794 defer arena.deinit(); 795 796 // validate the draft ownership and editing identity 797 { 798 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 799 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 800 if (fork_record.event.stage != .draft) return false; 801 if (fork_record.removed or 802 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 803 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 804 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 805 if (user.removed or 806 !std.mem.eql(u8, user.event.name, input.author.name) or 807 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 808 } 809 810 // read the draft patch from its fork 811 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 812 defer fork_repo.deinit(io, allocator); 813 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 814 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 815 if (record.removed) return error.PatchDataUnavailable; 816 817 // apply the edits and invalidate a revision targeting another branch 818 var patch = record.event; 819 patch.title = input.title; 820 patch.tags = input.tags; 821 patch.description = input.description; 822 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 823 patch.target_branch = input.target_branch; 824 825 // commit the updated draft metadata 826 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 827 .id = input.id, 828 .timestamp = input.timestamp, 829 .author = input.author, 830 .event = .{ .patch = patch }, 831 }}); 832 return true; 833 } 834 835 // merge the selected patch revision into its target branch 836 pub fn merge( 837 comptime repo_opts: rp.RepoOpts(.xit), 838 io: std.Io, 839 allocator: std.mem.Allocator, 840 repo_root_path: []const u8, 841 target_repo: *rp.Repo(.xit, repo_opts), 842 input: MergeInput, 843 ) !void { 844 const patch_id = try evt.parseEventId(&input.id); 845 errdefer |err| { 846 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 847 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 848 } 849 } 850 var arena = std.heap.ArenaAllocator.init(allocator); 851 defer arena.deinit(); 852 853 // validate the target patch 854 const target_moment = try evt.currentMoment(repo_opts, target_repo); 855 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 856 if (patch_record.removed) return error.InvalidPatch; 857 switch (patch_record.event.status) { 858 .open => {}, 859 .closed => return error.PatchClosed, 860 .merged => return error.PatchAlreadyMerged, 861 } 862 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 863 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 864 865 // open the fork 866 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 867 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; 868 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 869 870 // select the commit and merge identity 871 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 872 .squash => selected.squash_oid, 873 .source => selected.source_oid, 874 }) catch return error.InvalidPatch; 875 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 876 877 // merge the code and events in one target transaction 878 { 879 const DB = rp.Repo(.xit, repo_opts).DB; 880 const State = rp.Repo(.xit, repo_opts).State; 881 const Ctx = struct { 882 core: *rp.Repo(.xit, repo_opts).Core, 883 fork_repo: ?*rp.Repo(.xit, repo_opts), 884 io: std.Io, 885 allocator: std.mem.Allocator, 886 patch_id: [evt.event_id_size]u8, 887 expected_patch: evt.Patch, 888 target_ref: rf.Ref, 889 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 890 revision: evt.Patch.MergeRevision, 891 identity: []const u8, 892 author: evt.CommitAuthor, 893 timestamp: u64, 894 895 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 896 var moment = try DB.HashMap(.read_write).init(cursor.*); 897 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 898 899 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 900 defer check_arena.deinit(); 901 902 // require the fork's newest revision while both repos are locked 903 const selected_revision = ctx.expected_patch.revision orelse unreachable; 904 const revision_id = try evt.parseEventId(&selected_revision.id); 905 if (ctx.fork_repo) |repo| { 906 const fork_moment = try evt.currentMoment(repo_opts, repo); 907 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 908 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 909 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 910 911 // require a clean cached result for the selected merge style. 912 { 913 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 914 switch (availability.get(ctx.revision)) { 915 .clean => {}, 916 .conflict => return error.MergeConflict, 917 .unknown => return error.MergeCheckUnavailable, 918 } 919 } 920 921 // copy the selected commit and its dependencies 922 if (ctx.fork_repo) |repo| { 923 var fork_repo_moment = try repo.core.latestMoment(); 924 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 925 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 926 defer objects.deinit(); 927 try objects.include(&ctx.selected_oid); 928 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 929 } 930 931 // merge the selected commit 932 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 933 { 934 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 935 .kind = .full, 936 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 937 .commit_metadata = .{ 938 .author = ctx.identity, 939 .committer = ctx.identity, 940 .message = ctx.expected_patch.title, 941 .timestamp = ctx.timestamp, 942 }, 943 }, ctx.target_ref, null); 944 defer merge_result.deinit(); 945 switch (merge_result.result) { 946 .conflict => return error.MergeConflict, 947 .success, .fast_forward, .nothing => {}, 948 .clean => unreachable, 949 } 950 } 951 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 952 953 // retain the submitted revision and snapshot the merge result 954 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; 955 956 // record the merge as one undoable action. 957 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = merge_undo_action } }); 958 } 959 }; 960 961 // lock the fork before the target for the full merge transaction. 962 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 963 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 964 try target_repo.core.db_file.lock(io, .exclusive); 965 defer target_repo.core.db_file.unlock(io); 966 967 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 968 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 969 .core = &target_repo.core, 970 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 971 .io = io, 972 .allocator = allocator, 973 .patch_id = patch_id, 974 .expected_patch = patch_record.event, 975 .target_ref = target_ref, 976 .selected_oid = selected_oid, 977 .revision = input.revision, 978 .identity = identity, 979 .author = input.author, 980 .timestamp = input.timestamp, 981 }); 982 } 983 984 // refresh other patches affected by the updated target branch. 985 refreshMergeability(repo_opts, io, allocator, target_repo, null); 986 987 // the merge moved the target branch, so its indexes follow 988 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 989 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 990 }; 991 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 992 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 993 }; 994 } 995 996 // merge a published patch and remove its fork 997 pub fn mergeAndRemoveFork( 998 comptime repo_opts: rp.RepoOpts(.xit), 999 io: std.Io, 1000 allocator: std.mem.Allocator, 1001 repo_root_path: []const u8, 1002 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1003 target_repo: *rp.Repo(.xit, repo_opts), 1004 input: MergeInput, 1005 ) !void { 1006 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1007 var arena = std.heap.ArenaAllocator.init(allocator); 1008 defer arena.deinit(); 1009 1010 // remove fork data only for patches backed by a fork. 1011 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1012 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1013 } 1014 1015 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1016 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1017 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1018 const name = std.mem.trimEnd(u8, line[0..open], " "); 1019 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1020 return .{ .name = name, .email = line[open + 1 .. close] }; 1021 } 1022 1023 // import a revision after detecting a client-side merge 1024 fn importMerged( 1025 comptime repo_opts: rp.RepoOpts(.xit), 1026 state: rp.Repo(.xit, repo_opts).State(.read_write), 1027 db: *evt.EventDB(repo_opts.hash), 1028 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1029 io: std.Io, 1030 allocator: std.mem.Allocator, 1031 repo_root_path: []const u8, 1032 patch_id: *const [evt.event_id_size]u8, 1033 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1034 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1035 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1036 ) !void { 1037 var arena = std.heap.ArenaAllocator.init(allocator); 1038 defer arena.deinit(); 1039 1040 // identify which selected revision was merged by the client. 1041 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1042 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1043 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1044 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1045 const selected = record.event.revision orelse return; 1046 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; 1047 1048 // open the fork when the revision is not stored in the target repository. 1049 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 }); 1050 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1051 1052 // import the revision and record the client-side merge. 1053 _ = 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); 1054 } 1055 1056 // import the revision and mark its patch merged in the current transaction 1057 fn importMergedRevision( 1058 comptime repo_opts: rp.RepoOpts(.xit), 1059 state: rp.Repo(.xit, repo_opts).State(.read_write), 1060 db: *evt.EventDB(repo_opts.hash), 1061 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1062 io: std.Io, 1063 allocator: std.mem.Allocator, 1064 fork_repo: ?*rp.Repo(.xit, repo_opts), 1065 patch_id: *const [evt.event_id_size]u8, 1066 merged: struct { 1067 revision: evt.Patch.MergeRevision, 1068 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1069 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1070 }, 1071 expected_patch: ?evt.Patch, 1072 merged_author: ?evt.CommitAuthor, 1073 merged_timestamp: u64, 1074 ) !bool { 1075 const DB = evt.EventDB(repo_opts.hash); 1076 var arena = std.heap.ArenaAllocator.init(allocator); 1077 defer arena.deinit(); 1078 1079 // read the patch and reject outdated or conflicting merge requests. 1080 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1081 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1082 const selected = patch_record.event.revision orelse return false; 1083 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1084 if (expected_patch) |expected| { 1085 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1086 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1087 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1088 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1089 } 1090 } 1091 const revision_id = try evt.parseEventId(&selected.id); 1092 1093 // resolve the selected revision from the target or its fork. 1094 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1095 const revision = (if (fork_repo) |repo| 1096 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1097 else 1098 current_revision) orelse return false; 1099 if (!selected.matches(revision)) return false; 1100 1101 // read the original revision commit and author. 1102 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1103 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 } }; 1104 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1105 if (revision.event_oid.len != event_oid.len) return false; 1106 @memcpy(&event_oid, revision.event_oid); 1107 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1108 defer event_object.deinit(); 1109 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1110 1111 // retain the submitted revision if the target has not imported it yet. 1112 var events_buffer: [3]evt.EventWithId = undefined; 1113 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1114 var tree_entries: [2]evt.EventTreeEntry = undefined; 1115 const needs_import = if (current_revision) |existing| existing.removed else true; 1116 if (needs_import) { 1117 tree_entries = .{ 1118 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1119 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1120 }; 1121 events.appendAssumeCapacity(.{ 1122 .id = selected.id, 1123 .timestamp = event_object.content.commit.metadata.timestamp, 1124 .author = original_author, 1125 .tree_entries = &tree_entries, 1126 .event = .{ .patchrev = revision.event }, 1127 }); 1128 } else { 1129 const existing = current_revision orelse unreachable; 1130 if (!selected.matches(existing)) return error.InvalidPatch; 1131 } 1132 1133 // snapshot the merge result and mark the patch as merged. 1134 { 1135 const author = merged_author orelse original_author; 1136 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1137 var patch = patch_record.event; 1138 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1139 events.appendAssumeCapacity(result.event); 1140 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1141 events.appendAssumeCapacity(.{ 1142 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1143 .timestamp = timestamp, 1144 .author = author, 1145 .event = .{ .patch = patch }, 1146 }); 1147 } 1148 1149 // commit and consume the revision and patch events together. 1150 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1151 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1152 return true; 1153 } 1154 1155 // find patches merged by commits received in a push 1156 pub fn detectMerged( 1157 comptime repo_opts: rp.RepoOpts(.xit), 1158 state: rp.Repo(.xit, repo_opts).State(.read_write), 1159 db: *evt.EventDB(repo_opts.hash), 1160 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1161 io: std.Io, 1162 allocator: std.mem.Allocator, 1163 repo_root_path: []const u8, 1164 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1165 error_writer: *std.Io.Writer, 1166 ) !void { 1167 const DB = evt.EventDB(repo_opts.hash); 1168 var arena = std.heap.ArenaAllocator.init(allocator); 1169 defer arena.deinit(); 1170 1171 // read the revision index used to identify merged patches. 1172 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1173 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1174 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1175 1176 // ignore event refs and inspect only changed branch tips. 1177 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1178 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1179 const heads_prefix = "refs/heads/"; 1180 for (updates) |update| { 1181 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1182 std.mem.eql(u8, update.ref_name, events_ref_path) or 1183 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1184 1185 // validate the ref tips and skip branch deletions. 1186 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1187 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1188 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1189 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1190 @memcpy(&old_oid, update.old_oid); 1191 @memcpy(&new_oid, update.new_oid); 1192 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1193 1194 // traverse commits introduced by this branch update. 1195 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1196 defer commits.deinit(); 1197 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1198 var targets: std.ArrayList(struct { 1199 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1200 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1201 }) = .empty; 1202 1203 // collect merge boundaries along the target's first-parent history. 1204 { 1205 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1206 defer first_parents.deinit(); 1207 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1208 try first_parents.include(&new_oid); 1209 while (try first_parents.next(arena.allocator())) |commit| { 1210 defer commit.deinit(); 1211 try targets.append(arena.allocator(), .{ 1212 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1213 .after_oid = commit.oid, 1214 }); 1215 } 1216 } 1217 1218 // visit target commits oldest first, attributing each revision to the 1219 // commit that introduced it; the shared iterator visits each ancestor once 1220 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1221 while (targets.pop()) |target| { 1222 try commits.include(&target.after_oid); 1223 while (try commits.next(arena.allocator())) |commit| { 1224 defer commit.deinit(); 1225 1226 // find patches whose selected revision matches this commit. 1227 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1228 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1229 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1230 var ids_iter = try ids.iterator(); 1231 while (try ids_iter.next()) |cursor| { 1232 const pair = try cursor.readKeyValuePair(); 1233 var patch_id: [evt.event_id_size]u8 = undefined; 1234 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1235 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1236 1237 // a fast-forward has no recorded merge boundary; use the old ref tip 1238 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1239 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1240 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1241 continue; 1242 }; 1243 } 1244 } 1245 } 1246 } 1247 } 1248