╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
791 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 792 defer objects.deinit(); 793 try objects.include(&source); 794 try objects.include(&squash); 795 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 796 } 797 798 // check source and squash merges against the same target 799 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 800 return .{ 801 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 802 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 803 }; 804 } 805 806 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 { 807 const DB = rp.Repo(.xit, repo_opts).DB; 808 809 // store the check under the current event history moment 810 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 811 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 812 _ = try last_object_id_cursor.readBytes(&last_object_id); 813 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 814 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 815 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 816 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 817 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 818 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 819 } 820 821 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 { 822 // check that the source branch still points to the selected commit 823 const branch = patch.source_branch orelse return false; 824 const selected = patch.revision orelse return false; 825 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 826 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 827 828 // verify that the stored revision metadata also matches 829 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 830 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 831 return selected.matches(revision); 832 } 833 834 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 835 try evt.PatchRev.validateOid(hash_kind, oid); 836 var result: [hash.hexLen(hash_kind)]u8 = undefined; 837 @memcpy(&result, oid); 838 return result; 839 } 840 841 fn checkCommit( 842 comptime repo_opts: rp.RepoOpts(.xit), 843 state: rp.Repo(.xit, repo_opts).State(.read_write), 844 io: std.Io, 845 allocator: std.mem.Allocator, 846 oid: *const [hash.hexLen(repo_opts.hash)]u8, 847 target: rf.Ref, 848 ) Mergeability.Status { 849 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 850 .kind = .full, 851 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 852 .dry_run = true, 853 }, target, null) catch |err| { 854 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 855 return .unknown; 856 }; 857 defer result.deinit(); 858 859 // translate the dry-run outcome into a cached status 860 return switch (result.result) { 861 .conflict => .conflict, 862 .clean, .success, .nothing, .fast_forward => .clean, 863 }; 864 } 865 866 pub const MergeInput = struct { 867 id: [evt.event_id_size * 2]u8, 868 revision: evt.Patch.MergeRevision, 869 author: evt.CommitAuthor, 870 timestamp: u64, 871 }; 872 873 pub fn publish( 874 comptime repo_opts: rp.RepoOpts(.xit), 875 io: std.Io, 876 allocator: std.mem.Allocator, 877 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 878 target_repo: *rp.Repo(.xit, repo_opts), 879 fork_path: []const u8, 880 input: PublishInput, 881 ) !void { 882 const patch_id = try evt.parseEventId(&input.id); 883 var arena = std.heap.ArenaAllocator.init(allocator); 884 defer arena.deinit(); 885 886 // validate the fork ownership and publishing identity 887 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 888 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 889 if (fork_record.removed or 890 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 891 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 892 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 893 if (user.removed or 894 !std.mem.eql(u8, user.event.name, input.author.name) or 895 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 896 897 // read the patch staged in the fork 898 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 899 defer fork_repo.deinit(io, allocator); 900 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 901 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 902 903 // check whether this patch has already been published 904 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 905 error.NotFound => null, 906 else => |other| return other, 907 }; 908 const existing = if (target_moment) |moment| 909 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 910 else 911 null; 912 if (existing) |record| { 913 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 914 } 915 916 // publish the selected revision unless the draft was already consumed 917 if (local_patch.removed) { 918 if (existing == null) return error.PatchDataUnavailable; 919 } else { 920 var patch = (existing orelse local_patch).event; 921 if (local_patch.event.revision) |selected| { 922 const revision_id = try evt.parseEventId(&selected.id); 923 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 924 if (!selected.matches(revision)) return error.PatchNotPushed; 925 patch.revision = selected; 926 } 927 if (existing == null) patch.status = .open; 928 929 // write the published patch to the target repository 930 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 931 .id = input.id, 932 .timestamp = input.timestamp, 933 .author = input.author, 934 .event = .{ .patch = patch }, 935 }}); 936 937 // remove the consumed draft from the fork 938 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 939 .id = input.id, 940 .timestamp = input.timestamp, 941 .author = input.author, 942 .event = .{ .patch = null }, 943 }}); 944 } 945 946 // mark the fork as published in the administration repository 947 if (fork_record.event.stage == .draft) { 948 var published = fork_record.event; 949 published.stage = .publish; 950 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 951 .id = input.id, 952 .timestamp = input.timestamp, 953 .author = input.author, 954 .event = .{ .fork = published }, 955 }}); 956 } 957 } 958 959 pub fn editDraft( 960 comptime repo_opts: rp.RepoOpts(.xit), 961 io: std.Io, 962 allocator: std.mem.Allocator, 963 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 964 fork_path: []const u8, 965 input: EditDraftInput, 966 ) !bool { 967 // validate the submitted fields before opening repositories 968 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 969 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 970 const patch_id = try evt.parseEventId(&input.id); 971 var arena = std.heap.ArenaAllocator.init(allocator); 972 defer arena.deinit(); 973 974 // validate the draft ownership and editing identity 975 { 976 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 977 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 978 if (fork_record.event.stage != .draft) return false; 979 if (fork_record.removed or 980 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 981 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 982 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 983 if (user.removed or 984 !std.mem.eql(u8, user.event.name, input.author.name) or 985 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 986 } 987 988 // read the draft patch from its fork 989 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 990 defer fork_repo.deinit(io, allocator); 991 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 992 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 993 if (record.removed) return error.PatchDataUnavailable; 994 995 // apply the edits and invalidate a revision targeting another branch 996 var patch = record.event; 997 patch.title = input.title; 998 patch.tags = input.tags; 999 patch.description = input.description; 1000 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 1001 patch.target_branch = input.target_branch; 1002 1003 // commit the updated draft metadata 1004 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 1005 .id = input.id, 1006 .timestamp = input.timestamp, 1007 .author = input.author, 1008 .event = .{ .patch = patch }, 1009 }}); 1010 return true; 1011 } 1012 1013 // merge the selected patch revision into its target branch 1014 pub fn merge( 1015 comptime repo_opts: rp.RepoOpts(.xit), 1016 io: std.Io, 1017 allocator: std.mem.Allocator, 1018 repo_root_path: []const u8, 1019 target_repo: *rp.Repo(.xit, repo_opts), 1020 input: MergeInput, 1021 ) !void { 1022 const patch_id = try evt.parseEventId(&input.id); 1023 errdefer |err| { 1024 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 1025 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 1026 } 1027 } 1028 var arena = std.heap.ArenaAllocator.init(allocator); 1029 defer arena.deinit(); 1030 1031 // validate the target patch 1032 const target_moment = try evt.currentMoment(repo_opts, target_repo); 1033 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 1034 if (patch_record.removed) return error.InvalidPatch; 1035 switch (patch_record.event.status) { 1036 .open => {}, 1037 .closed => return error.PatchClosed, 1038 .merged => return error.PatchAlreadyMerged, 1039 } 1040 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 1041 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 1042 1043 // open the fork 1044 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 1045 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; 1046 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1047 1048 // select the commit and merge identity 1049 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 1050 .squash => selected.squash_oid, 1051 .source => selected.source_oid, 1052 }) catch return error.InvalidPatch; 1053 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 1054 1055 // merge the code and events in one target transaction 1056 { 1057 const DB = rp.Repo(.xit, repo_opts).DB; 1058 const State = rp.Repo(.xit, repo_opts).State; 1059 const Ctx = struct { 1060 core: *rp.Repo(.xit, repo_opts).Core, 1061 fork_repo: ?*rp.Repo(.xit, repo_opts), 1062 io: std.Io, 1063 allocator: std.mem.Allocator, 1064 patch_id: [evt.event_id_size]u8, 1065 expected_patch: evt.Patch, 1066 target_ref: rf.Ref, 1067 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 1068 revision: evt.Patch.MergeRevision, 1069 identity: []const u8, 1070 author: evt.CommitAuthor, 1071 timestamp: u64, 1072 1073 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1074 var moment = try DB.HashMap(.read_write).init(cursor.*); 1075 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 1076 1077 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 1078 defer check_arena.deinit(); 1079 1080 // require the fork's newest revision while both repos are locked 1081 const selected_revision = ctx.expected_patch.revision orelse unreachable; 1082 const revision_id = try evt.parseEventId(&selected_revision.id); 1083 if (ctx.fork_repo) |repo| { 1084 const fork_moment = try evt.currentMoment(repo_opts, repo); 1085 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 1086 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 1087 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 1088 1089 // require a clean cached result for the selected merge style. 1090 { 1091 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 1092 switch (availability.get(ctx.revision)) { 1093 .clean => {}, 1094 .conflict => return error.MergeConflict, 1095 .unknown => return error.MergeCheckUnavailable, 1096 } 1097 } 1098 1099 // copy the selected commit and its dependencies 1100 if (ctx.fork_repo) |repo| { 1101 var fork_repo_moment = try repo.core.latestMoment(); 1102 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 1103 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 1104 defer objects.deinit(); 1105 try objects.include(&ctx.selected_oid); 1106 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 1107 } 1108 1109 // merge the selected commit 1110 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1111 { 1112 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 1113 .kind = .full, 1114 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 1115 .commit_metadata = .{ 1116 .author = ctx.identity, 1117 .committer = ctx.identity, 1118 .message = ctx.expected_patch.title, 1119 .timestamp = ctx.timestamp, 1120 }, 1121 }, ctx.target_ref, null); 1122 defer merge_result.deinit(); 1123 switch (merge_result.result) { 1124 .conflict => return error.MergeConflict, 1125 .success, .fast_forward, .nothing => {}, 1126 .clean => unreachable, 1127 } 1128 } 1129 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1130 1131 // retain the submitted revision and snapshot the merge result 1132 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; 1133 1134 // record the merge as one undoable action. 1135 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 1136 } 1137 }; 1138 1139 // lock the fork before the target for the full merge transaction. 1140 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 1141 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 1142 try target_repo.core.db_file.lock(io, .exclusive); 1143 defer target_repo.core.db_file.unlock(io); 1144 1145 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1146 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1147 .core = &target_repo.core, 1148 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 1149 .io = io, 1150 .allocator = allocator, 1151 .patch_id = patch_id, 1152 .expected_patch = patch_record.event, 1153 .target_ref = target_ref, 1154 .selected_oid = selected_oid, 1155 .revision = input.revision, 1156 .identity = identity, 1157 .author = input.author, 1158 .timestamp = input.timestamp, 1159 }); 1160 } 1161 1162 // refresh other patches affected by the updated target branch. 1163 refreshOpenMergeability(repo_opts, io, allocator, target_repo, null, null); 1164 1165 // the merge moved the target branch, so its indexes follow 1166 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 1167 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 1168 }; 1169 srch_cmmt.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 1170 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 1171 }; 1172 } 1173 1174 // merge a published patch and remove its fork 1175 pub fn mergeAndRemoveFork( 1176 comptime repo_opts: rp.RepoOpts(.xit), 1177 io: std.Io, 1178 allocator: std.mem.Allocator, 1179 repo_root_path: []const u8, 1180 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1181 target_repo: *rp.Repo(.xit, repo_opts), 1182 input: MergeInput, 1183 ) !void { 1184 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1185 var arena = std.heap.ArenaAllocator.init(allocator); 1186 defer arena.deinit(); 1187 1188 // remove fork data only for patches backed by a fork. 1189 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1190 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1191 } 1192 1193 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1194 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1195 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1196 const name = std.mem.trimEnd(u8, line[0..open], " "); 1197 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1198 return .{ .name = name, .email = line[open + 1 .. close] }; 1199 } 1200 1201 // import a revision after detecting a client-side merge 1202 fn importMerged( 1203 comptime repo_opts: rp.RepoOpts(.xit), 1204 state: rp.Repo(.xit, repo_opts).State(.read_write), 1205 db: *evt.EventDB(repo_opts.hash), 1206 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1207 io: std.Io, 1208 allocator: std.mem.Allocator, 1209 repo_root_path: []const u8, 1210 patch_id: *const [evt.event_id_size]u8, 1211 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1212 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1213 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1214 ) !void { 1215 var arena = std.heap.ArenaAllocator.init(allocator); 1216 defer arena.deinit(); 1217 1218 // identify which selected revision was merged by the client. 1219 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1220 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1221 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1222 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1223 const selected = record.event.revision orelse return; 1224 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; 1225 1226 // open the fork when the revision is not stored in the target repository. 1227 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 }); 1228 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1229 1230 // import the revision and record the client-side merge. 1231 _ = 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); 1232 } 1233 1234 // import the revision and mark its patch merged in the current transaction 1235 fn importMergedRevision( 1236 comptime repo_opts: rp.RepoOpts(.xit), 1237 state: rp.Repo(.xit, repo_opts).State(.read_write), 1238 db: *evt.EventDB(repo_opts.hash), 1239 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1240 io: std.Io, 1241 allocator: std.mem.Allocator, 1242 fork_repo: ?*rp.Repo(.xit, repo_opts), 1243 patch_id: *const [evt.event_id_size]u8, 1244 merged: struct { 1245 revision: evt.Patch.MergeRevision, 1246 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1247 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1248 }, 1249 expected_patch: ?evt.Patch, 1250 merged_author: ?evt.CommitAuthor, 1251 merged_timestamp: u64, 1252 ) !bool { 1253 const DB = evt.EventDB(repo_opts.hash); 1254 var arena = std.heap.ArenaAllocator.init(allocator); 1255 defer arena.deinit(); 1256 1257 // read the patch and reject outdated or conflicting merge requests. 1258 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1259 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1260 const selected = patch_record.event.revision orelse return false; 1261 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1262 if (expected_patch) |expected| { 1263 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1264 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1265 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1266 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1267 } 1268 } 1269 const revision_id = try evt.parseEventId(&selected.id); 1270 1271 // resolve the selected revision from the target or its fork. 1272 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1273 const revision = (if (fork_repo) |repo| 1274 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1275 else 1276 current_revision) orelse return false; 1277 if (!selected.matches(revision)) return false; 1278 1279 // read the original revision commit and author. 1280 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1281 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 } }; 1282 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1283 if (revision.event_oid.len != event_oid.len) return false; 1284 @memcpy(&event_oid, revision.event_oid); 1285 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1286 defer event_object.deinit(); 1287 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1288 1289 // retain the submitted revision if the target has not imported it yet. 1290 var events_buffer: [3]evt.EventWithId = undefined; 1291 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1292 var tree_entries: [2]evt.EventTreeEntry = undefined; 1293 const needs_import = if (current_revision) |existing| existing.removed else true; 1294 if (needs_import) { 1295 tree_entries = .{ 1296 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1297 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1298 }; 1299 events.appendAssumeCapacity(.{ 1300 .id = selected.id, 1301 .timestamp = event_object.content.commit.metadata.timestamp, 1302 .author = original_author, 1303 .tree_entries = &tree_entries, 1304 .event = .{ .patchrev = revision.event }, 1305 }); 1306 } else { 1307 const existing = current_revision orelse unreachable; 1308 if (!selected.matches(existing)) return error.InvalidPatch; 1309 } 1310 1311 // snapshot the merge result and mark the patch as merged. 1312 { 1313 const author = merged_author orelse original_author; 1314 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1315 var patch = patch_record.event; 1316 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1317 events.appendAssumeCapacity(result.event); 1318 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1319 events.appendAssumeCapacity(.{ 1320 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1321 .timestamp = timestamp, 1322 .author = author, 1323 .event = .{ .patch = patch }, 1324 }); 1325 } 1326 1327 // commit and consume the revision and patch events together. 1328 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1329 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1330 return true; 1331 } 1332 1333 // find patches merged by commits received in a push 1334 pub fn detectMerged( 1335 comptime repo_opts: rp.RepoOpts(.xit), 1336 state: rp.Repo(.xit, repo_opts).State(.read_write), 1337 db: *evt.EventDB(repo_opts.hash), 1338 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1339 io: std.Io, 1340 allocator: std.mem.Allocator, 1341 repo_root_path: []const u8, 1342 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1343 error_writer: *std.Io.Writer, 1344 ) !void { 1345 const DB = evt.EventDB(repo_opts.hash); 1346 var arena = std.heap.ArenaAllocator.init(allocator); 1347 defer arena.deinit(); 1348 1349 // read the revision index used to identify merged patches. 1350 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1351 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1352 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1353 1354 // ignore event refs and inspect only changed branch tips. 1355 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1356 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1357 const heads_prefix = "refs/heads/"; 1358 for (updates) |update| { 1359 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1360 std.mem.eql(u8, update.ref_name, events_ref_path) or 1361 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1362 1363 // validate the ref tips and skip branch deletions. 1364 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1365 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1366 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1367 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1368 @memcpy(&old_oid, update.old_oid); 1369 @memcpy(&new_oid, update.new_oid); 1370 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1371 1372 // traverse commits introduced by this branch update. 1373 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1374 defer commits.deinit(); 1375 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1376 var targets: std.ArrayList(struct { 1377 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1378 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1379 }) = .empty; 1380 1381 // collect merge boundaries along the target's first-parent history. 1382 { 1383 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1384 defer first_parents.deinit(); 1385 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1386 try first_parents.include(&new_oid); 1387 while (try first_parents.next(arena.allocator())) |commit| { 1388 defer commit.deinit(); 1389 try targets.append(arena.allocator(), .{ 1390 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1391 .after_oid = commit.oid, 1392 }); 1393 } 1394 } 1395 1396 // visit target commits oldest first, attributing each revision to the 1397 // commit that introduced it; the shared iterator visits each ancestor once 1398 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1399 while (targets.pop()) |target| { 1400 try commits.include(&target.after_oid); 1401 while (try commits.next(arena.allocator())) |commit| { 1402 defer commit.deinit(); 1403 1404 // find patches whose selected revision matches this commit. 1405 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1406 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1407 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1408 var ids_iter = try ids.iterator(); 1409 while (try ids_iter.next()) |cursor| { 1410 const pair = try cursor.readKeyValuePair(); 1411 var patch_id: [evt.event_id_size]u8 = undefined; 1412 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1413 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1414 1415 // a fast-forward has no recorded merge boundary; use the old ref tip 1416 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1417 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1418 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1419 continue; 1420 }; 1421 } 1422 } 1423 } 1424 } 1425 } 1426