╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
972 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, evt.events_ref)) return error.CancelTransaction; 973 _ = try ctx.checks.update(state, ctx.io, ctx.allocator); 974 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = evt.undo_action } }); 975 } 976 }; 977 978 try target_repo.core.db_file.lock(io, .exclusive); 979 defer target_repo.core.db_file.unlock(io); 980 981 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 982 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 983 .core = &target_repo.core, 984 .io = io, 985 .allocator = allocator, 986 .events = &.{.{ 987 .id = input.id, 988 .timestamp = input.timestamp, 989 .author = input.author, 990 .event = .{ .patch = patch }, 991 }}, 992 .patch_id = patch_id, 993 .forker_id = std.fmt.bytesToHex(input.user_id, .lower), 994 .checks = &checks, 995 .first_parent = first_parent, 996 }) catch |err| switch (err) { 997 error.CancelTransaction => {}, 998 else => |e| return e, 999 }; 1000 } 1001 evt.bumpRepoActivityAt(io, allocator, users_dir, target_repo.core.work_path); 1002 1003 // remove the consumed draft from the fork 1004 try evt.consume(.{ .server = .{ .users_dir = users_dir } }, .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 = null }, 1009 }}); 1010 } 1011 1012 // mark the fork as published in the forker's user repo 1013 if (fork_record.event.stage == .draft) { 1014 var published = fork_record.event; 1015 published.stage = .publish; 1016 try evt.consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, evt.user_repo_opts, io, allocator, &user_repo, evt.events_ref, &.{.{ 1017 .id = input.id, 1018 .timestamp = input.timestamp, 1019 .author = input.author, 1020 .event = .{ .fork = published }, 1021 }}); 1022 } 1023 } 1024 1025 pub fn editDraft( 1026 comptime repo_opts: rp.RepoOpts(.xit), 1027 io: std.Io, 1028 allocator: std.mem.Allocator, 1029 users_dir: []const u8, 1030 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1031 input: EditDraftInput, 1032 ) !bool { 1033 // validate the submitted fields before opening repositories 1034 if (!evt.Patch.fieldsValid(input.title, input.labels)) return error.InvalidFields; 1035 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 1036 const patch_id = try evt.parseEventId(&input.id); 1037 var arena = std.heap.ArenaAllocator.init(allocator); 1038 defer arena.deinit(); 1039 1040 // validate the draft ownership and editing identity 1041 { 1042 var user_repo = (try evt.openUserRepo(io, allocator, users_dir, &input.user_id)) orelse return false; 1043 defer user_repo.deinit(io, allocator); 1044 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 1045 const user_moment = (try evt.userMoment(&user_repo)) orelse return false; 1046 const fork_record = (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, &arena, &patch_id)) orelse return false; 1047 if (fork_record.event.stage != .draft) return false; 1048 if (fork_record.removed or !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 1049 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 1050 if (user.removed or 1051 !std.mem.eql(u8, user.event.name, input.author.name) or 1052 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 1053 } 1054 1055 // read the draft patch from its fork 1056 const fork_path = try fork.forkPath(arena.allocator(), users_dir, &input.user_id, &patch_id); 1057 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 1058 defer fork_repo.deinit(io, allocator); 1059 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 1060 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 1061 if (record.removed) return error.PatchDataUnavailable; 1062 1063 // apply the edits and invalidate a revision targeting another branch 1064 var patch = record.event; 1065 patch.title = input.title; 1066 patch.labels = input.labels; 1067 patch.description = input.description; 1068 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 1069 patch.target_branch = input.target_branch; 1070 1071 // commit the updated draft metadata 1072 try evt.consume(.{ .server = .{ .users_dir = users_dir } }, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 1073 .id = input.id, 1074 .timestamp = input.timestamp, 1075 .author = input.author, 1076 .event = .{ .patch = patch }, 1077 }}); 1078 return true; 1079 } 1080 1081 // merge the selected patch revision into its target branch 1082 pub fn merge( 1083 comptime repo_opts: rp.RepoOpts(.xit), 1084 io: std.Io, 1085 allocator: std.mem.Allocator, 1086 users_dir: []const u8, 1087 target_repo: *rp.Repo(.xit, repo_opts), 1088 input: MergeInput, 1089 ) !void { 1090 const patch_id = try evt.parseEventId(&input.id); 1091 errdefer |err| { 1092 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 1093 refreshMergeability(repo_opts, io, allocator, target_repo, users_dir, patch_id); 1094 } 1095 } 1096 var arena = std.heap.ArenaAllocator.init(allocator); 1097 defer arena.deinit(); 1098 1099 // validate the target patch 1100 const target_moment = try evt.currentMoment(repo_opts, target_repo); 1101 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 1102 if (patch_record.removed) return error.InvalidPatch; 1103 switch (patch_record.event.status) { 1104 .open => {}, 1105 .closed => return error.PatchClosed, 1106 .merged => return error.PatchAlreadyMerged, 1107 } 1108 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 1109 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 1110 1111 // open the fork 1112 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (patch_record.event.source_branch != null) null else blk: { 1113 var config = try target_repo.listConfig(io, allocator); 1114 defer config.deinit(); 1115 const forker_id = (try fork.readForkerId(&config.sections, &patch_id)) orelse return error.PatchDataUnavailable; 1116 const fork_path = try fork.forkPath(arena.allocator(), users_dir, &forker_id, &patch_id); 1117 break :blk rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 1118 }; 1119 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1120 1121 // select the commit and merge identity 1122 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 1123 .squash => selected.squash_oid, 1124 .source => selected.source_oid, 1125 }) catch return error.InvalidPatch; 1126 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 1127 1128 // merge the code and events in one target transaction 1129 { 1130 const DB = rp.Repo(.xit, repo_opts).DB; 1131 const State = rp.Repo(.xit, repo_opts).State; 1132 const Ctx = struct { 1133 core: *rp.Repo(.xit, repo_opts).Core, 1134 fork_repo: ?*rp.Repo(.xit, repo_opts), 1135 io: std.Io, 1136 allocator: std.mem.Allocator, 1137 patch_id: [evt.event_id_size]u8, 1138 expected_patch: evt.Patch, 1139 target_ref: rf.Ref, 1140 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 1141 revision: evt.Patch.MergeRevision, 1142 identity: []const u8, 1143 author: evt.CommitAuthor, 1144 timestamp: u64, 1145 1146 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1147 var moment = try DB.HashMap(.read_write).init(cursor.*); 1148 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 1149 1150 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 1151 defer check_arena.deinit(); 1152 1153 // require the fork's newest revision while both repos are locked 1154 const selected_revision = ctx.expected_patch.revision orelse unreachable; 1155 const revision_id = try evt.parseEventId(&selected_revision.id); 1156 if (ctx.fork_repo) |repo| { 1157 const fork_moment = try evt.currentMoment(repo_opts, repo); 1158 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 1159 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 1160 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 1161 1162 // require a clean cached result for the selected merge style. 1163 { 1164 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 1165 switch (availability.get(ctx.revision)) { 1166 .clean => {}, 1167 .conflict => return error.MergeConflict, 1168 .unknown => return error.MergeCheckUnavailable, 1169 } 1170 } 1171 1172 // copy the selected commit and its dependencies 1173 if (ctx.fork_repo) |repo| { 1174 var fork_repo_moment = try repo.core.latestMoment(); 1175 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 1176 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 1177 defer objects.deinit(); 1178 try objects.include(&ctx.selected_oid); 1179 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 1180 } 1181 1182 // merge the selected commit 1183 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1184 { 1185 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 1186 .kind = .full, 1187 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 1188 .commit_metadata = .{ 1189 .author = ctx.identity, 1190 .committer = ctx.identity, 1191 .message = ctx.expected_patch.title, 1192 .timestamp = ctx.timestamp, 1193 }, 1194 }, ctx.target_ref, null); 1195 defer merge_result.deinit(); 1196 switch (merge_result.result) { 1197 .conflict => return error.MergeConflict, 1198 .success, .fast_forward, .nothing => {}, 1199 .clean => unreachable, 1200 } 1201 } 1202 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1203 1204 // retain the submitted revision and snapshot the merge result 1205 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; 1206 1207 // the merge moved the target branch, so its indexes follow, 1208 // the commit index deriving from the old tip's version 1209 _ = try find.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, null); 1210 _ = try srch_cmmt.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, &.{.{ .old_oid = &before_oid, .new_oid = &after_oid }}, null); 1211 1212 // record the merge as one undoable action. 1213 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 1214 } 1215 }; 1216 1217 // lock the fork before the target for the full merge transaction. 1218 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 1219 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 1220 try target_repo.core.db_file.lock(io, .exclusive); 1221 defer target_repo.core.db_file.unlock(io); 1222 1223 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1224 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1225 .core = &target_repo.core, 1226 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 1227 .io = io, 1228 .allocator = allocator, 1229 .patch_id = patch_id, 1230 .expected_patch = patch_record.event, 1231 .target_ref = target_ref, 1232 .selected_oid = selected_oid, 1233 .revision = input.revision, 1234 .identity = identity, 1235 .author = input.author, 1236 .timestamp = input.timestamp, 1237 }); 1238 } 1239 evt.bumpRepoActivityAt(io, allocator, users_dir, target_repo.core.work_path); 1240 1241 // refresh other patches affected by the updated target branch. 1242 refreshOpenMergeability(repo_opts, io, allocator, target_repo, users_dir, null, null); 1243 } 1244 1245 // merge a published patch and remove its fork 1246 pub fn mergeAndRemoveFork( 1247 comptime repo_opts: rp.RepoOpts(.xit), 1248 io: std.Io, 1249 allocator: std.mem.Allocator, 1250 users_dir: []const u8, 1251 target_repo: *rp.Repo(.xit, repo_opts), 1252 input: MergeInput, 1253 ) !void { 1254 try merge(repo_opts, io, allocator, users_dir, target_repo, input); 1255 var arena = std.heap.ArenaAllocator.init(allocator); 1256 defer arena.deinit(); 1257 1258 // remove fork data only for patches backed by a fork 1259 const patch_id = try evt.parseEventId(&input.id); 1260 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &patch_id)) orelse return error.InvalidPatch; 1261 if (record.event.source_branch != null) return; 1262 // a patch from another instance has no fork here 1263 const forker_id = blk: { 1264 var config = try target_repo.listConfig(io, allocator); 1265 defer config.deinit(); 1266 break :blk (try fork.readForkerId(&config.sections, &patch_id)) orelse return; 1267 }; 1268 try fork.remove(io, allocator, users_dir, &forker_id, &input.id, input.author); 1269 } 1270 1271 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1272 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1273 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1274 const name = std.mem.trimEnd(u8, line[0..open], " "); 1275 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1276 return .{ .name = name, .email = line[open + 1 .. close] }; 1277 } 1278 1279 // import a revision after detecting a client-side merge 1280 fn importMerged( 1281 comptime repo_opts: rp.RepoOpts(.xit), 1282 state: rp.Repo(.xit, repo_opts).State(.read_write), 1283 db: *evt.EventDB(repo_opts.hash), 1284 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1285 io: std.Io, 1286 allocator: std.mem.Allocator, 1287 users_dir: []const u8, 1288 patch_id: *const [evt.event_id_size]u8, 1289 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1290 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1291 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1292 ) !void { 1293 var arena = std.heap.ArenaAllocator.init(allocator); 1294 defer arena.deinit(); 1295 1296 // identify which selected revision was merged by the client. 1297 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1298 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1299 const selected = record.event.revision orelse return; 1300 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; 1301 1302 // open the fork when the revision is not stored in the target repository. 1303 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (record.event.source_branch != null) null else blk: { 1304 var config = try xit.config.Config(.xit, repo_opts).init(state.readOnly(), io, allocator); 1305 defer config.deinit(); 1306 const forker_id = (try fork.readForkerId(&config.sections, patch_id)) orelse return error.PatchDataUnavailable; 1307 const fork_path = try fork.forkPath(arena.allocator(), users_dir, &forker_id, patch_id); 1308 break :blk try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 1309 }; 1310 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1311 1312 // import the revision and record the client-side merge. 1313 _ = 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); 1314 } 1315 1316 // import the revision and mark its patch merged in the current transaction 1317 fn importMergedRevision( 1318 comptime repo_opts: rp.RepoOpts(.xit), 1319 state: rp.Repo(.xit, repo_opts).State(.read_write), 1320 db: *evt.EventDB(repo_opts.hash), 1321 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1322 io: std.Io, 1323 allocator: std.mem.Allocator, 1324 fork_repo: ?*rp.Repo(.xit, repo_opts), 1325 patch_id: *const [evt.event_id_size]u8, 1326 merged: struct { 1327 revision: evt.Patch.MergeRevision, 1328 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1329 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1330 }, 1331 expected_patch: ?evt.Patch, 1332 merged_author: ?evt.CommitAuthor, 1333 merged_timestamp: u64, 1334 ) !bool { 1335 const DB = evt.EventDB(repo_opts.hash); 1336 var arena = std.heap.ArenaAllocator.init(allocator); 1337 defer arena.deinit(); 1338 1339 // read the patch and reject outdated or conflicting merge requests. 1340 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1341 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1342 const selected = patch_record.event.revision orelse return false; 1343 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1344 if (expected_patch) |expected| { 1345 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1346 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1347 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1348 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1349 } 1350 } 1351 const revision_id = try evt.parseEventId(&selected.id); 1352 1353 // resolve the selected revision from the target or its fork. 1354 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1355 const revision = (if (fork_repo) |repo| 1356 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1357 else 1358 current_revision) orelse return false; 1359 if (!selected.matches(revision)) return false; 1360 1361 // read the original revision commit and author. 1362 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1363 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 } }; 1364 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1365 if (revision.event_oid.len != event_oid.len) return false; 1366 @memcpy(&event_oid, revision.event_oid); 1367 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1368 defer event_object.deinit(); 1369 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1370 1371 // retain the submitted revision if the target has not imported it yet. 1372 var events_buffer: [3]evt.EventWithId = undefined; 1373 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1374 var tree_entries: [2]evt.EventTreeEntry = undefined; 1375 const needs_import = if (current_revision) |existing| existing.removed else true; 1376 if (needs_import) { 1377 tree_entries = .{ 1378 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1379 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1380 }; 1381 events.appendAssumeCapacity(.{ 1382 .id = selected.id, 1383 .timestamp = event_object.content.commit.metadata.timestamp, 1384 .author = original_author, 1385 .tree_entries = &tree_entries, 1386 .event = .{ .patchrev = revision.event }, 1387 }); 1388 } else { 1389 const existing = current_revision orelse unreachable; 1390 if (!selected.matches(existing)) return error.InvalidPatch; 1391 } 1392 1393 // snapshot the merge result and mark the patch as merged. 1394 { 1395 const author = merged_author orelse original_author; 1396 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1397 var patch = patch_record.event; 1398 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1399 events.appendAssumeCapacity(result.event); 1400 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1401 events.appendAssumeCapacity(.{ 1402 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1403 .timestamp = timestamp, 1404 .author = author, 1405 .event = .{ .patch = patch }, 1406 }); 1407 } 1408 1409 // commit and consume the revision and patch events together. 1410 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1411 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1412 return true; 1413 } 1414 1415 // find patches merged by commits received in a push 1416 pub fn detectMerged( 1417 comptime repo_opts: rp.RepoOpts(.xit), 1418 state: rp.Repo(.xit, repo_opts).State(.read_write), 1419 db: *evt.EventDB(repo_opts.hash), 1420 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1421 io: std.Io, 1422 allocator: std.mem.Allocator, 1423 users_dir: []const u8, 1424 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1425 error_writer: *std.Io.Writer, 1426 ) !void { 1427 const DB = evt.EventDB(repo_opts.hash); 1428 var arena = std.heap.ArenaAllocator.init(allocator); 1429 defer arena.deinit(); 1430 1431 // read the revision index used to identify merged patches. 1432 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1433 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1434 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1435 1436 // ignore event refs and inspect only changed branch tips. 1437 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1438 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1439 const heads_prefix = "refs/heads/"; 1440 for (updates) |update| { 1441 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1442 std.mem.eql(u8, update.ref_name, events_ref_path) or 1443 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1444 1445 // validate the ref tips and skip branch deletions. 1446 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1447 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1448 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1449 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1450 @memcpy(&old_oid, update.old_oid); 1451 @memcpy(&new_oid, update.new_oid); 1452 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1453 1454 // traverse commits introduced by this branch update. 1455 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1456 defer commits.deinit(); 1457 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1458 var targets: std.ArrayList(struct { 1459 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1460 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1461 }) = .empty; 1462 1463 // collect merge boundaries along the target's first-parent history. 1464 { 1465 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1466 defer first_parents.deinit(); 1467 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1468 try first_parents.include(&new_oid); 1469 while (try first_parents.next(arena.allocator())) |commit| { 1470 defer commit.deinit(); 1471 try targets.append(arena.allocator(), .{ 1472 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1473 .after_oid = commit.oid, 1474 }); 1475 } 1476 } 1477 1478 // visit target commits oldest first, attributing each revision to the 1479 // commit that introduced it; the shared iterator visits each ancestor once 1480 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1481 while (targets.pop()) |target| { 1482 try commits.include(&target.after_oid); 1483 while (try commits.next(arena.allocator())) |commit| { 1484 defer commit.deinit(); 1485 1486 // find patches whose selected revision matches this commit. 1487 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1488 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1489 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1490 var ids_iter = try ids.iterator(); 1491 while (try ids_iter.next()) |cursor| { 1492 const pair = try cursor.readKeyValuePair(); 1493 var patch_id: [evt.event_id_size]u8 = undefined; 1494 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1495 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1496 1497 // a fast-forward has no recorded merge boundary; use the old ref tip 1498 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1499 importMerged(repo_opts, state, db, moment, io, allocator, users_dir, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1500 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1501 continue; 1502 }; 1503 } 1504 } 1505 } 1506 } 1507 } 1508