╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
895 896 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 897 defer check_arena.deinit(); 898 899 // require the fork's newest revision while both repos are locked 900 const selected_revision = ctx.expected_patch.revision orelse unreachable; 901 const revision_id = try evt.parseEventId(&selected_revision.id); 902 if (ctx.fork_repo) |repo| { 903 const fork_moment = try evt.currentMoment(repo_opts, repo); 904 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 905 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 906 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 907 908 // require a clean cached result for the selected merge style. 909 { 910 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 911 switch (availability.get(ctx.revision)) { 912 .clean => {}, 913 .conflict => return error.MergeConflict, 914 .unknown => return error.MergeCheckUnavailable, 915 } 916 } 917 918 // copy the selected commit and its dependencies 919 if (ctx.fork_repo) |repo| { 920 var fork_repo_moment = try repo.core.latestMoment(); 921 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 922 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 923 defer objects.deinit(); 924 try objects.include(&ctx.selected_oid); 925 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 926 } 927 928 // merge the selected commit 929 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 930 { 931 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 932 .kind = .full, 933 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 934 .commit_metadata = .{ 935 .author = ctx.identity, 936 .committer = ctx.identity, 937 .message = ctx.expected_patch.title, 938 .timestamp = ctx.timestamp, 939 }, 940 }, ctx.target_ref, null); 941 defer merge_result.deinit(); 942 switch (merge_result.result) { 943 .conflict => return error.MergeConflict, 944 .success, .fast_forward, .nothing => {}, 945 .clean => unreachable, 946 } 947 } 948 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 949 950 // retain the submitted revision and snapshot the merge result 951 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; 952 953 // record the merge as one undoable action. 954 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = "merge_patch" } }); 955 } 956 }; 957 958 // lock the fork before the target for the full merge transaction. 959 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 960 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 961 try target_repo.core.db_file.lock(io, .exclusive); 962 defer target_repo.core.db_file.unlock(io); 963 964 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 965 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 966 .core = &target_repo.core, 967 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 968 .io = io, 969 .allocator = allocator, 970 .patch_id = patch_id, 971 .expected_patch = patch_record.event, 972 .target_ref = target_ref, 973 .selected_oid = selected_oid, 974 .revision = input.revision, 975 .identity = identity, 976 .author = input.author, 977 .timestamp = input.timestamp, 978 }); 979 } 980 981 // refresh other patches affected by the updated target branch. 982 refreshMergeability(repo_opts, io, allocator, target_repo, null); 983 984 // the merge moved the target branch, so its indexes follow 985 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 986 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 987 }; 988 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 989 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 990 }; 991 } 992 993 // merge a published patch and remove its fork 994 pub fn mergeAndRemoveFork( 995 comptime repo_opts: rp.RepoOpts(.xit), 996 io: std.Io, 997 allocator: std.mem.Allocator, 998 repo_root_path: []const u8, 999 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1000 target_repo: *rp.Repo(.xit, repo_opts), 1001 input: MergeInput, 1002 ) !void { 1003 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1004 var arena = std.heap.ArenaAllocator.init(allocator); 1005 defer arena.deinit(); 1006 1007 // remove fork data only for patches backed by a fork. 1008 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1009 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1010 } 1011 1012 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1013 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1014 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1015 const name = std.mem.trimEnd(u8, line[0..open], " "); 1016 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1017 return .{ .name = name, .email = line[open + 1 .. close] }; 1018 } 1019 1020 // import a revision after detecting a client-side merge 1021 fn importMerged( 1022 comptime repo_opts: rp.RepoOpts(.xit), 1023 state: rp.Repo(.xit, repo_opts).State(.read_write), 1024 db: *evt.EventDB(repo_opts.hash), 1025 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1026 io: std.Io, 1027 allocator: std.mem.Allocator, 1028 repo_root_path: []const u8, 1029 patch_id: *const [evt.event_id_size]u8, 1030 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1031 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1032 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1033 ) !void { 1034 var arena = std.heap.ArenaAllocator.init(allocator); 1035 defer arena.deinit(); 1036 1037 // identify which selected revision was merged by the client. 1038 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1039 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1040 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1041 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1042 const selected = record.event.revision orelse return; 1043 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; 1044 1045 // open the fork when the revision is not stored in the target repository. 1046 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 }); 1047 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1048 1049 // import the revision and record the client-side merge. 1050 _ = 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); 1051 } 1052 1053 // import the revision and mark its patch merged in the current transaction 1054 fn importMergedRevision( 1055 comptime repo_opts: rp.RepoOpts(.xit), 1056 state: rp.Repo(.xit, repo_opts).State(.read_write), 1057 db: *evt.EventDB(repo_opts.hash), 1058 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1059 io: std.Io, 1060 allocator: std.mem.Allocator, 1061 fork_repo: ?*rp.Repo(.xit, repo_opts), 1062 patch_id: *const [evt.event_id_size]u8, 1063 merged: struct { 1064 revision: evt.Patch.MergeRevision, 1065 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1066 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1067 }, 1068 expected_patch: ?evt.Patch, 1069 merged_author: ?evt.CommitAuthor, 1070 merged_timestamp: u64, 1071 ) !bool { 1072 const DB = evt.EventDB(repo_opts.hash); 1073 var arena = std.heap.ArenaAllocator.init(allocator); 1074 defer arena.deinit(); 1075 1076 // read the patch and reject outdated or conflicting merge requests. 1077 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1078 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1079 const selected = patch_record.event.revision orelse return false; 1080 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1081 if (expected_patch) |expected| { 1082 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1083 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1084 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1085 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1086 } 1087 } 1088 const revision_id = try evt.parseEventId(&selected.id); 1089 1090 // resolve the selected revision from the target or its fork. 1091 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1092 const revision = (if (fork_repo) |repo| 1093 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1094 else 1095 current_revision) orelse return false; 1096 if (!selected.matches(revision)) return false; 1097 1098 // read the original revision commit and author. 1099 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1100 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 } }; 1101 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1102 if (revision.event_oid.len != event_oid.len) return false; 1103 @memcpy(&event_oid, revision.event_oid); 1104 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1105 defer event_object.deinit(); 1106 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1107 1108 // retain the submitted revision if the target has not imported it yet. 1109 var events_buffer: [3]evt.EventWithId = undefined; 1110 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1111 var tree_entries: [2]evt.EventTreeEntry = undefined; 1112 const needs_import = if (current_revision) |existing| existing.removed else true; 1113 if (needs_import) { 1114 tree_entries = .{ 1115 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1116 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1117 }; 1118 events.appendAssumeCapacity(.{ 1119 .id = selected.id, 1120 .timestamp = event_object.content.commit.metadata.timestamp, 1121 .author = original_author, 1122 .tree_entries = &tree_entries, 1123 .event = .{ .patchrev = revision.event }, 1124 }); 1125 } else { 1126 const existing = current_revision orelse unreachable; 1127 if (!selected.matches(existing)) return error.InvalidPatch; 1128 } 1129 1130 // snapshot the merge result and mark the patch as merged. 1131 { 1132 const author = merged_author orelse original_author; 1133 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1134 var patch = patch_record.event; 1135 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1136 events.appendAssumeCapacity(result.event); 1137 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1138 events.appendAssumeCapacity(.{ 1139 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1140 .timestamp = timestamp, 1141 .author = author, 1142 .event = .{ .patch = patch }, 1143 }); 1144 } 1145 1146 // commit and consume the revision and patch events together. 1147 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1148 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1149 return true; 1150 } 1151 1152 // find patches merged by commits received in a push 1153 pub fn detectMerged( 1154 comptime repo_opts: rp.RepoOpts(.xit), 1155 state: rp.Repo(.xit, repo_opts).State(.read_write), 1156 db: *evt.EventDB(repo_opts.hash), 1157 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1158 io: std.Io, 1159 allocator: std.mem.Allocator, 1160 repo_root_path: []const u8, 1161 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1162 error_writer: *std.Io.Writer, 1163 ) !void { 1164 const DB = evt.EventDB(repo_opts.hash); 1165 var arena = std.heap.ArenaAllocator.init(allocator); 1166 defer arena.deinit(); 1167 1168 // read the revision index used to identify merged patches. 1169 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1170 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1171 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1172 1173 // ignore event refs and inspect only changed branch tips. 1174 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1175 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1176 const heads_prefix = "refs/heads/"; 1177 for (updates) |update| { 1178 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1179 std.mem.eql(u8, update.ref_name, events_ref_path) or 1180 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1181 1182 // validate the ref tips and skip branch deletions. 1183 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1184 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1185 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1186 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1187 @memcpy(&old_oid, update.old_oid); 1188 @memcpy(&new_oid, update.new_oid); 1189 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1190 1191 // traverse commits introduced by this branch update. 1192 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1193 defer commits.deinit(); 1194 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1195 var targets: std.ArrayList(struct { 1196 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1197 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1198 }) = .empty; 1199 1200 // collect merge boundaries along the target's first-parent history. 1201 { 1202 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1203 defer first_parents.deinit(); 1204 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1205 try first_parents.include(&new_oid); 1206 while (try first_parents.next(arena.allocator())) |commit| { 1207 defer commit.deinit(); 1208 try targets.append(arena.allocator(), .{ 1209 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1210 .after_oid = commit.oid, 1211 }); 1212 } 1213 } 1214 1215 // visit target commits oldest first, attributing each revision to the 1216 // commit that introduced it; the shared iterator visits each ancestor once 1217 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1218 while (targets.pop()) |target| { 1219 try commits.include(&target.after_oid); 1220 while (try commits.next(arena.allocator())) |commit| { 1221 defer commit.deinit(); 1222 1223 // find patches whose selected revision matches this commit. 1224 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1225 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1226 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1227 var ids_iter = try ids.iterator(); 1228 while (try ids_iter.next()) |cursor| { 1229 const pair = try cursor.readKeyValuePair(); 1230 var patch_id: [evt.event_id_size]u8 = undefined; 1231 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1232 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1233 1234 // a fast-forward has no recorded merge boundary; use the old ref tip 1235 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1236 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1237 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1238 continue; 1239 }; 1240 } 1241 } 1242 } 1243 } 1244 } 1245