╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
687 var arena = std.heap.ArenaAllocator.init(allocator); 688 defer arena.deinit(); 689 var changed = false; 690 for (self.forks.keys(), self.forks.values()) |id, *repo| { 691 const saved = updateMergeCheck(repo_opts, state, io, &arena, &id, if (repo.*) |*value| value else null) catch |err| switch (err) { 692 error.MergeCheckRestoreFailed => return err, 693 else => { 694 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 695 continue; 696 }, 697 }; 698 if (saved) changed = true; 699 } 700 return changed; 701 } 702 }; 703 } 704 705 // the caller holds the target's exclusive lock, and any fork's shared lock. 706 // this only saves the cache; it never creates a top-level history transaction. 707 fn updateMergeCheck( 708 comptime repo_opts: rp.RepoOpts(.xit), 709 state: rp.Repo(.xit, repo_opts).State(.read_write), 710 io: std.Io, 711 arena: *std.heap.ArenaAllocator, 712 id: *const [evt.event_id_size]u8, 713 fork_repo: ?*rp.Repo(.xit, repo_opts), 714 ) !bool { 715 const DB = rp.Repo(.xit, repo_opts).DB; 716 717 // read the patch from the current transaction 718 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.readOnly()) catch |err| switch (err) { 719 error.NotFound => return false, 720 else => return err, 721 }; 722 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, arena, id)) orelse return false; 723 if (patch_record.removed or patch_record.event.status.kind() != .open) return false; 724 725 // find the newest fork revision when the patch uses a fork 726 var newest: ?evt.PatchRev.WithId = null; 727 if (fork_repo) |repo| { 728 if (evt.currentMoment(repo_opts, repo)) |events| { 729 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, arena) catch |err| blk: { 730 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 731 break :blk null; 732 }; 733 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 734 } 735 736 // compare the selected revision and target against the cache 737 const patch = patch_record.event; 738 const revision = patch.revision orelse return false; 739 const target_oid = try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 740 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 741 const cached = try readMergeCheck(repo_opts, target_events, arena, id); 742 const current = if (patch.source_branch != null) 743 try branchCurrent(repo_opts, state.readOnly(), io, arena, patch) 744 else if (newest) |latest| 745 std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) 746 else 747 false; 748 749 // run trial merges only for a current revision with an unresolved check 750 if (current and target_oid != null) { 751 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return false; 752 check.result = try trialMergeCheck(repo_opts, state, io, arena.child_allocator, &check, fork_repo); 753 } 754 755 // persist the result only when it differs from the cache 756 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return false; 757 try saveMergeCheck(repo_opts, state.extra.moment.*, id, check); 758 return true; 759 } 760 761 fn trialMergeCheck( 762 comptime repo_opts: rp.RepoOpts(.xit), 763 state: rp.Repo(.xit, repo_opts).State(.read_write), 764 io: std.Io, 765 allocator: std.mem.Allocator, 766 check: *const MergeCheck, 767 fork_repo: ?*rp.Repo(.xit, repo_opts), 768 ) !Mergeability { 769 // freeze the parent state so trial writes copy its nodes 770 const moment = state.extra.moment; 771 const snapshot = moment.slot(); 772 // TODO: use an xitdb savepoint to also reclaim trial bytes on rollback. 773 // restoring the root leaves the appended data unused until gc. 774 try state.core.db.freeze(); 775 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 776 777 // keep the trial result in memory while discarding its state changes 778 const result = calculateMergeCheck(repo_opts, state, io, allocator, check, fork_repo); 779 780 // restore the parent state before handling any trial error 781 moment.cursor.write(.{ .slot = snapshot }) catch return error.MergeCheckRestoreFailed; 782 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 783 784 // report failed trials as unknown after the parent state is restored 785 return result catch |err| { 786 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 787 return .{}; 788 }; 789 } 790 791 // queue `oid` and its history on `objects`, which reads from `source`, minus 792 // what `holder` already has. a repo and its forks start as copies of each other, 793 // so walking back to the newest commit `holder` has usually skips nearly all of it. 794 pub fn includeMissing( 795 comptime repo_opts: rp.RepoOpts(.xit), 796 objects: *obj.ObjectIterator(.xit, repo_opts), 797 holder: rp.Repo(.xit, repo_opts).State(.read_only), 798 source: rp.Repo(.xit, repo_opts).State(.read_only), 799 io: std.Io, 800 allocator: std.mem.Allocator, 801 oid: *const [hash.hexLen(repo_opts.hash)]u8, 802 ) !void { 803 var held_oid = oid.*; 804 while (true) { 805 var reader_or_err = obj.ObjectReader(.xit, repo_opts).init(holder, io, allocator, &held_oid); 806 if (reader_or_err) |*reader| { 807 reader.deinit(); 808 break; 809 } else |err| switch (err) { 810 error.ObjectNotFound => {}, 811 else => |e| return e, 812 } 813 var commit = try obj.Object(.xit, repo_opts).init(source, io, allocator, &held_oid); 814 defer commit.deinit(); 815 const parent_oids = commit.content.commit.metadata.parent_oids orelse return objects.include(oid); 816 if (parent_oids.len == 0) return objects.include(oid); 817 held_oid = parent_oids[0]; 818 } 819 if (std.mem.eql(u8, &held_oid, oid)) return; 820 try objects.include(oid); 821 try objects.exclude(&held_oid); 822 } 823 824 fn calculateMergeCheck( 825 comptime repo_opts: rp.RepoOpts(.xit), 826 state: rp.Repo(.xit, repo_opts).State(.read_write), 827 io: std.Io, 828 allocator: std.mem.Allocator, 829 check: *const MergeCheck, 830 fork_repo: ?*rp.Repo(.xit, repo_opts), 831 ) !Mergeability { 832 const source = try oidArray(repo_opts.hash, check.revision.source_oid); 833 const squash = try oidArray(repo_opts.hash, check.revision.squash_oid); 834 835 // import fork objects into the temporary trial state 836 if (fork_repo) |repo| { 837 var fork_moment = try repo.core.latestMoment(); 838 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 839 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 840 defer objects.deinit(); 841 try includeMissing(repo_opts, &objects, state.readOnly(), fork_state, io, allocator, &source); 842 try includeMissing(repo_opts, &objects, state.readOnly(), fork_state, io, allocator, &squash); 843 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 844 } 845 846 // check source and squash merges against the same target 847 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 848 return .{ 849 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 850 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 851 }; 852 } 853 854 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 { 855 const DB = rp.Repo(.xit, repo_opts).DB; 856 857 // store the check under the current event history moment 858 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 859 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 860 _ = try last_object_id_cursor.readBytes(&last_object_id); 861 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 862 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 863 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 864 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 865 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 866 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 867 } 868 869 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 { 870 // check that the source branch still points to the selected commit 871 const branch = patch.source_branch orelse return false; 872 const selected = patch.revision orelse return false; 873 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 874 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 875 876 // verify that the stored revision metadata also matches 877 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 878 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 879 return selected.matches(revision); 880 } 881 882 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 883 try evt.PatchRev.validateOid(hash_kind, oid); 884 var result: [hash.hexLen(hash_kind)]u8 = undefined; 885 @memcpy(&result, oid); 886 return result; 887 } 888 889 fn checkCommit( 890 comptime repo_opts: rp.RepoOpts(.xit), 891 state: rp.Repo(.xit, repo_opts).State(.read_write), 892 io: std.Io, 893 allocator: std.mem.Allocator, 894 oid: *const [hash.hexLen(repo_opts.hash)]u8, 895 target: rf.Ref, 896 ) Mergeability.Status { 897 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 898 .kind = .full, 899 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 900 .dry_run = true, 901 }, target, null) catch |err| { 902 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 903 return .unknown; 904 }; 905 defer result.deinit(); 906 907 // translate the dry-run outcome into a cached status 908 return switch (result.result) { 909 .conflict => .conflict, 910 .clean, .success, .nothing, .fast_forward => .clean, 911 }; 912 } 913 914 pub const MergeInput = struct { 915 id: [evt.event_id_size * 2]u8, 916 revision: evt.Patch.MergeRevision, 917 author: evt.CommitAuthor, 918 timestamp: u64, 919 }; 920 921 pub fn publish( 922 comptime repo_opts: rp.RepoOpts(.xit), 923 io: std.Io, 924 allocator: std.mem.Allocator, 925 server: evt.Host.Server, 926 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 927 target_repo: *rp.Repo(.xit, repo_opts), 928 input: PublishInput, 929 ) !void { 930 const patch_id = try evt.parseEventId(&input.id); 931 var arena = std.heap.ArenaAllocator.init(allocator); 932 defer arena.deinit(); 933 934 // validate the fork ownership and publishing identity 935 var user_repo = (try evt.openUserRepo(io, allocator, server.users_dir, &input.user_id)) orelse return error.InvalidPatchDraft; 936 defer user_repo.deinit(io, allocator); 937 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 938 const user_moment = (try evt.userMoment(&user_repo)) orelse return error.InvalidPatchDraft; 939 const fork_record = (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 940 if (fork_record.removed or !std.mem.eql(u8, &fork_record.event.repo_id, &std.fmt.bytesToHex(input.repo_id, .lower))) return error.InvalidPatchDraft; 941 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 942 if (user.removed or 943 !std.mem.eql(u8, user.event.name, input.author.name) or 944 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 945 946 // read the patch staged in the fork 947 const fork_path = try fork.forkPath(arena.allocator(), server.users_dir, &input.user_id, &patch_id); 948 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 949 defer fork_repo.deinit(io, allocator); 950 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 951 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 952 953 // check whether this patch has already been published 954 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 955 error.NotFound => null, 956 else => |other| return other, 957 }; 958 const existing = if (target_moment) |moment| 959 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 960 else 961 null; 962 if (existing) |record| { 963 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 964 } 965 966 // publish the selected revision unless the draft was already consumed 967 if (local_patch.removed) { 968 if (existing == null) return error.PatchDataUnavailable; 969 } else { 970 var patch = (existing orelse local_patch).event; 971 if (local_patch.event.revision) |selected| { 972 const revision_id = try evt.parseEventId(&selected.id); 973 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 974 if (!selected.matches(revision)) return error.PatchNotPushed; 975 patch.revision = selected; 976 } 977 if (existing == null) patch.status = .open; 978 979 // write the published patch and its forker to the target repository 980 const events = &[_]evt.EventWithId{.{ 981 .id = input.id, 982 .timestamp = input.timestamp, 983 .author = input.author, 984 .event = .{ .patch = patch }, 985 }}; 986 { 987 var checks: MergeCheckInputs(repo_opts) = .{}; 988 defer checks.deinit(io, allocator); 989 try checks.addFork(io, allocator, patch_id, patch, fork_path); 990 const first_parent = try eventsFirstParent(.xit, repo_opts, io, allocator, target_repo); 991 992 const DB = rp.Repo(.xit, repo_opts).DB; 993 const State = rp.Repo(.xit, repo_opts).State; 994 const Ctx = struct { 995 core: *rp.Repo(.xit, repo_opts).Core, 996 io: std.Io, 997 allocator: std.mem.Allocator, 998 events: []const evt.EventWithId, 999 patch_id: [evt.event_id_size]u8, 1000 forker_id: [evt.event_id_size * 2]u8, 1001 checks: *MergeCheckInputs(repo_opts), 1002 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 1003 1004 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1005 var moment = try DB.HashMap(.read_write).init(cursor.*); 1006 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 1007 1008 // code that starts from the target finds the fork through this entry 1009 var config = try xit.config.Config(.xit, repo_opts).init(state.readOnly(), ctx.io, ctx.allocator); 1010 defer config.deinit(); 1011 try config.add(state, ctx.io, .{ .name = &fork.forkerConfigName(&ctx.patch_id), .value = &ctx.forker_id }); 1012 1013 const parent = if (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = evt.events_ref }) == null) ctx.first_parent else null; 1014 try evt.commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, evt.events_ref, ctx.events, parent); 1015 _ = try evt.consumeInTransaction(.repo, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, evt.events_ref); 1016 _ = try ctx.checks.update(state, ctx.io, ctx.allocator); 1017 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = evt.undo_action } }); 1018 } 1019 }; 1020 1021 try target_repo.core.db_file.lock(io, .exclusive); 1022 defer target_repo.core.db_file.unlock(io); 1023 1024 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1025 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1026 .core = &target_repo.core, 1027 .io = io, 1028 .allocator = allocator, 1029 .events = events, 1030 .patch_id = patch_id, 1031 .forker_id = std.fmt.bytesToHex(input.user_id, .lower), 1032 .checks = &checks, 1033 .first_parent = first_parent, 1034 }) catch |err| switch (err) { 1035 error.CancelTransaction => {}, 1036 else => |e| return e, 1037 }; 1038 } 1039 notify.subscribeParticipants(io, allocator, server, target_repo.core.work_path, events); 1040 evt.bumpRepoActivityAt(io, allocator, server, target_repo.core.work_path); 1041 1042 // remove the consumed draft from the fork 1043 try evt.consume(.{ .server = server }, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 1044 .id = input.id, 1045 .timestamp = input.timestamp, 1046 .author = input.author, 1047 .event = .{ .patch = null }, 1048 }}); 1049 } 1050 1051 // mark the fork as published in the forker's user repo 1052 if (fork_record.event.stage == .draft) { 1053 var published = fork_record.event; 1054 published.stage = .publish; 1055 try evt.consume(.{ .server = server }, .user, .xit, evt.user_repo_opts, io, allocator, &user_repo, evt.events_ref, &.{.{ 1056 .id = input.id, 1057 .timestamp = input.timestamp, 1058 .author = input.author, 1059 .event = .{ .fork = published }, 1060 }}); 1061 } 1062 } 1063 1064 pub fn editDraft( 1065 comptime repo_opts: rp.RepoOpts(.xit), 1066 io: std.Io, 1067 allocator: std.mem.Allocator, 1068 users_dir: []const u8, 1069 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1070 input: EditDraftInput, 1071 ) !bool { 1072 // validate the submitted fields before opening repositories 1073 if (!evt.Patch.fieldsValid(input.title, input.labels)) return error.InvalidFields; 1074 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 1075 const patch_id = try evt.parseEventId(&input.id); 1076 var arena = std.heap.ArenaAllocator.init(allocator); 1077 defer arena.deinit(); 1078 1079 // validate the draft ownership and editing identity 1080 { 1081 var user_repo = (try evt.openUserRepo(io, allocator, users_dir, &input.user_id)) orelse return false; 1082 defer user_repo.deinit(io, allocator); 1083 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 1084 const user_moment = (try evt.userMoment(&user_repo)) orelse return false; 1085 const fork_record = (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, &arena, &patch_id)) orelse return false; 1086 if (fork_record.event.stage != .draft) return false; 1087 if (fork_record.removed or !std.mem.eql(u8, &fork_record.event.repo_id, &std.fmt.bytesToHex(input.repo_id, .lower))) return error.InvalidPatchDraft; 1088 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 1089 if (user.removed or 1090 !std.mem.eql(u8, user.event.name, input.author.name) or 1091 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 1092 } 1093 1094 // read the draft patch from its fork 1095 const fork_path = try fork.forkPath(arena.allocator(), users_dir, &input.user_id, &patch_id); 1096 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 1097 defer fork_repo.deinit(io, allocator); 1098 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 1099 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 1100 if (record.removed) return error.PatchDataUnavailable; 1101 1102 // apply the edits and invalidate a revision targeting another branch 1103 var patch = record.event; 1104 patch.title = input.title; 1105 patch.labels = input.labels; 1106 patch.description = input.description; 1107 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 1108 patch.target_branch = input.target_branch; 1109 1110 // commit the updated draft metadata 1111 try evt.consume(.{ .server = .{ .users_dir = users_dir } }, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 1112 .id = input.id, 1113 .timestamp = input.timestamp, 1114 .author = input.author, 1115 .event = .{ .patch = patch }, 1116 }}); 1117 return true; 1118 } 1119 1120 // merge the selected patch revision into its target branch 1121 pub fn merge( 1122 comptime repo_opts: rp.RepoOpts(.xit), 1123 io: std.Io, 1124 allocator: std.mem.Allocator, 1125 server: evt.Host.Server, 1126 target_repo: *rp.Repo(.xit, repo_opts), 1127 input: MergeInput, 1128 ) !void { 1129 const patch_id = try evt.parseEventId(&input.id); 1130 mergeInner(repo_opts, io, allocator, server, target_repo, input, patch_id) catch |err| { 1131 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 1132 refreshMergeability(repo_opts, io, allocator, target_repo, server.users_dir, patch_id); 1133 } 1134 return err; 1135 }; 1136 } 1137 1138 fn mergeInner( 1139 comptime repo_opts: rp.RepoOpts(.xit), 1140 io: std.Io, 1141 allocator: std.mem.Allocator, 1142 server: evt.Host.Server, 1143 target_repo: *rp.Repo(.xit, repo_opts), 1144 input: MergeInput, 1145 patch_id: [evt.event_id_size]u8, 1146 ) !void { 1147 var arena = std.heap.ArenaAllocator.init(allocator); 1148 defer arena.deinit(); 1149 1150 // validate the target patch 1151 const target_moment = try evt.currentMoment(repo_opts, target_repo); 1152 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 1153 if (patch_record.removed) return error.InvalidPatch; 1154 switch (patch_record.event.status) { 1155 .open => {}, 1156 .closed => return error.PatchClosed, 1157 .merged => return error.PatchAlreadyMerged, 1158 } 1159 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 1160 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 1161 1162 // open the fork 1163 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (patch_record.event.source_branch != null) null else blk: { 1164 var config = try target_repo.listConfig(io, allocator); 1165 defer config.deinit(); 1166 const forker_id = (try fork.readForkerId(&config.sections, &patch_id)) orelse return error.PatchDataUnavailable; 1167 const fork_path = try fork.forkPath(arena.allocator(), server.users_dir, &forker_id, &patch_id); 1168 break :blk rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 1169 }; 1170 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1171 1172 // select the commit and merge identity 1173 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 1174 .squash => selected.squash_oid, 1175 .source => selected.source_oid, 1176 }) catch return error.InvalidPatch; 1177 const identity = try arena.allocator().print("{s} <{s}>", .{ input.author.name, input.author.email }); 1178 1179 // merge the code and events in one target transaction 1180 { 1181 const DB = rp.Repo(.xit, repo_opts).DB; 1182 const State = rp.Repo(.xit, repo_opts).State; 1183 const Ctx = struct { 1184 core: *rp.Repo(.xit, repo_opts).Core, 1185 fork_repo: ?*rp.Repo(.xit, repo_opts), 1186 io: std.Io, 1187 allocator: std.mem.Allocator, 1188 patch_id: [evt.event_id_size]u8, 1189 expected_patch: evt.Patch, 1190 target_ref: rf.Ref, 1191 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 1192 revision: evt.Patch.MergeRevision, 1193 identity: []const u8, 1194 author: evt.CommitAuthor, 1195 timestamp: u64, 1196 1197 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1198 var moment = try DB.HashMap(.read_write).init(cursor.*); 1199 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 1200 1201 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 1202 defer check_arena.deinit(); 1203 1204 // require the fork's newest revision while both repos are locked 1205 const selected_revision = ctx.expected_patch.revision orelse unreachable; 1206 const revision_id = try evt.parseEventId(&selected_revision.id); 1207 if (ctx.fork_repo) |repo| { 1208 const fork_moment = try evt.currentMoment(repo_opts, repo); 1209 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 1210 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 1211 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 1212 1213 // require a clean cached result for the selected merge style. 1214 { 1215 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 1216 switch (availability.get(ctx.revision)) { 1217 .clean => {}, 1218 .conflict => return error.MergeConflict, 1219 .unknown => return error.MergeCheckUnavailable, 1220 } 1221 } 1222 1223 // copy the selected commit and its dependencies 1224 if (ctx.fork_repo) |repo| { 1225 var fork_repo_moment = try repo.core.latestMoment(); 1226 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 1227 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 1228 defer objects.deinit(); 1229 try includeMissing(repo_opts, &objects, state.readOnly(), fork_state, ctx.io, ctx.allocator, &ctx.selected_oid); 1230 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 1231 } 1232 1233 // merge the selected commit 1234 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1235 { 1236 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 1237 .kind = .full, 1238 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 1239 .commit_metadata = .{ 1240 .author = ctx.identity, 1241 .committer = ctx.identity, 1242 .message = ctx.expected_patch.title, 1243 .timestamp = ctx.timestamp, 1244 }, 1245 }, ctx.target_ref, null); 1246 defer merge_result.deinit(); 1247 switch (merge_result.result) { 1248 .conflict => return error.MergeConflict, 1249 .success, .fast_forward, .nothing => {}, 1250 .clean => unreachable, 1251 } 1252 } 1253 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1254 1255 // retain the submitted revision and snapshot the merge result 1256 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; 1257 1258 // the merge moved the target branch, so its indexes follow, 1259 // the commit index deriving from the old tip's version 1260 _ = try find.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, null); 1261 _ = try srch_cmmt.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, &.{.{ .old_oid = &before_oid, .new_oid = &after_oid }}, null); 1262 1263 // record the merge as one undoable action. 1264 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 1265 } 1266 }; 1267 1268 // lock the fork before the target for the full merge transaction. 1269 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 1270 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 1271 try target_repo.core.db_file.lock(io, .exclusive); 1272 defer target_repo.core.db_file.unlock(io); 1273 1274 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1275 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1276 .core = &target_repo.core, 1277 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 1278 .io = io, 1279 .allocator = allocator, 1280 .patch_id = patch_id, 1281 .expected_patch = patch_record.event, 1282 .target_ref = target_ref, 1283 .selected_oid = selected_oid, 1284 .revision = input.revision, 1285 .identity = identity, 1286 .author = input.author, 1287 .timestamp = input.timestamp, 1288 }); 1289 } 1290 evt.bumpRepoActivityAt(io, allocator, server, target_repo.core.work_path); 1291 1292 // refresh other patches affected by the updated target branch. 1293 refreshOpenMergeability(repo_opts, io, allocator, target_repo, server.users_dir, null, null); 1294 } 1295 1296 // merge a published patch and remove its fork 1297 pub fn mergeAndRemoveFork( 1298 comptime repo_opts: rp.RepoOpts(.xit), 1299 io: std.Io, 1300 allocator: std.mem.Allocator, 1301 server: evt.Host.Server, 1302 target_repo: *rp.Repo(.xit, repo_opts), 1303 input: MergeInput, 1304 ) !void { 1305 try merge(repo_opts, io, allocator, server, target_repo, input); 1306 var arena = std.heap.ArenaAllocator.init(allocator); 1307 defer arena.deinit(); 1308 1309 // remove fork data only for patches backed by a fork 1310 const patch_id = try evt.parseEventId(&input.id); 1311 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &patch_id)) orelse return error.InvalidPatch; 1312 if (record.event.source_branch != null) return; 1313 // a patch from another instance has no fork here 1314 const forker_id = blk: { 1315 var config = try target_repo.listConfig(io, allocator); 1316 defer config.deinit(); 1317 break :blk (try fork.readForkerId(&config.sections, &patch_id)) orelse return; 1318 }; 1319 try fork.remove(io, allocator, server.users_dir, &forker_id, &input.id, input.author); 1320 } 1321 1322 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1323 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1324 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1325 const name = std.mem.trimEnd(u8, line[0..open], " "); 1326 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1327 return .{ .name = name, .email = line[open + 1 .. close] }; 1328 } 1329 1330 // import a revision after detecting a client-side merge 1331 fn importMerged( 1332 comptime repo_opts: rp.RepoOpts(.xit), 1333 state: rp.Repo(.xit, repo_opts).State(.read_write), 1334 db: *evt.EventDB(repo_opts.hash), 1335 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1336 io: std.Io, 1337 allocator: std.mem.Allocator, 1338 users_dir: []const u8, 1339 patch_id: *const [evt.event_id_size]u8, 1340 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1341 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1342 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1343 ) !void { 1344 var arena = std.heap.ArenaAllocator.init(allocator); 1345 defer arena.deinit(); 1346 1347 // identify which selected revision was merged by the client. 1348 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1349 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1350 const selected = record.event.revision orelse return; 1351 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; 1352 1353 // open the fork when the revision is not stored in the target repository. 1354 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (record.event.source_branch != null) null else blk: { 1355 var config = try xit.config.Config(.xit, repo_opts).init(state.readOnly(), io, allocator); 1356 defer config.deinit(); 1357 const forker_id = (try fork.readForkerId(&config.sections, patch_id)) orelse return error.PatchDataUnavailable; 1358 const fork_path = try fork.forkPath(arena.allocator(), users_dir, &forker_id, patch_id); 1359 break :blk try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 1360 }; 1361 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1362 1363 // import the revision and record the client-side merge. 1364 _ = 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); 1365 } 1366 1367 // import the revision and mark its patch merged in the current transaction 1368 fn importMergedRevision( 1369 comptime repo_opts: rp.RepoOpts(.xit), 1370 state: rp.Repo(.xit, repo_opts).State(.read_write), 1371 db: *evt.EventDB(repo_opts.hash), 1372 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1373 io: std.Io, 1374 allocator: std.mem.Allocator, 1375 fork_repo: ?*rp.Repo(.xit, repo_opts), 1376 patch_id: *const [evt.event_id_size]u8, 1377 merged: struct { 1378 revision: evt.Patch.MergeRevision, 1379 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1380 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1381 }, 1382 expected_patch: ?evt.Patch, 1383 merged_author: ?evt.CommitAuthor, 1384 merged_timestamp: u64, 1385 ) !bool { 1386 const DB = evt.EventDB(repo_opts.hash); 1387 var arena = std.heap.ArenaAllocator.init(allocator); 1388 defer arena.deinit(); 1389 1390 // read the patch and reject outdated or conflicting merge requests. 1391 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1392 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1393 const selected = patch_record.event.revision orelse return false; 1394 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1395 if (expected_patch) |expected| { 1396 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1397 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1398 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1399 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1400 } 1401 } 1402 const revision_id = try evt.parseEventId(&selected.id); 1403 1404 // resolve the selected revision from the target or its fork. 1405 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1406 const revision = (if (fork_repo) |repo| 1407 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1408 else 1409 current_revision) orelse return false; 1410 if (!selected.matches(revision)) return false; 1411 1412 // read the original revision commit and author. 1413 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1414 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 } }; 1415 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1416 if (revision.event_oid.len != event_oid.len) return false; 1417 @memcpy(&event_oid, revision.event_oid); 1418 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1419 defer event_object.deinit(); 1420 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1421 1422 // retain the submitted revision if the target has not imported it yet. 1423 var events_buffer: [3]evt.EventWithId = undefined; 1424 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1425 var tree_entries: [2]evt.EventTreeEntry = undefined; 1426 const needs_import = if (current_revision) |existing| existing.removed else true; 1427 if (needs_import) { 1428 tree_entries = .{ 1429 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1430 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1431 }; 1432 events.appendAssumeCapacity(.{ 1433 .id = selected.id, 1434 .timestamp = event_object.content.commit.metadata.timestamp, 1435 .author = original_author, 1436 .tree_entries = &tree_entries, 1437 .event = .{ .patchrev = revision.event }, 1438 }); 1439 } else { 1440 const existing = current_revision orelse unreachable; 1441 if (!selected.matches(existing)) return error.InvalidPatch; 1442 } 1443 1444 // snapshot the merge result and mark the patch as merged. 1445 { 1446 const author = merged_author orelse original_author; 1447 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1448 var patch = patch_record.event; 1449 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1450 events.appendAssumeCapacity(result.event); 1451 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1452 events.appendAssumeCapacity(.{ 1453 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1454 .timestamp = timestamp, 1455 .author = author, 1456 .event = .{ .patch = patch }, 1457 }); 1458 } 1459 1460 // commit and consume the revision and patch events together. 1461 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1462 _ = try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref); 1463 return true; 1464 } 1465 1466 // find patches merged by commits received in a push 1467 pub fn detectMerged( 1468 comptime repo_opts: rp.RepoOpts(.xit), 1469 state: rp.Repo(.xit, repo_opts).State(.read_write), 1470 db: *evt.EventDB(repo_opts.hash), 1471 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1472 io: std.Io, 1473 allocator: std.mem.Allocator, 1474 users_dir: []const u8, 1475 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1476 error_writer: *std.Io.Writer, 1477 ) !void { 1478 const DB = evt.EventDB(repo_opts.hash); 1479 var arena = std.heap.ArenaAllocator.init(allocator); 1480 defer arena.deinit(); 1481 1482 // read the revision index used to identify merged patches. 1483 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1484 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1485 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1486 1487 // ignore event refs and inspect only changed branch tips. 1488 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1489 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1490 const heads_prefix = "refs/heads/"; 1491 for (updates) |update| { 1492 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1493 std.mem.eql(u8, update.ref_name, events_ref_path) or 1494 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1495 1496 // validate the ref tips and skip branch deletions. 1497 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1498 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1499 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1500 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1501 @memcpy(&old_oid, update.old_oid); 1502 @memcpy(&new_oid, update.new_oid); 1503 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1504 1505 // traverse commits introduced by this branch update. 1506 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1507 defer commits.deinit(); 1508 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1509 var targets: std.ArrayList(struct { 1510 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1511 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1512 }) = .empty; 1513 1514 // collect merge boundaries along the target's first-parent history. 1515 { 1516 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1517 defer first_parents.deinit(); 1518 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1519 try first_parents.include(&new_oid); 1520 while (try first_parents.next(arena.allocator())) |commit| { 1521 defer commit.deinit(); 1522 try targets.append(arena.allocator(), .{ 1523 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1524 .after_oid = commit.oid, 1525 }); 1526 } 1527 } 1528 1529 // visit target commits oldest first, attributing each revision to the 1530 // commit that introduced it; the shared iterator visits each ancestor once 1531 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1532 while (targets.pop()) |target| { 1533 try commits.include(&target.after_oid); 1534 while (try commits.next(arena.allocator())) |commit| { 1535 defer commit.deinit(); 1536 1537 // find patches whose selected revision matches this commit. 1538 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1539 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1540 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1541 var ids_iter = try ids.iterator(); 1542 while (try ids_iter.next()) |cursor| { 1543 const pair = try cursor.readKeyValuePair(); 1544 var patch_id: [evt.event_id_size]u8 = undefined; 1545 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1546 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1547 1548 // a fast-forward has no recorded merge boundary; use the old ref tip 1549 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1550 importMerged(repo_opts, state, db, moment, io, allocator, users_dir, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1551 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1552 continue; 1553 }; 1554 } 1555 } 1556 } 1557 } 1558 } 1559