╭ Patches.zig ──────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const evt = @import("../../event.zig"); 4 const ui = @import("../../ui.zig"); 5 const xit = @import("xit"); 6 const rp = xit.repo; 7 const hash = xit.hash; 8 const xitui = xit.xitui; 9 const wgt = xitui.widget; 10 const diff3 = @import("../../diff3.zig"); 11 const Comment = @import("Comment.zig"); 12 const Attachment = @import("Attachment.zig"); 13 const thread = ui.widget.thread; 14 const fork = @import("../../fork.zig"); 15 const pch = @import("../../patch.zig"); 16 17 const wasm = builtin.target.cpu.arch == .wasm32; 18 19 pub const Source = struct { 20 box: wgt.Box(ui.Widget), 21 session: *ui.Session, 22 selectors: std.enums.EnumMap(Kind, usize), 23 24 pub const Kind = enum { fork, branch }; 25 26 pub fn init(allocator: std.mem.Allocator, session: *ui.Session, initial: []const u8, initial_kind: Kind) !Source { 27 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 28 errdefer box.deinit(allocator); 29 const selected: Kind = if (session.data.host_kind == .local) .branch else initial_kind; 30 var selectors: std.enums.EnumMap(Kind, usize) = .{}; 31 if (session.data.host_kind != .local) { 32 for (std.enums.values(Kind)) |kind| { 33 const label = switch (kind) { 34 .fork => "from a new fork", 35 .branch => "from an existing branch", 36 }; 37 var selector = try wgt.TextBox.init(allocator, label, .{ .border_style = .single, .round_corners = true, .wrap_kind = .none }); 38 errdefer selector.deinit(allocator); 39 selector.getFocus().mode = .all; 40 try box.children.put(allocator, selector.getFocus().id, .{ .widget = .{ .text_box = selector }, .rect = null, .min_size = .{ .width = label.len + 2, .height = 3 } }); 41 selectors.put(kind, selector.getFocus().id); 42 } 43 } 44 var input_box = try wgt.TextInput.init(allocator, .{ .label = " source branch ", .name = "source_branch", .round_corners = true, .visible_width = null, .render_content = session.is_terminal }); 45 errdefer input_box.deinit(allocator); 46 input_box.getFocus().mode = .all; 47 try input_box.setContent(allocator, initial); 48 try box.children.put(allocator, input_box.getFocus().id, .{ .widget = .{ .text_input = input_box }, .rect = null, .min_size = .{ .width = 15, .height = 3 } }); 49 box.getFocus().child_id = selectors.get(selected) orelse input_box.getFocus().id; 50 return .{ .box = box, .session = session, .selectors = selectors }; 51 } 52 53 pub fn field(self: *Source) *wgt.TextInput { 54 for (self.box.children.values()) |*child| switch (child.widget) { 55 .text_input => |*text_input| return text_input, 56 else => {}, 57 }; 58 unreachable; 59 } 60 61 // the selection is whichever selector focus last landed on, like every 62 // other selection in the ui, so a click (which only moves focus on the 63 // web) selects. the branch text input is only reachable while branch is 64 // selected, so focus on it means branch too. 65 pub fn selectedKind(self: *Source) Kind { 66 const current = self.box.getFocus().child_id orelse return .branch; 67 var iter = self.selectors.iterator(); 68 while (iter.next()) |selector| { 69 if (selector.value.* == current) return selector.key; 70 } 71 return .branch; 72 } 73 74 pub fn deinit(self: *Source, allocator: std.mem.Allocator) void { 75 self.box.deinit(allocator); 76 } 77 78 pub fn clearGrid(self: *Source) void { 79 self.box.clearGrid(); 80 } 81 82 pub fn getGrid(self: Source) ?xitui.grid.Grid { 83 return self.box.getGrid(); 84 } 85 86 pub fn getFocus(self: *Source) *xitui.focus.Focus { 87 return self.box.getFocus(); 88 } 89 90 pub fn build(self: *Source, allocator: std.mem.Allocator, constraint: xitui.layout.Constraint, root_focus: *xitui.focus.Focus) !void { 91 self.clearGrid(); 92 const selected = self.selectedKind(); 93 for (self.box.children.keys(), self.box.children.values()) |id, *child| switch (child.widget) { 94 .text_input => child.hidden = selected == .fork, 95 .text_box => |*selector| selector.options.border_style = if (id == self.selectors.get(selected)) .single else .hidden, 96 else => {}, 97 }; 98 try self.box.build(allocator, constraint, root_focus); 99 if (!self.session.is_terminal) { 100 try self.session.text_inputs.put(self.session.arena.allocator(), self.field().getFocus().id, self.field()); 101 } 102 } 103 104 pub fn input(self: *Source, allocator: std.mem.Allocator, key: xitui.input.Key, root_focus: *xitui.focus.Focus) !void { 105 const current = self.box.getFocus().child_id orelse return; 106 const text_input = self.field(); 107 if (current == text_input.getFocus().id) { 108 if (key == .arrow_left) { 109 if (self.selectors.get(.branch)) |id| { 110 root_focus.setFocus(id); 111 return; 112 } 113 } 114 return text_input.input(allocator, key, root_focus); 115 } 116 117 var iter = self.selectors.iterator(); 118 var previous: ?Kind = null; 119 while (iter.next()) |selector| { 120 if (selector.value.* == current) break; 121 previous = selector.key; 122 } else return; 123 switch (key) { 124 .arrow_left => if (previous) |kind| root_focus.setFocus(self.selectors.get(kind) orelse return), 125 // past the last selector (branch) lies its text input 126 .arrow_right => if (iter.next()) |next| root_focus.setFocus(next.value.*) else root_focus.setFocus(text_input.getFocus().id), 127 .enter => if (self.selectedKind() == .branch) root_focus.setFocus(text_input.getFocus().id), 128 else => {}, 129 } 130 } 131 }; 132 133 // how many patches one window shows before a "next" link appears. 134 pub const page_size = 20; 135 136 // how many labels the labels view shows at most. 137 pub const max_labels = 1000; 138 139 // one patch from the repo's consumed event database, with its hex event id 140 // (the id lives in the event envelope, not the payload). 141 pub const PatchWithId = struct { 142 id: []const u8, 143 record: evt.Patch.Record, 144 // the creation commit's author 145 author: ui.Author = .unknown, 146 // whether the patch has an unresolved merge conflict 147 conflicted: bool = false, 148 comments: Comment.Window = .empty, 149 attachments: []const Attachment.WithId = &.{}, 150 draft: bool = false, 151 revision_oid: []const u8 = "", 152 base_oid: []const u8 = "", 153 commit_count: ?u64 = null, 154 no_changes: bool = false, 155 fork_exists: bool = false, 156 // the name of the user whose fork backs the patch 157 forker: []const u8 = "", 158 mergeability: pch.Mergeability = .{}, 159 }; 160 161 pub const Entry = PatchWithId; 162 163 // one side of a conflicted field: its value and who set it 164 pub const Side = struct { 165 text: []const u8, 166 author: ui.Author = .unknown, 167 }; 168 169 pub const FieldConflict = struct { 170 ours: Side, 171 theirs: Side, 172 }; 173 174 // the selected patch's conflict, read for the resolve view. ours is the live 175 // record; the chunks split the description against the merge base. 176 pub const Conflict = struct { 177 title: ?FieldConflict = null, 178 labels: ?FieldConflict = null, 179 status: ?FieldConflict = null, 180 revision: ?FieldConflict = null, 181 target_branch: ?FieldConflict = null, 182 description: ?struct { 183 chunks: []const diff3.Chunk, 184 ours_author: ui.Author = .unknown, 185 theirs_author: ui.Author = .unknown, 186 } = null, 187 }; 188 189 // one status's windowed listing. 190 pub const Window = struct { 191 items: []const PatchWithId, 192 // the id of the previous window's first patch, or null when this window 193 // is already the first. 194 prev_id: ?[]const u8, 195 // the id of the next window's first patch, or null when this is the last 196 // window. 197 next_id: ?[]const u8, 198 // how many patches the listing holds across all windows. 199 count: usize, 200 // whether a search stopped counting at its cap, so `count` is a floor. 201 more: bool = false, 202 203 pub const empty: Window = .{ .items = &.{}, .prev_id = null, .next_id = null, .count = 0 }; 204 }; 205 206 // "owner/name", so the view can build /repo/owner/name/patches/... links. 207 identity: []const u8, 208 default_target_branch: []const u8 = "", 209 // the url-encoded label the lists are filtered to ("" = unfiltered). 210 label: []const u8, 211 // the decoded query the lists are filtered to, or null when unfiltered. 212 search: ?[]const u8 = null, 213 // the hex event id of the patch its status's window is rooted at ("" = the 214 // first window), mirrored into the url. 215 selected_id: []const u8, 216 // the comment shown in the selected patch's detail pane. 217 comment_id: []const u8, 218 // the selected patch's comment window (0 = the first window). 219 comments_start: usize, 220 // the selected comment and its immediate replies. 221 comment_page: ?Comment.Permalink = null, 222 // who the page is built for, null when logged out 223 viewer: ?ui.Viewer = null, 224 open: Window, 225 closed: Window, 226 merged: Window, 227 drafts: Window, 228 // the conflicted patches' listing; its count also gates the conflicts tab. 229 conflicts: Window, 230 // the selected patch's conflict, set when the page shows the resolve view. 231 conflict: ?Conflict = null, 232 // the resolve view's comma-separated fields prefilled from their side, 233 // mirrored from the url. 234 theirs_picks: []const u8 = "", 235 // the view the page shows initially (a selected patch's status overrides the route's) 236 view: ui.RoutablePage.PatchesView, 237 // the /description page: the detail pane shows the selected patch's whole 238 // description behind a back link. 239 description_page: bool = false, 240 // every label in the repo, in sorted order, for the labels view. 241 labels: []const []const u8, 242 // the on-disk repo this page was read from, for the terminal submit path 243 // (the web posts the new-patch form to the patch route instead). 244 repo_source: ?ui.RepoSource = null, 245 repo_id: ?[evt.event_id_size]u8 = null, 246 247 const Self = @This(); 248 249 pub const Event = evt.Patch; 250 pub const Status = evt.Patch.StatusKind; 251 pub const ViewKind = ui.RoutablePage.PatchesView; 252 pub const thread_name = "patch"; 253 pub const header_widget_name = "repo_patches_header"; 254 255 pub fn statusKind(event: Event) Status { 256 return event.status.kind(); 257 } 258 259 pub fn listRoute(identity: []const u8, status: Status, label: []const u8, selected: []const u8) ?ui.RoutablePage { 260 return ui.RoutablePage.repoPatchesRoute(identity, status, label, selected); 261 } 262 263 // a fork route's identity names the forker and the target repo 264 fn forkIdentity(buffer: []u8, identity: []const u8, entry: PatchWithId) ![]const u8 { 265 const repo_identity = ui.RoutablePage.RepoIdentity.parse(identity) orelse return error.RouteTooLong; 266 return std.fmt.bufPrint(buffer, "{s}/{s}", .{ entry.forker, repo_identity.name }) catch error.RouteTooLong; 267 } 268 269 pub fn commitsRoute(identity: []const u8, entry: PatchWithId) !?ui.RoutablePage { 270 var buffer: [ui.RoutablePage.repo_identity_max_len]u8 = undefined; 271 if (entry.fork_exists and entry.record.event.status.kind() != .merged) 272 return ui.RoutablePage.forkCommitsRoute(try forkIdentity(&buffer, identity, entry), entry.id, "", 0, "") orelse error.RouteTooLong; 273 if (entry.revision_oid.len == 0 or entry.base_oid.len == 0) return null; 274 return ui.RoutablePage.repoCommitsRoute(identity, .object, entry.revision_oid, 0, "", entry.base_oid) orelse error.RouteTooLong; 275 } 276 277 pub fn diffRoute(identity: []const u8, entry: PatchWithId) !?ui.RoutablePage { 278 const patch = entry.record.event; 279 const revision_id = switch (patch.status) { 280 // merged patches show what actually landed, including conflict resolutions 281 .merged => |merged| merged.patchrev_id, 282 .open, .closed => blk: { 283 if (entry.fork_exists) { 284 var buffer: [ui.RoutablePage.repo_identity_max_len]u8 = undefined; 285 return ui.RoutablePage.forkDiffRoute(try forkIdentity(&buffer, identity, entry), entry.id, 0, "") orelse error.RouteTooLong; 286 } 287 if (patch.source_branch == null) return null; 288 break :blk (patch.revision orelse return null).id; 289 }, 290 }; 291 return ui.RoutablePage.repoPatchRevDiffRoute(identity, &revision_id, 0, "") orelse error.RouteTooLong; 292 } 293 294 pub fn draftsRoute(identity: []const u8) ?ui.RoutablePage { 295 return ui.RoutablePage.repoPatchesDraftsRoute(identity); 296 } 297 298 pub fn conflictsRoute(identity: []const u8, selected: []const u8) ?ui.RoutablePage { 299 return ui.RoutablePage.repoPatchesConflictsRoute(identity, selected); 300 } 301 302 pub fn resolveRoute(identity: []const u8, selected: []const u8, picks: []const u8) ?ui.RoutablePage { 303 return ui.RoutablePage.repoPatchesResolveRoute(identity, selected, picks); 304 } 305 306 pub fn publishRoute(identity: []const u8, selected: []const u8) ?ui.RoutablePage { 307 return ui.RoutablePage.repoPatchPublishRoute(identity, selected); 308 } 309 310 pub fn mergeRoute(identity: []const u8, selected: []const u8) ?ui.RoutablePage { 311 return ui.RoutablePage.repoPatchMergeRoute(identity, selected); 312 } 313 314 pub fn canMerge(entry: Entry, session: *const ui.Session) bool { 315 return !entry.draft and 316 (entry.fork_exists or entry.record.event.source_branch != null) and 317 !entry.conflicted and 318 entry.record.event.revision != null and 319 entry.record.event.status.kind() == .open and 320 session.data.host_kind == .server; 321 } 322 323 pub fn create( 324 data: *const Self, 325 session: *ui.Session, 326 allocator: std.mem.Allocator, 327 actor: ui.Actor, 328 title: []const u8, 329 labels: []const u8, 330 description: []const u8, 331 target_branch: []const u8, 332 source_branch: ?[]const u8, 333 ) ![evt.event_id_size * 2]u8 { 334 if (!evt.Patch.fieldsValid(title, labels)) return error.InvalidFields; 335 const io = session.io orelse return error.NotFound; 336 const repo_source = data.repo_source orelse return error.NotFound; 337 var id_bytes: [evt.event_id_size]u8 = undefined; 338 io.random(&id_bytes); 339 const id = std.fmt.bytesToHex(id_bytes, .lower); 340 if (source_branch) |branch| { 341 switch (repo_source.repo_kind) { 342 inline else => |repo_kind| { 343 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, repo_source.localInitOpts()); 344 defer any_repo.deinit(io, allocator); 345 switch (any_repo) { 346 inline else => |*repo| try pch.writeBranchPatch(session.eventHost(), repo_kind, repo.self_repo_opts, io, allocator, repo, id, .{ 347 .title = title, 348 .labels = labels, 349 .description = description, 350 .target_branch = target_branch, 351 .source_branch = branch, 352 }, null, actor.author), 353 } 354 }, 355 } 356 return id; 357 } 358 if (session.data.host_kind == .local) return error.InvalidSourceBranch; 359 const users_dir = session.users_dir orelse return error.NotFound; 360 const user_id = actor.user_id orelse return error.NotFound; 361 const repo_id = data.repo_id orelse return error.NotFound; 362 const repo_user_id = actor.repo_user_id orelse return error.NotFound; 363 if (!evt.Patch.branchValid(target_branch) or !try repo_source.hasBranch(io, allocator, target_branch)) return error.InvalidTargetBranch; 364 const fork_path = try fork.create(.{}, io, allocator, users_dir, .{ 365 .id = id, 366 .user_id = user_id, 367 .repo_id = repo_id, 368 .repo_user_id = repo_user_id, 369 .title = title, 370 .description = description, 371 .labels = labels, 372 .target_branch = target_branch, 373 .author = actor.author, 374 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 375 }); 376 allocator.free(fork_path); 377 return id; 378 } 379 380 pub fn publishDraft(data: *const Self, session: *ui.Session, allocator: std.mem.Allocator, author: evt.CommitAuthor, id: []const u8) !void { 381 const io = session.io orelse return error.NotFound; 382 const users_dir = session.users_dir orelse return error.NotFound; 383 const admin_repo = session.admin_repo orelse return error.NotFound; 384 const repo_source = data.repo_source orelse return error.NotFound; 385 const repo_id = data.repo_id orelse return error.NotFound; 386 const user_id = session.userId() orelse return error.NotFound; 387 const patch_id = evt.parseEventId(id) catch return error.NotFound; 388 389 const id_hex = std.fmt.bytesToHex(patch_id, .lower); 390 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, repo_source.localInitOpts()); 391 defer target_repo.deinit(io, allocator); 392 switch (target_repo) { 393 inline else => |*repo| try pch.publish(repo.self_repo_opts, io, allocator, users_dir, admin_repo, repo, .{ 394 .id = id_hex, 395 .user_id = user_id, 396 .repo_id = repo_id, 397 .author = author, 398 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 399 }), 400 } 401 } 402 403 pub fn mergePatch(data: *const Self, session: *ui.Session, allocator: std.mem.Allocator, author: evt.CommitAuthor, id: []const u8, revision: evt.Patch.MergeRevision) !void { 404 const io = session.io orelse return error.NotFound; 405 const users_dir = session.users_dir orelse return error.NotFound; 406 const repo_source = data.repo_source orelse return error.NotFound; 407 if (repo_source.repo_kind != .xit) return error.NotFound; 408 const patch_id = evt.parseEventId(id) catch return error.NotFound; 409 410 const id_hex = std.fmt.bytesToHex(patch_id, .lower); 411 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, repo_source.localInitOpts()); 412 defer target_repo.deinit(io, allocator); 413 switch (target_repo) { 414 inline else => |*repo| try pch.mergeAndRemoveFork(repo.self_repo_opts, io, allocator, users_dir, repo, .{ 415 .id = id_hex, 416 .revision = revision, 417 .author = author, 418 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 419 }), 420 } 421 } 422 423 pub fn editDraft( 424 data: *const Self, 425 session: *ui.Session, 426 allocator: std.mem.Allocator, 427 author: evt.CommitAuthor, 428 id: []const u8, 429 title: []const u8, 430 labels: []const u8, 431 description: []const u8, 432 target_branch: []const u8, 433 ) !void { 434 const io = session.io orelse return error.NotFound; 435 const users_dir = session.users_dir orelse return error.NotFound; 436 const admin_repo = session.admin_repo orelse return error.NotFound; 437 const repo_id = data.repo_id orelse return error.NotFound; 438 const repo_source = data.repo_source orelse return error.NotFound; 439 const user_id = session.userId() orelse return error.NotFound; 440 const patch_id = evt.parseEventId(id) catch return error.NotFound; 441 if (!evt.Patch.branchValid(target_branch) or !try repo_source.hasBranch(io, allocator, target_branch)) return error.InvalidTargetBranch; 442 443 const id_hex = std.fmt.bytesToHex(patch_id, .lower); 444 if (!try pch.editDraft(.{}, io, allocator, users_dir, admin_repo, .{ 445 .id = id_hex, 446 .user_id = user_id, 447 .repo_id = repo_id, 448 .title = title, 449 .labels = labels, 450 .description = description, 451 .target_branch = target_branch, 452 .author = author, 453 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 454 })) return error.NotFound; 455 } 456 457 pub fn removeDraft(session: *ui.Session, allocator: std.mem.Allocator, author: evt.CommitAuthor, id: *const [evt.event_id_size]u8) !void { 458 const io = session.io orelse return error.NotFound; 459 const users_dir = session.users_dir orelse return error.NotFound; 460 const user_id = session.userId() orelse return error.NotFound; 461 462 const id_hex = std.fmt.bytesToHex(id.*, .lower); 463 try fork.remove(io, allocator, users_dir, &user_id, &id_hex, author); 464 } 465 466 // `status`'s windowed listing. 467 pub fn window(self: *const Self, status: Status) *const Window { 468 return switch (status) { 469 .open => &self.open, 470 .closed => &self.closed, 471 .merged => &self.merged, 472 }; 473 } 474 475 // whether `field` (a field name or "d<n>" hunk name) is listed in the url's 476 // theirs: picks. 477 pub fn theirsPicked(self: *const Self, field: []const u8) bool { 478 var it = std.mem.splitScalar(u8, self.theirs_picks, ','); 479 while (it.next()) |pick| { 480 if (std.mem.eql(u8, pick, field)) return true; 481 } 482 return false; 483 } 484 485 // the patch `selected_id` names, in whichever window holds it. 486 pub fn selectedThread(self: *const Self) ?*const PatchWithId { 487 if (self.selected_id.len == 0) return null; 488 for ([_]*const Window{ &self.open, &self.closed, &self.merged, &self.drafts }) |win| { 489 for (win.items) |*entry| { 490 if (std.mem.eql(u8, entry.id, self.selected_id)) return entry; 491 } 492 } 493 return null; 494 } 495 496 // an empty listing, for the wasm / no-repo paths. 497 pub fn emptyResult(aa: std.mem.Allocator, identity: []const u8, label: []const u8, search: []const u8, selected_id: []const u8, comment_id: []const u8, comments_start: usize, theirs_picks: []const u8, view: ui.RoutablePage.PatchesView) !Self { 498 return .{ 499 .identity = try aa.dupe(u8, identity), 500 .default_target_branch = "", 501 .label = try aa.dupe(u8, label), 502 .search = if (search.len == 0) null else std.Uri.percentDecodeInPlace(try aa.dupe(u8, search)), 503 .selected_id = try aa.dupe(u8, selected_id), 504 .comment_id = try aa.dupe(u8, comment_id), 505 .comments_start = comments_start, 506 .open = .empty, 507 .closed = .empty, 508 .merged = .empty, 509 .drafts = .empty, 510 .conflicts = .empty, 511 .theirs_picks = try aa.dupe(u8, theirs_picks), 512 // a description url shows a status list, the patch's own status 513 // picking it once the patch is read; conflicts and resolve urls also 514 // start there, upgraded by init when the conflict data exists. 515 .view = switch (view) { 516 .description, .conflicts, .resolve => .open, 517 else => view, 518 }, 519 .description_page = view == .description, 520 .labels = &.{}, 521 }; 522 } 523 524 pub fn detailResult(aa: std.mem.Allocator, identity: []const u8, entry: PatchWithId) !Self { 525 var result = try emptyResult(aa, identity, "", "", entry.id, "", 0, "", .open); 526 const items = try aa.dupe(PatchWithId, &.{entry}); 527 const detail_window = Window{ .items = items, .prev_id = null, .next_id = null, .count = 1 }; 528 if (entry.draft) { 529 result.drafts = detail_window; 530 result.view = .drafts; 531 } else switch (entry.record.event.status) { 532 .open => result.open = detail_window, 533 .closed => { 534 result.closed = detail_window; 535 result.view = .closed; 536 }, 537 .merged => { 538 result.merged = detail_window; 539 result.view = .merged; 540 }, 541 } 542 return result; 543 } 544 545 // read one window per status of an opened repo's patches (filtered to `label` 546 // when set), ordered by creation (newest first). the window of the patch 547 // `selected_id` names starts at it ("" = the beginning). a git repo reads the 548 // event db next to it (synced from the events branch on each page build); a 549 // xit repo reads its own db. 550 pub fn init( 551 comptime repo_kind: rp.RepoKind, 552 comptime repo_opts: rp.RepoOpts(repo_kind), 553 arena: *std.heap.ArenaAllocator, 554 repo: *rp.Repo(repo_kind, repo_opts), 555 io: std.Io, 556 // the admin db's moment, for resolving author emails to user names (null 557 // in local mode, which has no users) 558 admin_moment: ?evt.AdminDB.HashMap(.read_only), 559 session: *ui.Session, 560 repo_id_maybe: ?[evt.event_id_size]u8, 561 identity: []const u8, 562 target_branch: []const u8, 563 label: []const u8, 564 search: []const u8, 565 selected_id: []const u8, 566 comment_id: []const u8, 567 comments_start: usize, 568 theirs_picks: []const u8, 569 view: ui.RoutablePage.PatchesView, 570 viewer: ?ui.Viewer, 571 ) !Self { 572 const allowed_view: ui.RoutablePage.PatchesView = if (session.local != null and view == .drafts) .open else view; 573 var empty = try emptyResult(arena.allocator(), identity, label, search, selected_id, comment_id, comments_start, theirs_picks, allowed_view); 574 empty.default_target_branch = try arena.allocator().dupe(u8, target_branch); 575 576 const aa = arena.allocator(); 577 const DB = evt.EventDB(repo_opts.hash); 578 const rooted = empty.selected_id.len != 0; 579 const labeled = empty.label.len != 0; 580 const drafts_window = if (admin_moment) |admin| 581 if (repo_id_maybe) |repo_id| 582 if (session.data.user_id != null and session.users_dir != null) 583 try loadDraftWindow(repo_kind, repo_opts, arena, session, admin, &repo_id, empty.selected_id, repo) 584 else 585 Window.empty 586 else 587 Window.empty 588 else 589 Window.empty; 590 var draft_selected = false; 591 if (rooted) for (drafts_window.items) |item| { 592 if (std.mem.eql(u8, item.id, empty.selected_id)) { 593 draft_selected = true; 594 break; 595 } 596 }; 597 empty.drafts = drafts_window; 598 if (draft_selected and view != .edit and view != .publish and view != .remove) empty.view = .drafts; 599 600 // an explicitly named published patch that doesn't exist is a bad url 601 // (NotFound -> 404); drafts, labels, and bare routes can use the empty fallback. 602 const strict = rooted and !draft_selected; 603 604 // a repo with no consumed events has no moment yet. 605 const gpa = arena.child_allocator; 606 var event_db_maybe: ?evt.LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try evt.LocalEventDB(repo_opts.hash).openReadOnly(io, gpa, repo.core.repo_dir) else null; 607 defer if (event_db_maybe) |*event_db| event_db.deinit(io, gpa); 608 const haxy_moment = (if (event_db_maybe) |*event_db| 609 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 610 else if (repo_kind == .git) 611 return empty 612 else 613 evt.currentMoment(repo_opts, repo)) catch { 614 if (strict) return error.NotFound; 615 return empty; 616 }; 617 618 // the sorted sets to window, per status: the label's sets when filtered, 619 // else the top-level per-status sets. a missing set is an empty window. 620 var open_set: ?DB.SortedSet(.read_only) = null; 621 var closed_set: ?DB.SortedSet(.read_only) = null; 622 var merged_set: ?DB.SortedSet(.read_only) = null; 623 if (labeled) { 624 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.label_status_to_id_set_key))) |label_to_patches_cursor| { 625 const label_to_patches = try DB.SortedMap(.read_only).init(label_to_patches_cursor); 626 const decoded = std.Uri.percentDecodeInPlace(try aa.dupe(u8, empty.label)); 627 open_set = try thread.labelStatusSet(Self, DB, label_to_patches, decoded, .open); 628 closed_set = try thread.labelStatusSet(Self, DB, label_to_patches, decoded, .closed); 629 merged_set = try thread.labelStatusSet(Self, DB, label_to_patches, decoded, .merged); 630 } 631 } else if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key))) |status_to_patches_cursor| { 632 const status_to_patches = try DB.SortedMap(.read_only).init(status_to_patches_cursor); 633 open_set = try thread.statusSet(Self, DB, status_to_patches, .open); 634 closed_set = try thread.statusSet(Self, DB, status_to_patches, .closed); 635 merged_set = try thread.statusSet(Self, DB, status_to_patches, .merged); 636 } else if (strict) return error.NotFound; 637 638 const event_id_to_patch_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.record_map_key)) orelse { 639 if (strict) return error.NotFound; 640 return empty; 641 }; 642 const event_id_to_patch = try DB.HashMap(.read_only).init(event_id_to_patch_cursor); 643 644 // the conflicted patches' container: a set view for membership and 645 // windowing, a map view for the resolve entry, over the same cursor. 646 var conflict_set: ?DB.SortedSet(.read_only) = null; 647 var conflicts_map: ?DB.SortedMap(.read_only) = null; 648 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 649 conflict_set = try DB.SortedSet(.read_only).init(cursor); 650 conflicts_map = try DB.SortedMap(.read_only).init(cursor); 651 } 652 653 // a named patch roots its own status's window at itself (the conflicts 654 // view's window instead); the other windows start at the beginning. 655 var resolved_view = empty.view; 656 var open_root: ?[]const u8 = null; 657 var closed_root: ?[]const u8 = null; 658 var merged_root: ?[]const u8 = null; 659 var conflicts_root: ?[]const u8 = null; 660 var conflict_data: ?Conflict = null; 661 if (rooted and !draft_selected) { 662 const id_bytes = evt.parseEventId(empty.selected_id) catch return error.NotFound; 663 const patch_cursor = try event_id_to_patch.getCursor(hash.hashInt(repo_opts.hash, &id_bytes)) orelse return error.NotFound; 664 const patch_map = try DB.HashMap(.read_only).init(patch_cursor); 665 const patch_event = try evt.read(evt.Patch.Record, DB, repo_opts.hash, arena, patch_map); 666 const order_key = try aa.dupe(u8, &evt.orderKeyDesc(patch_event.created_order, &id_bytes)); 667 668 if (view == .conflicts) { 669 // the id roots the conflicts window, so it must be conflicted 670 const set = conflict_set orelse return error.NotFound; 671 if (!try set.contains(order_key)) return error.NotFound; 672 conflicts_root = order_key; 673 } else { 674 // the named patch must be in its windowed set (a label url can name 675 // an patch that doesn't carry the label). 676 const set = (switch (patch_event.event.status) { 677 .open => open_set, 678 .closed => closed_set, 679 .merged => merged_set, 680 }) orelse return error.NotFound; 681 if (!try set.contains(order_key)) return error.NotFound; 682 683 switch (patch_event.event.status) { 684 .open => open_root = order_key, 685 .closed => closed_root = order_key, 686 .merged => merged_root = order_key, 687 } 688 // form urls keep their view; otherwise the patch's status picks it. 689 if (view != .edit and view != .merge and view != .new_comment and view != .edit_comment and view != .remove) resolved_view = switch (patch_event.event.status) { 690 .open => .open, 691 .closed => .closed, 692 .merged => .merged, 693 }; 694 695 // a resolve url shows the resolve view only while the patch still 696 // has a conflict entry; otherwise the status list stands. the 697 // wasm client renders from the snapshot, so the diff machinery 698 // this pulls in is gated out of its build. 699 if (comptime !wasm) { 700 if (view == .resolve) { 701 if (conflicts_map) |map| { 702 if (try map.getCursor(order_key)) |conflict_cursor| { 703 const conflict_entry = try DB.HashMap(.read_only).init(conflict_cursor); 704 conflict_data = try thread.readConflict(Self, repo_kind, repo_opts, arena, repo, io, admin_moment, haxy_moment, &id_bytes, patch_event, conflict_entry); 705 resolved_view = .resolve; 706 } 707 } 708 } 709 } 710 } 711 } 712 const thread_comments_start = if (empty.comment_id.len == 0) comments_start else 0; 713 var open_window = try thread.loadWindow(Self, .patch, repo_opts.hash, arena, admin_moment, haxy_moment, event_id_to_patch, open_set, open_root, conflict_set, empty.selected_id, thread_comments_start, empty.search, viewer); 714 var closed_window = try thread.loadWindow(Self, .patch, repo_opts.hash, arena, admin_moment, haxy_moment, event_id_to_patch, closed_set, closed_root, conflict_set, empty.selected_id, thread_comments_start, empty.search, viewer); 715 var merged_window = try thread.loadWindow(Self, .patch, repo_opts.hash, arena, admin_moment, haxy_moment, event_id_to_patch, merged_set, merged_root, conflict_set, empty.selected_id, thread_comments_start, empty.search, viewer); 716 var conflicts_window = try thread.loadWindow(Self, .patch, repo_opts.hash, arena, admin_moment, haxy_moment, event_id_to_patch, conflict_set, conflicts_root, conflict_set, empty.selected_id, thread_comments_start, null, viewer); 717 try setPatchDetails(repo_kind, repo_opts, io, arena, admin_moment, session.users_dir, haxy_moment, repo, &open_window); 718 try setPatchDetails(repo_kind, repo_opts, io, arena, admin_moment, session.users_dir, haxy_moment, repo, &closed_window); 719 try setPatchDetails(repo_kind, repo_opts, io, arena, admin_moment, session.users_dir, haxy_moment, repo, &merged_window); 720 try setPatchDetails(repo_kind, repo_opts, io, arena, admin_moment, session.users_dir, haxy_moment, repo, &conflicts_window); 721 if (view == .conflicts and conflicts_window.count > 0) resolved_view = .conflicts; 722 723 const comment_page = if (empty.comment_id.len == 0) 724 null 725 else 726 try Comment.init(repo_opts.hash, arena, admin_moment, haxy_moment, empty.selected_id, empty.comment_id, comments_start, viewer); 727 728 const labels = try thread.loadLabels(Self, repo_opts.hash, arena, haxy_moment); 729 730 return .{ 731 .identity = empty.identity, 732 .default_target_branch = empty.default_target_branch, 733 .label = empty.label, 734 .search = empty.search, 735 .selected_id = empty.selected_id, 736 .comment_id = empty.comment_id, 737 .comments_start = comments_start, 738 .comment_page = comment_page, 739 .viewer = viewer, 740 .open = open_window, 741 .closed = closed_window, 742 .merged = merged_window, 743 .drafts = drafts_window, 744 .conflicts = conflicts_window, 745 .conflict = conflict_data, 746 .theirs_picks = empty.theirs_picks, 747 .view = resolved_view, 748 .description_page = empty.description_page, 749 .labels = labels, 750 }; 751 } 752 753 fn setPatchDetails( 754 comptime repo_kind: rp.RepoKind, 755 comptime repo_opts: rp.RepoOpts(repo_kind), 756 io: std.Io, 757 arena: *std.heap.ArenaAllocator, 758 admin_moment: ?evt.AdminDB.HashMap(.read_only), 759 users_dir: ?[]const u8, 760 haxy_moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 761 repo: *rp.Repo(repo_kind, repo_opts), 762 target: *Window, 763 ) !void { 764 if (target.items.len == 0) return; 765 var config = try repo.listConfig(io, arena.child_allocator); 766 defer config.deinit(); 767 const items = try arena.allocator().dupe(PatchWithId, target.items); 768 for (items) |*item| { 769 const id = try evt.parseEventId(item.id); 770 const status = item.record.event.status.kind(); 771 // a fork-backed patch's fork lives in its forker's user repo 772 if (admin_moment) |moment| if (users_dir) |dir| if (item.record.event.source_branch == null) { 773 if (try fork.readForkerId(&config.sections, &id)) |forker_id| { 774 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &forker_id)) |forker| item.forker = forker.event.name; 775 const record = try evt.readForkById(io, arena.child_allocator, arena, dir, &forker_id, &id); 776 item.fork_exists = if (record) |value| !value.removed else false; 777 } 778 }; 779 const target_branch = item.record.event.target_branch; 780 const revision = item.record.event.revision orelse continue; 781 item.commit_count = revision.commit_count; 782 const merge_revision: evt.Patch.MergeRevision = switch (item.record.event.status) { 783 .merged => |merged| merged.revision, 784 else => .source, 785 }; 786 item.revision_oid = switch (merge_revision) { 787 .source => revision.source_oid, 788 .squash => revision.squash_oid, 789 }; 790 if (!item.fork_exists or status == .merged) { 791 const revision_id = try evt.parseEventId(&revision.id); 792 if (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, haxy_moment, arena, &revision_id)) |record| { 793 item.base_oid = record.event.base_oid; 794 } 795 } 796 if (status == .merged) { 797 if (merge_revision == .squash) item.commit_count = 1; 798 continue; 799 } 800 if (comptime repo_kind == .xit) { 801 var moment = try repo.core.latestMoment(); 802 const state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 803 item.mergeability = pch.readMergeability(repo_opts, state, io, arena, &id, item.record.event) catch .{}; 804 } 805 const target_oid = try repo.readRef(io, .{ .kind = .head, .name = target_branch }); 806 item.no_changes = if (target_oid) |oid| std.mem.eql(u8, &oid, revision.source_oid) else false; 807 } 808 target.items = items; 809 } 810 811 fn loadDraftWindow( 812 comptime repo_kind: rp.RepoKind, 813 comptime repo_opts: rp.RepoOpts(repo_kind), 814 arena: *std.heap.ArenaAllocator, 815 session: *ui.Session, 816 admin_moment: evt.AdminDB.HashMap(.read_only), 817 repo_id: *const [evt.event_id_size]u8, 818 selected_id: []const u8, 819 target_repo: *rp.Repo(repo_kind, repo_opts), 820 ) !Window { 821 const user_id = session.userId() orelse return .empty; 822 const user_name = session.data.user_name orelse return .empty; 823 const users_dir = session.users_dir orelse return .empty; 824 const io = session.io orelse return .empty; 825 826 // the viewer's drafts live in their user repo 827 var user_repo = (try evt.openUserRepo(io, arena.child_allocator, users_dir, &user_id)) orelse return .empty; 828 defer user_repo.deinit(io, arena.child_allocator); 829 const user_moment = (try evt.userMoment(&user_repo)) orelse return .empty; 830 const drafts_cursor = try user_moment.getCursor(hash.hashInt(evt.user_repo_opts.hash, evt.Fork.repo_to_draft_id_set_key)) orelse return .empty; 831 const drafts = try evt.UserDB.HashMap(.read_only).init(drafts_cursor); 832 const set_cursor = try drafts.getCursor(hash.hashInt(evt.user_repo_opts.hash, repo_id)) orelse return .empty; 833 const set = try evt.UserDB.SortedSet(.read_only).init(set_cursor); 834 const aa = arena.allocator(); 835 836 var root_key: ?[]const u8 = null; 837 if (selected_id.len != 0) { 838 const id = evt.parseEventId(selected_id) catch return error.NotFound; 839 if (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, arena, &id)) |record| { 840 if (!record.removed and record.event.stage == .draft) { 841 const order_key = try aa.dupe(u8, &evt.orderKeyDesc(record.created_order, &id)); 842 if (!try set.contains(order_key)) return error.NotFound; 843 root_key = order_key; 844 } 845 } 846 } 847 848 var prev_id: ?[]const u8 = null; 849 var iter = if (root_key) |root| blk: { 850 const rank = try set.rank(root); 851 if (rank > 0 and rank <= page_size) { 852 prev_id = ""; 853 } else if (rank > page_size) { 854 const pair = try set.getIndexKeyValuePair(@intCast(rank - page_size)) orelse return error.NotFound; 855 var previous: [@sizeOf(u64) + evt.event_id_size]u8 = undefined; 856 _ = try pair.key_cursor.readBytes(&previous); 857 const hex = std.fmt.bytesToHex(previous[@sizeOf(u64)..].*, .lower); 858 prev_id = try aa.dupe(u8, &hex); 859 } 860 break :blk try set.iteratorFrom(root); 861 } else try set.iteratorFromIndex(0); 862 863 var items: std.ArrayList(PatchWithId) = .empty; 864 var next_id: ?[]const u8 = null; 865 while (try iter.next()) |cursor| { 866 const id = try evt.readOrderKeyId(evt.UserDB, cursor); 867 const id_hex = std.fmt.bytesToHex(id, .lower); 868 if (items.items.len == page_size) { 869 next_id = try aa.dupe(u8, &id_hex); 870 break; 871 } 872 const path = try fork.forkPath(aa, users_dir, &user_id, &id); 873 // a fork shares its target's hash kind 874 var fork_repo = rp.Repo(.xit, .{ .hash = repo_opts.hash }).open(io, arena.child_allocator, .{ .path = path, .require_repo_root = true }) catch continue; 875 defer fork_repo.deinit(io, arena.child_allocator); 876 const entry = (try loadDraftEntry(repo_kind, repo_opts, arena, io, admin_moment, &fork_repo, target_repo, id, user_name)) orelse continue; 877 try items.append(aa, entry); 878 } 879 return .{ 880 .items = items.items, 881 .prev_id = prev_id, 882 .next_id = next_id, 883 .count = @intCast(try set.count()), 884 }; 885 } 886 887 pub fn loadDraftEntry( 888 comptime repo_kind: rp.RepoKind, 889 comptime repo_opts: rp.RepoOpts(repo_kind), 890 arena: *std.heap.ArenaAllocator, 891 io: std.Io, 892 admin_moment: ?evt.AdminDB.HashMap(.read_only), 893 fork_repo: *rp.Repo(.xit, .{ .hash = repo_opts.hash }), 894 target_repo: *rp.Repo(repo_kind, repo_opts), 895 id: [evt.event_id_size]u8, 896 forker: []const u8, 897 ) !?PatchWithId { 898 const aa = arena.allocator(); 899 const id_hex = std.fmt.bytesToHex(id, .lower); 900 const fork_oid = (try fork_repo.readRef(io, fork.ref)) orelse return null; 901 const moment = evt.currentMoment(.{ .hash = repo_opts.hash }, fork_repo) catch return null; 902 const patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, arena, &id)) orelse return null; 903 const target_branch = patch.event.target_branch; 904 const target_oid = try target_repo.readRef(io, .{ .kind = .head, .name = target_branch }); 905 const commit_count: ?u64 = blk: { 906 const newest = evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, arena) catch break :blk null; 907 break :blk if (newest) |revision| revision.record.commit_count else 0; 908 }; 909 return .{ 910 .id = try aa.dupe(u8, &id_hex), 911 .record = patch, 912 .author = try ui.Author.initFromEmail(admin_moment, arena, patch.author_email), 913 .draft = true, 914 .revision_oid = try aa.dupe(u8, &fork_oid), 915 .commit_count = commit_count, 916 .no_changes = if (target_oid) |oid| std.mem.eql(u8, &oid, &fork_oid) else false, 917 .fork_exists = true, 918 .forker = try aa.dupe(u8, forker), 919 }; 920 } 921 922 pub const View = thread.View(.patch, Self); 923 pub const Detail = thread.Detail(.patch, Self); 924 pub const detail_widget_name = "repo_patch_detail"; 925 926 pub const Header = thread.Header; 927 928 const open_tab_label = "open"; 929 const closed_tab_label = "closed"; 930 const merged_tab_label = "merged"; 931 const labels_tab_label = "labels"; 932 const edit_tab_label = "edit"; 933 const publish_tab_label = "publish"; 934 const merge_tab_label = "merge"; 935 const reply_tab_label = "reply"; 936 const remove_tab_label = "remove"; 937 const resolve_tab_label = "resolve"; 938 const new_tab_label = "new"; 939 const drafts_tab_label = "drafts"; 940 const conflicts_tab_label = "conflicts"; 941 942 pub fn appendDetails(self: *const Self, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), session: *ui.Session, entry: Entry) !void { 943 const aa = session.page_arena.allocator(); 944 const status_kind = entry.record.event.status.kind(); 945 const target_branch = entry.record.event.target_branch; 946 947 if (status_kind != .merged and entry.fork_exists) if (session.data.git_ssh_port) |port| { 948 const url = try std.fmt.allocPrint(aa, "ssh://localhost:{d}/fork/{s}/patch:{s}", .{ port, self.identity, entry.id }); 949 const push_command = try std.fmt.allocPrint(aa, "git push {s} HEAD:patch", .{url}); 950 const clone_name = try cloneDirectoryName(aa, entry.record.event.title); 951 const clone_command = if (clone_name.len == 0) 952 try std.fmt.allocPrint(aa, "git clone {s}", .{url}) 953 else 954 try std.fmt.allocPrint(aa, "git clone {s} {s}", .{ url, clone_name }); 955 const merge_command = try std.fmt.allocPrint(aa, "git fetch '{s}' refs/heads/patch && git merge FETCH_HEAD", .{url}); 956 const choices: [3]ui.widget.CopyableText.Choice = .{ 957 .{ 958 .selector = "push", 959 .text = push_command, 960 .copyable_text = try std.fmt.allocPrint(aa, "{s}{s}", .{ session.data.git_ssh_prefix, push_command }), 961 .label = " push to this patch from existing repo ", 962 }, 963 .{ 964 .selector = "clone", 965 .text = clone_command, 966 .copyable_text = try std.fmt.allocPrint(aa, "{s}{s}", .{ session.data.git_ssh_prefix, clone_command }), 967 .label = " clone this patch ", 968 }, 969 .{ 970 .selector = "merge", 971 .text = merge_command, 972 .copyable_text = try std.fmt.allocPrint(aa, "{s}{s}", .{ session.data.git_ssh_prefix, merge_command }), 973 .label = " merge this patch locally ", 974 }, 975 }; 976 var copyable_text = try ui.widget.CopyableText.init(allocator, session, &choices, 0); 977 errdefer copyable_text.deinit(allocator); 978 try box.children.put(allocator, copyable_text.getFocus().id, .{ .widget = .{ .copyable_text = copyable_text }, .rect = null, .min_size = null }); 979 }; 980 if (entry.record.event.source_branch) |branch| { 981 var source = try wgt.TextBox.init(allocator, branch, .{ .label = " source branch ", .border_style = .single, .round_corners = true, .wrap_kind = .none }); 982 errdefer source.deinit(allocator); 983 source.getFocus().mode = .all; 984 try box.children.put(allocator, source.getFocus().id, .{ .widget = .{ .text_box = source }, .rect = null, .min_size = null }); 985 } 986 const fields = [_]ui.widget.CopyableText.Choice{ 987 .{ 988 .selector = "from", 989 .text = entry.revision_oid, 990 .label = if (entry.no_changes) " object id of this patch (no changes) " else " object id of this patch ", 991 }, 992 .{ 993 .selector = "to", 994 .text = target_branch, 995 .label = if (status_kind == .merged) " target branch this patch was merged into " else " target branch this patch will go to ", 996 }, 997 }; 998 var copyable_text = try ui.widget.CopyableText.init(allocator, session, fields[@intFromBool(entry.revision_oid.len == 0)..], 0); 999 errdefer copyable_text.deinit(allocator); 1000 try box.children.put(allocator, copyable_text.getFocus().id, .{ .widget = .{ .copyable_text = copyable_text }, .rect = null, .min_size = null }); 1001 } 1002 1003 fn cloneDirectoryName(allocator: std.mem.Allocator, title: []const u8) ![]const u8 { 1004 var name: [64]u8 = undefined; 1005 var len: usize = 0; 1006 var pending: ?u8 = null; 1007 1008 for (title) |char| { 1009 if (std.ascii.isAlphanumeric(char)) { 1010 const needed: usize = if (pending == null) 1 else 2; 1011 if (len + needed > name.len) break; 1012 if (pending) |value| { 1013 name[len] = value; 1014 len += 1; 1015 } 1016 name[len] = std.ascii.toLower(char); 1017 len += 1; 1018 pending = null; 1019 } else if (char == ' ') { 1020 if (len != 0) pending = '-'; 1021 } else if (char == '.') { 1022 if (len != 0 and pending != '-') pending = '.'; 1023 } 1024 } 1025 if (len == 0) return ""; 1026 return allocator.dupe(u8, name[0..len]); 1027 } 1028 1029 // tabs switching between the patches page's views 1030 pub fn initHeader(allocator: std.mem.Allocator, session: *ui.Session, data: *const Self) !Header { 1031 var header = try Header.init(allocator, session, data.search); 1032 errdefer header.deinit(allocator); 1033 const aa = session.page_arena.allocator(); 1034 const selected_index = View.viewIndex(data.view); 1035 const page_selected = std.meta.activeTag(session.data.current_page) == .repo_patches; 1036 1037 // a list tab per status, labeled with its listing's patch count 1038 const status_labels = [_][]const u8{ open_tab_label, closed_tab_label, merged_tab_label }; 1039 for ([_]Status{ .open, .closed, .merged }, status_labels, 0..) |status, status_label, index| { 1040 const route = try thread.searchRoute(ui.RoutablePage.repoPatchesRoute(data.identity, status, data.label, ""), data.search); 1041 const link = try ui.inPageTabLink(session, route, page_selected and selected_index == index); 1042 var label_buf: [64]u8 = undefined; 1043 const label = try thread.countLabel(&label_buf, status_label, data.window(status).*); 1044 try header.addTab(allocator, label, link, index); 1045 } 1046 1047 // labels tab, showing the active label filter 1048 { 1049 const labels_route = try thread.searchRoute(ui.RoutablePage.repoThreadLabelsRoute(.patch, data.identity, data.label), data.search); 1050 const labels_link = try ui.inPageTabLink(session, labels_route, page_selected and selected_index == View.viewIndex(.labels)); 1051 const label = if (data.label.len == 0) labels_tab_label else blk: { 1052 const decoded = std.Uri.percentDecodeInPlace(try aa.dupe(u8, data.label)); 1053 break :blk try std.fmt.allocPrint(aa, labels_tab_label ++ " ({s})", .{decoded}); 1054 }; 1055 try header.addTab(allocator, label, labels_link, View.viewIndex(.labels)); 1056 } 1057 1058 // new-patch tab; an edit or resolve url shows its tab in this place 1059 { 1060 const route = switch (data.view) { 1061 .edit => ui.RoutablePage.repoThreadEditRoute(.patch, data.identity, data.selected_id) orelse return error.RouteTooLong, 1062 .publish => ui.RoutablePage.repoPatchPublishRoute(data.identity, data.selected_id) orelse return error.RouteTooLong, 1063 .merge => ui.RoutablePage.repoPatchMergeRoute(data.identity, data.selected_id) orelse return error.RouteTooLong, 1064 .new_comment => ui.RoutablePage.repoThreadCommentNewRoute(.patch, data.identity, data.selected_id, data.comment_id) orelse return error.RouteTooLong, 1065 .edit_comment => ui.RoutablePage.repoThreadCommentEditRoute(.patch, data.identity, data.selected_id, data.comment_id) orelse return error.RouteTooLong, 1066 .remove => ui.RoutablePage.repoThreadRemoveRoute(.patch, data.identity, data.selected_id, data.comment_id) orelse return error.RouteTooLong, 1067 .resolve => ui.RoutablePage.repoPatchesResolveRoute(data.identity, data.selected_id, data.theirs_picks) orelse return error.RouteTooLong, 1068 else => ui.RoutablePage.repoThreadNewRoute(.patch, data.identity) orelse return error.RouteTooLong, 1069 }; 1070 const link = try ui.inPageTabLink(session, route, page_selected and selected_index == View.viewIndex(.new)); 1071 const label: []const u8 = switch (data.view) { 1072 .edit => edit_tab_label, 1073 .publish => publish_tab_label, 1074 .merge => merge_tab_label, 1075 .new_comment => reply_tab_label, 1076 .edit_comment => edit_tab_label, 1077 .remove => remove_tab_label, 1078 .resolve => resolve_tab_label, 1079 else => new_tab_label, 1080 }; 1081 try header.addTab(allocator, label, link, View.viewIndex(.new)); 1082 } 1083 1084 // drafts belong to the logged-in user and are not available locally 1085 if (session.data.host_kind != .local) { 1086 const route = ui.RoutablePage.repoPatchesDraftsRoute(data.identity) orelse return error.RouteTooLong; 1087 const link = try ui.inPageTabLink(session, route, page_selected and selected_index == View.viewIndex(.drafts)); 1088 var label_buf: [64]u8 = undefined; 1089 const label = try std.fmt.bufPrint(&label_buf, drafts_tab_label ++ " ({d})", .{data.drafts.count}); 1090 try header.addTab(allocator, label, link, View.viewIndex(.drafts)); 1091 } 1092 1093 // conflicts tab, labeled with the conflict count 1094 if (data.conflicts.count > 0) { 1095 const route = ui.RoutablePage.repoPatchesConflictsRoute(data.identity, "") orelse return error.RouteTooLong; 1096 const link = try ui.inPageTabLink(session, route, page_selected and selected_index == View.viewIndex(.conflicts)); 1097 var label_buf: [64]u8 = undefined; 1098 const label = try std.fmt.bufPrint(&label_buf, conflicts_tab_label ++ " ({d})", .{data.conflicts.count}); 1099 try header.addTab(allocator, label, link, View.viewIndex(.conflicts)); 1100 } 1101 1102 header.select(View.viewIndex(data.view)); 1103 return header; 1104 } 1105