forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.9 MiB·b00f3f4·Tahinli·1 month ago·147 commits
| 1 | //! Pages of one pull request at `/{owner}/{repo}/pulls/{n}`: the Conversation (header, timeline, |
| 2 | //! merge box, comment and state form, sidebar), Commits and Files changed. The timeline, sidebar |
| 3 | //! and comment POST logic are shared with issues (`issue_parts`); label, assignee and milestone |
| 4 | //! POSTs are in `issue_meta`. Comments post to `/pulls/{n}/comments`, close and reopen to |
| 5 | //! `/pulls/{n}/state`. The merge POST (`/pulls/{n}/merge`) lives in `pulls_merge`. |
| 6 | |
| 7 | use std::collections::HashMap; |
| 8 | |
| 9 | use forge_core::store::commit_status::StatusState; |
| 10 | use forge_core::{Action, IssueState, Mergeable, PullRequest, Review, ReviewState, authorize}; |
| 11 | use forge_git::browse::CommitInfo; |
| 12 | use forge_git::history::CommitDiff; |
| 13 | use forge_git::pulls::{is_ancestor, range_diff_files, range_log}; |
| 14 | use topcoat::Result; |
| 15 | use topcoat::context::{Cx, app_context}; |
| 16 | use topcoat::router::content::Form; |
| 17 | use topcoat::router::error::{not_found, see_other}; |
| 18 | use topcoat::router::request::uri; |
| 19 | use topcoat::router::{page, path_param}; |
| 20 | use topcoat::view::{View, component, view}; |
| 21 | |
| 22 | use crate::auth::require_user; |
| 23 | use crate::i18n::pulls_review::{self as g, K}; |
| 24 | use crate::i18n::{self, Lang}; |
| 25 | use crate::pages::commits::{CommitRow, now_secs}; |
| 26 | use crate::pages::issue_meta::item_href; |
| 27 | use crate::pages::issue_parts::{ |
| 28 | CommentForm, ItemKind, Posted, When, check_write, comment_form, csrf_of, discussion_timeline, |
| 29 | item_sidebar, load_discussion, load_sidebar, lock_message, may_change, may_converse, |
| 30 | parse_number, post_comment, triage, viewer, |
| 31 | }; |
| 32 | use crate::pages::notifications::notify_box_for; |
| 33 | use crate::pages::pull_branch::{self, branch_box, branch_error_from}; |
| 34 | use crate::pages::pull_reviews::error_text_in; |
| 35 | use crate::pages::pulls_merge::{ |
| 36 | ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, |
| 37 | ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, |
| 38 | ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE, |
| 39 | ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, |
| 40 | }; |
| 41 | use crate::pages::repo::repo_head; |
| 42 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 43 | use crate::pages::review_requests::{load_reviewers, reviewers_box}; |
| 44 | use crate::state::AppState; |
| 45 | use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status}; |
| 46 | use crate::views::diff::LIMITS; |
| 47 | use crate::views::{alert, now_unix, repo_href, shell, short_oid, user_link}; |
| 48 | |
| 49 | path_param!(owner); |
| 50 | path_param!(repo); |
| 51 | path_param!(number); |
| 52 | |
| 53 | /// Commits listed (and counted) for one pull request. |
| 54 | const MAX_COMMITS: usize = 250; |
| 55 | |
| 56 | /// Whether the pull request has been merged. A merged pull request is closed and cannot change. |
| 57 | pub(crate) fn is_merged(pr: &PullRequest) -> bool { |
| 58 | pr.merged_at.is_some() || pr.mergeable == Mergeable::Merged |
| 59 | } |
| 60 | |
| 61 | /// The pull request named by `{number}` in this repo, or 404. |
| 62 | async fn pull_for(state: &AppState, ctx: &RepoCtx, number: i64) -> Result<PullRequest> { |
| 63 | match state.store.pull_by_number(&ctx.repo.id, number).await? { |
| 64 | Some(pr) => Ok(pr), |
| 65 | None => Err(not_found().into()), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// The repo and pull request for a request whose path names `{owner}/{repo}/pulls/{number}`. |
| 70 | async fn load_pull(cx: &Cx) -> Result<(RepoCtx, PullRequest)> { |
| 71 | let number = parse_number(path_param::<Number>(cx))?; |
| 72 | let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?; |
| 73 | let pr = pull_for(app_context::<AppState>(cx), &ctx, number).await?; |
| 74 | Ok((ctx, pr)) |
| 75 | } |
| 76 | |
| 77 | // Git data |
| 78 | |
| 79 | /// The commits in `base..head`, oldest first, up to `MAX_COMMITS`. |
| 80 | pub(crate) async fn commits_of( |
| 81 | state: &AppState, |
| 82 | ctx: &RepoCtx, |
| 83 | pr: &PullRequest, |
| 84 | ) -> Result<Vec<CommitInfo>> { |
| 85 | Ok(range_log( |
| 86 | &state.git, |
| 87 | &ctx.path, |
| 88 | &pr.base_oid, |
| 89 | &pr.head_oid, |
| 90 | MAX_COMMITS, |
| 91 | ) |
| 92 | .await?) |
| 93 | } |
| 94 | |
| 95 | /// The diff of the head side of the pull request (merge base to head). |
| 96 | pub(crate) async fn diff_of( |
| 97 | state: &AppState, |
| 98 | ctx: &RepoCtx, |
| 99 | pr: &PullRequest, |
| 100 | ) -> Result<CommitDiff> { |
| 101 | Ok(range_diff_files(&state.git, &ctx.path, &pr.base_oid, &pr.head_oid, LIMITS).await?) |
| 102 | } |
| 103 | |
| 104 | // Header |
| 105 | |
| 106 | /// What the header and sub-tabs show: the title, state, byline and tab counts. |
| 107 | #[derive(Clone)] |
| 108 | pub(crate) struct Frame { |
| 109 | title: String, |
| 110 | number: i64, |
| 111 | pub(crate) page_title: String, |
| 112 | pub(crate) href: String, |
| 113 | author: String, |
| 114 | author_known: bool, |
| 115 | opened: When, |
| 116 | pub(crate) commit_count: usize, |
| 117 | pub(crate) file_count: usize, |
| 118 | base_branch: String, |
| 119 | head_label: String, |
| 120 | state_class: &'static str, |
| 121 | state_text: &'static str, |
| 122 | lang: Lang, |
| 123 | } |
| 124 | |
| 125 | /// The header for a pull request, with its strings in `lang`. |
| 126 | pub(crate) async fn frame_in( |
| 127 | lang: Lang, |
| 128 | state: &AppState, |
| 129 | ctx: &RepoCtx, |
| 130 | pr: &PullRequest, |
| 131 | commit_count: usize, |
| 132 | file_count: usize, |
| 133 | ) -> Result<Frame> { |
| 134 | let owner = ctx.repo.owner_name.clone(); |
| 135 | let name = ctx.repo.name.clone(); |
| 136 | let number = pr.issue.number; |
| 137 | |
| 138 | let users = state |
| 139 | .store |
| 140 | .usernames_by_ids(std::slice::from_ref(&pr.issue.author_id)) |
| 141 | .await?; |
| 142 | let author_known = users.contains_key(&pr.issue.author_id); |
| 143 | let author = users |
| 144 | .get(&pr.issue.author_id) |
| 145 | .map(|(display, _)| display.clone()) |
| 146 | .unwrap_or_else(|| g::t(lang, K::Unknown).to_owned()); |
| 147 | |
| 148 | // The head branch, qualified by its repo when that is a fork. A deleted head repo has none. |
| 149 | let head_label = match pr.head_repo_id.as_deref() { |
| 150 | None => g::branch_deleted(lang, &pr.head_branch), |
| 151 | Some(id) if id == ctx.repo.id => pr.head_branch.clone(), |
| 152 | Some(id) => match state.store.repo_by_id(id).await? { |
| 153 | Some(head) => format!("{}:{}", head.owner_name, pr.head_branch), |
| 154 | None => g::branch_deleted(lang, &pr.head_branch), |
| 155 | }, |
| 156 | }; |
| 157 | |
| 158 | let (state_class, state_text) = if is_merged(pr) { |
| 159 | ("issue-badge issue-badge-merged", g::t(lang, K::StateMerged)) |
| 160 | } else if matches!(pr.issue.state, IssueState::Open) && pr.draft { |
| 161 | ("issue-badge issue-badge-draft", g::t(lang, K::DraftBadge)) |
| 162 | } else if matches!(pr.issue.state, IssueState::Open) { |
| 163 | ("issue-badge issue-badge-open", g::t(lang, K::StateOpen)) |
| 164 | } else { |
| 165 | ("issue-badge issue-badge-closed", g::t(lang, K::StateClosed)) |
| 166 | }; |
| 167 | |
| 168 | Ok(Frame { |
| 169 | lang, |
| 170 | title: pr.issue.title.clone(), |
| 171 | number, |
| 172 | page_title: format!("{} #{number} \u{b7} {owner}/{name}", pr.issue.title), |
| 173 | href: repo_href(&owner, &name, "pulls", &number.to_string()), |
| 174 | author, |
| 175 | author_known, |
| 176 | opened: When::new(lang, &pr.issue.created_at, ctx.viewer_tz(), now_unix()), |
| 177 | commit_count, |
| 178 | file_count, |
| 179 | base_branch: pr.base_branch.clone(), |
| 180 | head_label, |
| 181 | state_class, |
| 182 | state_text, |
| 183 | }) |
| 184 | } |
| 185 | |
| 186 | #[component] |
| 187 | pub(crate) async fn pull_header(frame: Frame) -> Result<impl View> { |
| 188 | let Frame { |
| 189 | title, |
| 190 | number, |
| 191 | href, |
| 192 | state_class, |
| 193 | state_text, |
| 194 | author, |
| 195 | author_known, |
| 196 | opened, |
| 197 | commit_count, |
| 198 | base_branch, |
| 199 | head_label, |
| 200 | lang, |
| 201 | .. |
| 202 | } = frame; |
| 203 | let number_label = format!("#{number}"); |
| 204 | // The header is on every pull tab, so each tab follows the pull's stream. |
| 205 | let live_url = format!("{href}/events"); |
| 206 | let commits_text = g::commit_count_line(lang, commit_count); |
| 207 | let wants = g::t(lang, K::ByWantsToMerge); |
| 208 | let into = g::t(lang, K::ByInto); |
| 209 | let from = g::t(lang, K::ByFrom); |
| 210 | let byline_end = g::t(lang, K::BylineEnd); |
| 211 | // Turkish puts the source branch first and the commit count before the verb. |
| 212 | let turkish = matches!(lang, Lang::Tr); |
| 213 | Ok(view! { |
| 214 | <section class="issue-head" data-live=(live_url.as_str())> |
| 215 | <h1 class="issue-heading">(title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1> |
| 216 | <p class="issue-byline"> |
| 217 | <span class=(state_class)>(state_text)</span> |
| 218 | <strong> |
| 219 | if author_known { |
| 220 | user_link(shown: author.as_str(), login: author.as_str()) |
| 221 | } else { |
| 222 | (author.as_str()) |
| 223 | } |
| 224 | </strong> |
| 225 | if turkish { |
| 226 | (wants) <code>(head_label.as_str())</code> |
| 227 | (from) <code>(base_branch.as_str())</code> |
| 228 | (into) (commits_text.as_str()) |
| 229 | } else { |
| 230 | (wants) (commits_text.as_str()) (into) |
| 231 | <code>(base_branch.as_str())</code> |
| 232 | (from) |
| 233 | <code>(head_label.as_str())</code> |
| 234 | } |
| 235 | (byline_end) |
| 236 | <time datetime=(opened.iso.as_str()) title=(opened.absolute.as_str())>(opened.relative.as_str())</time> |
| 237 | </p> |
| 238 | </section> |
| 239 | }) |
| 240 | } |
| 241 | |
| 242 | /// Class for one sub-navigation link: the one named by `active` is marked current. |
| 243 | fn tab_class(active: &str, tab: &str) -> &'static str { |
| 244 | if active == tab { |
| 245 | "subnav-link current" |
| 246 | } else { |
| 247 | "subnav-link" |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /// The pull request's sub-tabs, with their labels in `lang`. |
| 252 | #[component] |
| 253 | pub(crate) async fn pull_subnav_in( |
| 254 | lang: Lang, |
| 255 | href: String, |
| 256 | active: String, |
| 257 | commits: usize, |
| 258 | files: usize, |
| 259 | ) -> Result<impl View> { |
| 260 | let commits_href = format!("{href}/commits"); |
| 261 | let files_href = format!("{href}/files"); |
| 262 | let commits_label = g::commits_tab(lang, commits); |
| 263 | let files_label = g::files_tab(lang, files); |
| 264 | let conversation = g::t(lang, K::TabConversation); |
| 265 | let aria = g::t(lang, K::PullPages); |
| 266 | Ok(view! { |
| 267 | <nav class="subnav" aria-label=(aria)> |
| 268 | <a class=(tab_class(&active, "conversation")) href=(href.as_str())>(conversation)</a> |
| 269 | <a class=(tab_class(&active, "commits")) href=(commits_href.as_str())>(commits_label.as_str())</a> |
| 270 | <a class=(tab_class(&active, "files")) href=(files_href.as_str())>(files_label.as_str())</a> |
| 271 | </nav> |
| 272 | }) |
| 273 | } |
| 274 | |
| 275 | // Merge box |
| 276 | |
| 277 | /// Where the merge form posts, and whether fast-forward is offered. |
| 278 | struct MergeForm { |
| 279 | action: String, |
| 280 | csrf: String, |
| 281 | ff: bool, |
| 282 | } |
| 283 | |
| 284 | /// One required check as the merge box lists it. |
| 285 | struct CheckRow { |
| 286 | context: String, |
| 287 | label: &'static str, |
| 288 | class: &'static str, |
| 289 | } |
| 290 | |
| 291 | /// The flow controls of the merge box: the draft toggle and auto-merge. |
| 292 | struct FlowView { |
| 293 | csrf: String, |
| 294 | /// `(action, button label)` of the draft toggle. |
| 295 | draft_toggle: Option<(String, &'static str)>, |
| 296 | /// Auto-merge is on: the status line and the disable action. |
| 297 | auto_on: Option<(String, String)>, |
| 298 | /// Auto-merge can be enabled: the action. |
| 299 | auto_enable: Option<String>, |
| 300 | /// The pull request waits in the merge queue: its position line and the remove action. |
| 301 | queue_position: Option<(String, String)>, |
| 302 | /// The pull request can join the merge queue: the action. |
| 303 | queue_add: Option<String>, |
| 304 | } |
| 305 | |
| 306 | /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of |
| 307 | /// `ok`, `bad` or `muted` and picks the box colors. |
| 308 | #[component] |
| 309 | async fn merge_box( |
| 310 | headline: String, |
| 311 | tone: String, |
| 312 | conflicts: Vec<String>, |
| 313 | reload: Option<String>, |
| 314 | form: Option<MergeForm>, |
| 315 | merge_error: Option<String>, |
| 316 | approvals: Option<String>, |
| 317 | blocked: Option<String>, |
| 318 | checks: Option<StatusSummary>, |
| 319 | required: Vec<CheckRow>, |
| 320 | flow: FlowView, |
| 321 | lang: Lang, |
| 322 | ) -> Result<impl View> { |
| 323 | let class = format!("merge-box merge-{tone}"); |
| 324 | let required_heading = g::t(lang, K::RequiredChecksHeading); |
| 325 | let style_rebase = g::t(lang, K::StyleRebase); |
| 326 | let style_merge_option = g::t(lang, K::StyleMergeCommit); |
| 327 | let style_squash_option = g::t(lang, K::StyleSquash); |
| 328 | let enable_auto = g::t(lang, K::EnableAutoMerge); |
| 329 | let auto_hint = g::t(lang, K::AutoMergeHint); |
| 330 | let disable_auto = g::t(lang, K::DisableAutoMerge); |
| 331 | let FlowView { |
| 332 | csrf: flow_csrf, |
| 333 | draft_toggle, |
| 334 | auto_on, |
| 335 | auto_enable, |
| 336 | queue_position, |
| 337 | queue_add, |
| 338 | } = flow; |
| 339 | let queue_add_label = |
| 340 | crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::AddToMergeQueue); |
| 341 | let queue_remove_label = |
| 342 | crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::RemoveFromQueue); |
| 343 | let queue_hint = crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::MergeQueueHint); |
| 344 | let reload_text = g::t(lang, K::ReloadToCheck); |
| 345 | let style_legend = g::t(lang, K::MergeStyleLegend); |
| 346 | let style_merge = g::t(lang, K::StyleMergeCommit); |
| 347 | let style_squash = g::t(lang, K::StyleSquash); |
| 348 | let style_ff = g::t(lang, K::StyleFastForward); |
| 349 | let message_label = g::t(lang, K::MergeMessageLabel); |
| 350 | let merge_button = g::t(lang, K::MergeButton); |
| 351 | Ok(view! { |
| 352 | <section class=(class.as_str())> |
| 353 | if let Some(text) = merge_error { |
| 354 | <p class="alert merge-error" role="alert">(text.as_str())</p> |
| 355 | } |
| 356 | <p class="merge-headline">(headline.as_str())</p> |
| 357 | if let Some(summary) = checks { |
| 358 | checks_summary(summary: summary, lang: StatusLang(lang)) |
| 359 | } |
| 360 | if !required.is_empty() { |
| 361 | <div class="required-checks"> |
| 362 | <p class="muted small">(required_heading)</p> |
| 363 | <ul class="required-check-list"> |
| 364 | for row in required.iter() { |
| 365 | <li class=(row.class)><code>(row.context.as_str())</code><span>(row.label)</span></li> |
| 366 | } |
| 367 | </ul> |
| 368 | </div> |
| 369 | } |
| 370 | if let Some(text) = approvals { |
| 371 | <p class="muted small">(text.as_str())</p> |
| 372 | } |
| 373 | if let Some(text) = blocked { |
| 374 | <p class="merge-blocked">(text.as_str())</p> |
| 375 | } |
| 376 | if !conflicts.is_empty() { |
| 377 | <ul class="merge-files"> |
| 378 | for file in conflicts.iter() { |
| 379 | <li><code>(file.as_str())</code></li> |
| 380 | } |
| 381 | </ul> |
| 382 | } |
| 383 | if let Some(href) = reload { |
| 384 | <p class="muted small"><a href=(href.as_str())>(reload_text)</a></p> |
| 385 | } |
| 386 | if let Some(f) = form { |
| 387 | <form method="post" action=(f.action.as_str()) class="stack merge-form"> |
| 388 | <input type="hidden" name="csrf" value=(f.csrf.as_str())> |
| 389 | <fieldset class="merge-styles"> |
| 390 | <legend>(style_legend)</legend> |
| 391 | <label><input type="radio" name="style" value="merge" checked=(true)>(style_merge)</label> |
| 392 | <label><input type="radio" name="style" value="squash">(style_squash)</label> |
| 393 | <label><input type="radio" name="style" value="rebase">(style_rebase)</label> |
| 394 | if f.ff { |
| 395 | <label><input type="radio" name="style" value="ff">(style_ff)</label> |
| 396 | } |
| 397 | </fieldset> |
| 398 | <label> |
| 399 | <span>(message_label)</span> |
| 400 | <textarea name="message" rows="3"></textarea> |
| 401 | </label> |
| 402 | <div><button type="submit" class="primary">(merge_button)</button></div> |
| 403 | </form> |
| 404 | } |
| 405 | if let Some((text, action)) = queue_position { |
| 406 | <form method="post" action=(action.as_str()) class="merge-flow"> |
| 407 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 408 | <p class="merge-headline">(text.as_str())</p> |
| 409 | <button type="submit">(queue_remove_label)</button> |
| 410 | </form> |
| 411 | } |
| 412 | if let Some(action) = queue_add { |
| 413 | <form method="post" action=(action.as_str()) class="merge-flow"> |
| 414 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 415 | <p class="muted small">(queue_hint)</p> |
| 416 | <select name="style" aria-label=(queue_add_label)> |
| 417 | <option value="merge">(style_merge_option.trim())</option> |
| 418 | <option value="squash">(style_squash_option.trim())</option> |
| 419 | <option value="rebase">(style_rebase.trim())</option> |
| 420 | </select> |
| 421 | <button type="submit" class="primary">(queue_add_label)</button> |
| 422 | </form> |
| 423 | } |
| 424 | if let Some((text, action)) = auto_on { |
| 425 | <form method="post" action=(action.as_str()) class="merge-flow"> |
| 426 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 427 | <p class="muted small">(text.as_str())</p> |
| 428 | <button type="submit">(disable_auto)</button> |
| 429 | </form> |
| 430 | } |
| 431 | if let Some(action) = auto_enable { |
| 432 | <form method="post" action=(action.as_str()) class="merge-flow"> |
| 433 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 434 | <p class="muted small">(auto_hint)</p> |
| 435 | <select name="style" aria-label=(enable_auto)> |
| 436 | <option value="merge">(style_merge_option.trim())</option> |
| 437 | <option value="squash">(style_squash_option.trim())</option> |
| 438 | <option value="rebase">(style_rebase.trim())</option> |
| 439 | </select> |
| 440 | <button type="submit">(enable_auto)</button> |
| 441 | </form> |
| 442 | } |
| 443 | if let Some((action, label)) = draft_toggle { |
| 444 | <form method="post" action=(action.as_str()) class="merge-flow"> |
| 445 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 446 | <button type="submit">(label)</button> |
| 447 | </form> |
| 448 | } |
| 449 | </section> |
| 450 | }) |
| 451 | } |
| 452 | |
| 453 | /// The note that replaces the merge box once the pull request is merged. |
| 454 | #[component] |
| 455 | async fn merged_notice( |
| 456 | who: String, |
| 457 | when: When, |
| 458 | commit: String, |
| 459 | commit_href: String, |
| 460 | lang: Lang, |
| 461 | ) -> Result<impl View> { |
| 462 | let short = short_oid(&commit).to_owned(); |
| 463 | let prefix = g::t(lang, K::MergedByPrefix); |
| 464 | let middle = g::t(lang, K::MergedByMiddle); |
| 465 | let as_sep = g::t(lang, K::MergedAsSep); |
| 466 | Ok(view! { |
| 467 | <section class="merge-box merge-merged"> |
| 468 | <p class="merge-headline"> |
| 469 | (prefix) <strong>user_link(shown: who.as_str(), login: who.as_str())</strong> (middle) |
| 470 | <time datetime=(when.iso.as_str()) title=(when.absolute.as_str())>(when.relative.as_str())</time> |
| 471 | if !commit.is_empty() { |
| 472 | (as_sep) |
| 473 | <a class="mono" href=(commit_href.as_str())>(short.as_str())</a> |
| 474 | } |
| 475 | </p> |
| 476 | </section> |
| 477 | }) |
| 478 | } |
| 479 | |
| 480 | // Review summary |
| 481 | |
| 482 | /// A Dismiss form for one counted review: its action URL and the label of its reason field. |
| 483 | struct DismissRow { |
| 484 | action: String, |
| 485 | label: String, |
| 486 | } |
| 487 | |
| 488 | /// Who approves and who requests changes, then a Dismiss form per counted review for Write |
| 489 | /// holders. Either summary line may be absent. |
| 490 | #[component] |
| 491 | async fn review_box( |
| 492 | approved: Option<String>, |
| 493 | changes: Option<String>, |
| 494 | dismiss: Vec<DismissRow>, |
| 495 | csrf: String, |
| 496 | lang: Lang, |
| 497 | ) -> Result<impl View> { |
| 498 | let dismiss_text = g::t(lang, K::DismissButton); |
| 499 | Ok(view! { |
| 500 | <section class="review-box"> |
| 501 | if let Some(text) = approved { |
| 502 | <p class="review-summary">(text.as_str())</p> |
| 503 | } |
| 504 | if let Some(text) = changes { |
| 505 | <p class="review-summary">(text.as_str())</p> |
| 506 | } |
| 507 | for row in dismiss.iter() { |
| 508 | <form method="post" action=(row.action.as_str()) class="review-dismiss"> |
| 509 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 510 | <label> |
| 511 | <span>(row.label.as_str())</span> |
| 512 | <input type="text" name="reason" required=(true)> |
| 513 | </label> |
| 514 | <button type="submit" class="link-button">(dismiss_text)</button> |
| 515 | </form> |
| 516 | } |
| 517 | </section> |
| 518 | }) |
| 519 | } |
| 520 | |
| 521 | /// The approvals and change requests that count toward the summary: each reviewer's latest one, |
| 522 | /// with dismissed reviews left out, so an earlier undismissed state counts again. In submission |
| 523 | /// order, as `review_summary` counts them. |
| 524 | async fn counted_reviews(state: &AppState, pr: &PullRequest) -> Result<Vec<Review>> { |
| 525 | let mut latest: HashMap<String, Review> = HashMap::new(); |
| 526 | for review in state.store.list_reviews(&pr.issue.id).await? { |
| 527 | if matches!( |
| 528 | review.state, |
| 529 | ReviewState::Approved | ReviewState::ChangesRequested |
| 530 | ) { |
| 531 | latest.insert(review.author_id.clone(), review); |
| 532 | } |
| 533 | } |
| 534 | let mut counted: Vec<Review> = latest.into_values().collect(); |
| 535 | counted.sort_by(|a, b| { |
| 536 | a.submitted_at |
| 537 | .cmp(&b.submitted_at) |
| 538 | .then_with(|| a.id.cmp(&b.id)) |
| 539 | }); |
| 540 | Ok(counted) |
| 541 | } |
| 542 | |
| 543 | // Commits and files |
| 544 | |
| 545 | /// The combined status of the pull request's head commit, `None` when nothing has reported on it. |
| 546 | async fn head_checks( |
| 547 | state: &AppState, |
| 548 | ctx: &RepoCtx, |
| 549 | pr: &PullRequest, |
| 550 | ) -> Result<Option<StatusSummary>> { |
| 551 | let rows = state.store.statuses_for(&ctx.repo.id, &pr.head_oid).await?; |
| 552 | Ok((!rows.is_empty()).then(|| StatusSummary::from_rows(&rows))) |
| 553 | } |
| 554 | |
| 555 | #[component] |
| 556 | async fn commit_list(rows: Vec<CommitRow>, lang: Lang) -> Result<impl View> { |
| 557 | let empty = rows.is_empty(); |
| 558 | let no_commits = g::t(lang, K::NoCommits); |
| 559 | let committed = g::t(lang, K::Committed); |
| 560 | let browse = g::t(lang, K::BrowseFiles); |
| 561 | Ok(view! { |
| 562 | if empty { |
| 563 | <p class="muted">(no_commits)</p> |
| 564 | } else { |
| 565 | <ul class="commit-list"> |
| 566 | for row in rows.iter() { |
| 567 | <li class="commit-row"> |
| 568 | <div class="commit-main"> |
| 569 | <a class="commit-summary" href=(row.commit_href.as_str())>(row.summary.as_str())</a> |
| 570 | <div class="commit-meta muted small"> |
| 571 | <span class="commit-author">(row.author.as_str())</span> |
| 572 | <span>(committed)</span> |
| 573 | <time datetime=(row.iso.as_str()) title=(row.absolute.as_str())>(row.relative.as_str())</time> |
| 574 | </div> |
| 575 | </div> |
| 576 | <div class="commit-actions"> |
| 577 | commit_status(summary: row.status.clone(), lang: StatusLang(lang)) |
| 578 | <a class="mono commit-oid" href=(row.commit_href.as_str())>(row.short.as_str())</a> |
| 579 | <a class="small muted" href=(row.tree_href.as_str())>(browse)</a> |
| 580 | </div> |
| 581 | </li> |
| 582 | } |
| 583 | </ul> |
| 584 | } |
| 585 | }) |
| 586 | } |
| 587 | |
| 588 | // Pages |
| 589 | |
| 590 | /// The Conversation tab. `draft` and `error` belong to the comment form, so a refused comment |
| 591 | /// keeps its text. |
| 592 | async fn pull_conversation( |
| 593 | cx: &Cx, |
| 594 | ctx: RepoCtx, |
| 595 | pr: PullRequest, |
| 596 | draft: String, |
| 597 | error: Option<String>, |
| 598 | merge_error: Option<String>, |
| 599 | ) -> Result<impl View> { |
| 600 | let state = app_context::<AppState>(cx); |
| 601 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); |
| 602 | let commit_count = commits_of(state, &ctx, &pr).await?.len(); |
| 603 | let file_count = diff_of(state, &ctx, &pr).await?.files.len(); |
| 604 | let frame = frame_in(lang, state, &ctx, &pr, commit_count, file_count).await?; |
| 605 | let href = frame.href.clone(); |
| 606 | let owner = ctx.repo.owner_name.clone(); |
| 607 | let name = ctx.repo.name.clone(); |
| 608 | |
| 609 | let discussion = load_discussion( |
| 610 | lang, |
| 611 | state, |
| 612 | &ctx, |
| 613 | &pr.issue, |
| 614 | ItemKind::Pull, |
| 615 | &pr.base_branch, |
| 616 | ) |
| 617 | .await?; |
| 618 | let sidebar = load_sidebar(state, &ctx.repo.id, &pr.issue).await?; |
| 619 | let notify = notify_box_for(state, &ctx, lang, &pr.issue.id, &href).await?; |
| 620 | let reviewers = load_reviewers(cx, state, &ctx, &pr.issue, &href).await?; |
| 621 | let csrf = csrf_of(&ctx); |
| 622 | let checks = head_checks(state, &ctx, &pr).await?; |
| 623 | let archived = ctx.repo.archived; |
| 624 | let signed_in = ctx.viewer.is_some(); |
| 625 | let merged = is_merged(&pr); |
| 626 | let open = matches!(pr.issue.state, IssueState::Open) && !merged; |
| 627 | let can_comment = signed_in && !archived && may_converse(&ctx, &pr.issue); |
| 628 | let locked_for_viewer = !may_converse(&ctx, &pr.issue); |
| 629 | let lock_notice = lock_message(lang, &pr.issue); |
| 630 | let can_close = may_change(&ctx, &pr.issue.author_id) && !merged; |
| 631 | let write_meta = !archived && triage(&ctx); |
| 632 | let comment_action = format!("{href}/comments"); |
| 633 | let state_action = format!("{href}/state"); |
| 634 | let login_href = "/login".to_owned(); |
| 635 | let archived_text = g::t(lang, K::ArchivedReadOnly); |
| 636 | let login_before = g::t(lang, K::LoginBefore); |
| 637 | let login_link = g::t(lang, K::LoginLink); |
| 638 | let login_after = g::t(lang, K::LoginAfter); |
| 639 | |
| 640 | let (headline, tone, conflicts, reload) = match pr.mergeable { |
| 641 | Mergeable::Clean => (g::t(lang, K::MergeClean).to_owned(), "ok", Vec::new(), None), |
| 642 | Mergeable::Conflict => ( |
| 643 | g::t(lang, K::MergeConflict).to_owned(), |
| 644 | "bad", |
| 645 | pr.conflict_files.clone(), |
| 646 | None, |
| 647 | ), |
| 648 | Mergeable::UpToDate => ( |
| 649 | g::t(lang, K::MergeUpToDate).to_owned(), |
| 650 | "muted", |
| 651 | Vec::new(), |
| 652 | None, |
| 653 | ), |
| 654 | Mergeable::Unknown | Mergeable::Merged => ( |
| 655 | g::t(lang, K::MergeChecking).to_owned(), |
| 656 | "muted", |
| 657 | Vec::new(), |
| 658 | Some(href.clone()), |
| 659 | ), |
| 660 | }; |
| 661 | let can_write = !archived |
| 662 | && authorize( |
| 663 | viewer(&ctx), |
| 664 | &ctx.repo, |
| 665 | ctx.role, |
| 666 | ctx.org_role, |
| 667 | Action::Write, |
| 668 | ) |
| 669 | .is_ok(); |
| 670 | // The merge rules of the base branch: approvals, change requests and up-to-date status. |
| 671 | let gate = if open { |
| 672 | Some(merge_gate(state, &ctx.repo, &pr).await?) |
| 673 | } else { |
| 674 | None |
| 675 | }; |
| 676 | // A branch that requires the merge queue tests the pull request on the current tip, so an |
| 677 | // outdated head does not block it. |
| 678 | let queue_required = |
| 679 | crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?; |
| 680 | let queue_blocker = gate.as_ref().and_then(|gate| { |
| 681 | gate.blockers() |
| 682 | .into_iter() |
| 683 | .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE)) |
| 684 | }); |
| 685 | let blocked = if queue_required { |
| 686 | queue_blocker.and_then(|code| merge_error_text(lang, code)) |
| 687 | } else { |
| 688 | gate.as_ref() |
| 689 | .and_then(|gate| gate.blocked()) |
| 690 | .and_then(|code| merge_error_text(lang, code)) |
| 691 | } |
| 692 | .map(str::to_owned); |
| 693 | let approvals = gate |
| 694 | .as_ref() |
| 695 | .filter(|gate| gate.rule.required_approvals > 0) |
| 696 | .map(|gate| { |
| 697 | g::approvals_of( |
| 698 | lang, |
| 699 | gate.approvals.min(gate.rule.required_approvals), |
| 700 | gate.rule.required_approvals, |
| 701 | ) |
| 702 | }); |
| 703 | let auto_merge_user = match pr.auto_merge.as_ref() { |
| 704 | Some(auto) => state |
| 705 | .store |
| 706 | .usernames_by_ids(std::slice::from_ref(&auto.user_id)) |
| 707 | .await? |
| 708 | .get(&auto.user_id) |
| 709 | .map(|(display, _)| display.clone()) |
| 710 | .unwrap_or_else(|| g::t(lang, K::Unknown).to_owned()), |
| 711 | None => String::new(), |
| 712 | }; |
| 713 | let required: Vec<CheckRow> = gate |
| 714 | .as_ref() |
| 715 | .map(|gate| { |
| 716 | gate.required |
| 717 | .iter() |
| 718 | .map(|check| { |
| 719 | let (class, label) = match check.state { |
| 720 | Some(StatusState::Success) => ("check-ok", g::t(lang, K::CheckPassing)), |
| 721 | Some(StatusState::Pending) => { |
| 722 | ("check-pending", g::t(lang, K::CheckPending)) |
| 723 | } |
| 724 | Some(StatusState::Failure) => ("check-bad", g::t(lang, K::CheckFailing)), |
| 725 | Some(StatusState::Error) => ("check-bad", g::t(lang, K::CheckErrored)), |
| 726 | None => ("check-pending", g::t(lang, K::CheckMissing)), |
| 727 | }; |
| 728 | CheckRow { |
| 729 | context: check.context.clone(), |
| 730 | label, |
| 731 | class, |
| 732 | } |
| 733 | }) |
| 734 | .collect() |
| 735 | }) |
| 736 | .unwrap_or_default(); |
| 737 | let auto_waiting = gate |
| 738 | .as_ref() |
| 739 | .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only()); |
| 740 | let queue_entry = match (open, queue_required) { |
| 741 | (true, true) => state.store.queue_entry_for_pull(&pr.issue.id).await?, |
| 742 | _ => None, |
| 743 | }; |
| 744 | let queue_position = match queue_entry.as_ref() { |
| 745 | Some(entry) => state |
| 746 | .store |
| 747 | .queue_for_branch(&ctx.repo.id, &entry.branch) |
| 748 | .await? |
| 749 | .iter() |
| 750 | .position(|waiting| waiting.id == entry.id) |
| 751 | .map(|index| index + 1), |
| 752 | None => None, |
| 753 | }; |
| 754 | let queue_can_add = open |
| 755 | && can_write |
| 756 | && queue_required |
| 757 | && queue_entry.is_none() |
| 758 | && pr.mergeable != Mergeable::Conflict |
| 759 | && pr.head_repo_id.is_some() |
| 760 | && blocked.is_none(); |
| 761 | let flow = FlowView { |
| 762 | queue_position: queue_position.filter(|_| can_write).map(|position| { |
| 763 | ( |
| 764 | crate::i18n::merge_queue::position_text(lang, position), |
| 765 | format!("{href}/merge-queue/remove"), |
| 766 | ) |
| 767 | }), |
| 768 | queue_add: queue_can_add.then(|| format!("{href}/merge-queue")), |
| 769 | csrf: csrf.clone(), |
| 770 | draft_toggle: (open |
| 771 | && !archived |
| 772 | && ctx |
| 773 | .viewer |
| 774 | .as_ref() |
| 775 | .is_some_and(|(user, _)| can_write || user.id == pr.issue.author_id)) |
| 776 | .then(|| { |
| 777 | if pr.draft { |
| 778 | (format!("{href}/ready"), g::t(lang, K::ReadyForReview)) |
| 779 | } else { |
| 780 | (format!("{href}/draft"), g::t(lang, K::ConvertToDraft)) |
| 781 | } |
| 782 | }), |
| 783 | auto_on: pr |
| 784 | .auto_merge |
| 785 | .as_ref() |
| 786 | .filter(|_| open && can_write) |
| 787 | .map(|auto| { |
| 788 | ( |
| 789 | g::auto_merge_on(lang, auto.style.as_str(), &auto_merge_user), |
| 790 | format!("{href}/auto-merge/disable"), |
| 791 | ) |
| 792 | }), |
| 793 | auto_enable: (open |
| 794 | && can_write |
| 795 | && !queue_required |
| 796 | && pr.auto_merge.is_none() |
| 797 | && auto_waiting |
| 798 | && pr.mergeable != Mergeable::Conflict |
| 799 | && pr.head_repo_id.is_some()) |
| 800 | .then(|| format!("{href}/auto-merge")), |
| 801 | }; |
| 802 | let merge_form = if open |
| 803 | && can_write |
| 804 | && !queue_required |
| 805 | && pr.mergeable == Mergeable::Clean |
| 806 | && pr.head_repo_id.is_some() |
| 807 | && blocked.is_none() |
| 808 | { |
| 809 | let ff = is_ancestor(&state.git, &ctx.path, &pr.base_oid, &pr.head_oid).await?; |
| 810 | Some(MergeForm { |
| 811 | action: format!("{href}/merge"), |
| 812 | csrf: csrf.clone(), |
| 813 | ff, |
| 814 | }) |
| 815 | } else { |
| 816 | None |
| 817 | }; |
| 818 | |
| 819 | let merged_who = match pr.merged_by.clone() { |
| 820 | Some(id) => state |
| 821 | .store |
| 822 | .usernames_by_ids(std::slice::from_ref(&id)) |
| 823 | .await? |
| 824 | .get(&id) |
| 825 | .map(|(display, _)| display.clone()) |
| 826 | .unwrap_or_else(|| g::t(lang, K::Unknown).to_owned()), |
| 827 | None => g::t(lang, K::Unknown).to_owned(), |
| 828 | }; |
| 829 | let merged_when = pr |
| 830 | .merged_at |
| 831 | .as_deref() |
| 832 | .map(|stamp| When::new(lang, stamp, ctx.viewer_tz(), now_unix())); |
| 833 | let merge_commit = pr.merge_commit.clone().unwrap_or_default(); |
| 834 | let merge_commit_href = format!("/{owner}/{name}/commit/{merge_commit}"); |
| 835 | |
| 836 | let review_error = review_error_from(lang, cx); |
| 837 | let summary = state.store.review_summary(&pr.issue.id).await?; |
| 838 | let approved = (!summary.approved_by.is_empty()) |
| 839 | .then(|| g::approved_by(lang, &summary.approved_by.join(", "))); |
| 840 | let changes = (!summary.changes_requested_by.is_empty()) |
| 841 | .then(|| g::changes_requested_by(lang, &summary.changes_requested_by.join(", "))); |
| 842 | let review_box_shown = approved.is_some() || changes.is_some(); |
| 843 | // Dismiss forms are for Write holders on an open pull request. |
| 844 | let dismiss: Vec<DismissRow> = if open && can_write { |
| 845 | counted_reviews(state, &pr) |
| 846 | .await? |
| 847 | .into_iter() |
| 848 | .map(|review| DismissRow { |
| 849 | action: format!("{href}/reviews/{}/dismiss", review.id), |
| 850 | label: g::dismiss_reason(lang, &review.author_name), |
| 851 | }) |
| 852 | .collect() |
| 853 | } else { |
| 854 | Vec::new() |
| 855 | }; |
| 856 | |
| 857 | let branch = pull_branch::branch_action(state, &ctx, &pr, &csrf).await?; |
| 858 | let branch_error = branch_error_from(cx, lang); |
| 859 | let branch_shown = !open && (branch.is_some() || branch_error.is_some()); |
| 860 | |
| 861 | let page_title = frame.page_title.clone(); |
| 862 | let header = ctx.head(state, "pulls").await?; |
| 863 | let labels_href = repo_href(&owner, &name, "labels.css", ""); |
| 864 | // The conversation follows the pull request's event stream: a change re-renders it. |
| 865 | let live = format!("{href}/events"); |
| 866 | Ok(view! { cx => |
| 867 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()), |
| 868 | repo_head(head: header) |
| 869 | pull_header(frame: frame.clone()) |
| 870 | pull_subnav_in(lang: lang, href: href.clone(), active: "conversation".to_owned(), |
| 871 | commits: commit_count, files: file_count) |
| 872 | if let Some(message) = review_error { |
| 873 | alert(message: message) |
| 874 | } |
| 875 | <div class="issue-layout" data-live=(live.as_str())> |
| 876 | <div class="issue-column"> |
| 877 | discussion_timeline(lang: lang, discussion: discussion) |
| 878 | if review_box_shown { |
| 879 | review_box(approved: approved, changes: changes, dismiss: dismiss, |
| 880 | csrf: csrf.clone(), lang: lang) |
| 881 | } |
| 882 | if open { |
| 883 | merge_box(headline: headline, tone: tone.to_owned(), conflicts: conflicts, |
| 884 | reload: reload, form: merge_form, merge_error: merge_error, |
| 885 | approvals: approvals, blocked: blocked, checks: checks, |
| 886 | required: required, flow: flow, lang: lang) |
| 887 | } |
| 888 | if let Some(when) = merged_when { |
| 889 | merged_notice(who: merged_who, when: when, commit: merge_commit, |
| 890 | commit_href: merge_commit_href, lang: lang) |
| 891 | } |
| 892 | if branch_shown { |
| 893 | branch_box(lang: lang, action: branch, error: branch_error) |
| 894 | } |
| 895 | if can_comment { |
| 896 | comment_form(lang: lang, action: comment_action, state_action: state_action, |
| 897 | csrf: csrf.clone(), draft: draft, error: error, can_close: can_close, open: open) |
| 898 | } |
| 899 | if archived { |
| 900 | <p class="muted">(archived_text)</p> |
| 901 | } |
| 902 | if locked_for_viewer { |
| 903 | <p class="muted">(lock_notice.as_str())</p> |
| 904 | } else if !signed_in { |
| 905 | <p class="muted">(login_before)<a href=(login_href.as_str())>(login_link)</a>(login_after)</p> |
| 906 | } |
| 907 | </div> |
| 908 | <aside class="issue-sidebar"> |
| 909 | item_sidebar(lang: lang, write: write_meta, base: href.clone(), csrf: csrf.clone(), sidebar: sidebar, notify: notify) |
| 910 | reviewers_box(lang: lang, reviewers: reviewers) |
| 911 | </aside> |
| 912 | </div> |
| 913 | ) |
| 914 | }) |
| 915 | } |
| 916 | |
| 917 | /// The message for a `merge_error` code set by `pulls_merge`. Unknown codes have no message, so a |
| 918 | /// crafted query value shows nothing. |
| 919 | fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> { |
| 920 | Some(match code { |
| 921 | ERR_CONFLICT => g::t(lang, K::ErrConflict), |
| 922 | ERR_UP_TO_DATE => g::t(lang, K::ErrUpToDate), |
| 923 | ERR_FF_IMPOSSIBLE => g::t(lang, K::ErrFfImpossible), |
| 924 | ERR_BASE_MOVED => g::t(lang, K::ErrBaseMoved), |
| 925 | ERR_ALREADY_MERGED => g::t(lang, K::ErrAlreadyMerged), |
| 926 | ERR_NOT_OPEN => g::t(lang, K::ErrNotOpen), |
| 927 | ERR_HEAD_MISSING => g::t(lang, K::ErrHeadMissing), |
| 928 | ERR_BASE_MISSING => g::t(lang, K::ErrBaseMissing), |
| 929 | ERR_NEEDS_APPROVALS => g::t(lang, K::ErrNeedsApprovals), |
| 930 | ERR_CHANGES_REQUESTED => g::t(lang, K::ErrChangesRequested), |
| 931 | ERR_NOT_UP_TO_DATE => g::t(lang, K::ErrNotUpToDate), |
| 932 | ERR_MESSAGE_INVALID => g::t(lang, K::ErrMessageInvalid), |
| 933 | ERR_DRAFT => g::t(lang, K::ErrDraft), |
| 934 | ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks), |
| 935 | ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict), |
| 936 | ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked), |
| 937 | ERR_QUEUE_REQUIRED => { |
| 938 | crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueRequired) |
| 939 | } |
| 940 | ERR_QUEUE_ALREADY => { |
| 941 | crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueAlready) |
| 942 | } |
| 943 | _ => return None, |
| 944 | }) |
| 945 | } |
| 946 | |
| 947 | /// The message for the `merge_error` query value of the request, when it is a known code. |
| 948 | fn merge_error_from(lang: Lang, cx: &Cx) -> Option<String> { |
| 949 | let request = uri(cx); |
| 950 | let query = request.query()?; |
| 951 | let (_, code) = |
| 952 | form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "merge_error")?; |
| 953 | merge_error_text(lang, &code).map(str::to_owned) |
| 954 | } |
| 955 | |
| 956 | /// The message for the `review_error` query value of the request, when it is a known code. |
| 957 | fn review_error_from(lang: Lang, cx: &Cx) -> Option<&'static str> { |
| 958 | let request = uri(cx); |
| 959 | let query = request.query()?; |
| 960 | let (_, code) = |
| 961 | form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "review_error")?; |
| 962 | error_text_in(lang, &code) |
| 963 | } |
| 964 | |
| 965 | #[page("/{owner}/{repo}/pulls/{number}")] |
| 966 | async fn pull_show(cx: &Cx) -> Result<impl View> { |
| 967 | let (ctx, pr) = load_pull(cx).await?; |
| 968 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); |
| 969 | let merge_error = merge_error_from(lang, cx); |
| 970 | pull_conversation(cx, ctx, pr, String::new(), None, merge_error).await |
| 971 | } |
| 972 | |
| 973 | #[page("/{owner}/{repo}/pulls/{number}/commits")] |
| 974 | async fn pull_commits(cx: &Cx) -> Result<impl View> { |
| 975 | let (ctx, pr) = load_pull(cx).await?; |
| 976 | let state = app_context::<AppState>(cx); |
| 977 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); |
| 978 | let commits = commits_of(state, &ctx, &pr).await?; |
| 979 | let file_count = diff_of(state, &ctx, &pr).await?.files.len(); |
| 980 | let frame = frame_in(lang, state, &ctx, &pr, commits.len(), file_count).await?; |
| 981 | |
| 982 | let owner = ctx.repo.owner_name.clone(); |
| 983 | let name = ctx.repo.name.clone(); |
| 984 | let tz = ctx.viewer_tz().to_owned(); |
| 985 | let now = now_secs(); |
| 986 | let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect(); |
| 987 | let statuses = state |
| 988 | .store |
| 989 | .statuses_for_many_rows(&ctx.repo.id, &oids) |
| 990 | .await?; |
| 991 | let rows: Vec<CommitRow> = commits |
| 992 | .iter() |
| 993 | .map(|info| { |
| 994 | CommitRow::new(&owner, &name, info, now, &tz, lang).with_statuses(&statuses, &info.oid) |
| 995 | }) |
| 996 | .collect(); |
| 997 | |
| 998 | let page_title = frame.page_title.clone(); |
| 999 | let href = frame.href.clone(); |
| 1000 | let header = ctx.head(state, "pulls").await?; |
| 1001 | Ok(view! { |
| 1002 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 1003 | repo_head(head: header) |
| 1004 | pull_header(frame: frame.clone()) |
| 1005 | pull_subnav_in(lang: lang, href: href, active: "commits".to_owned(), |
| 1006 | commits: frame.commit_count, files: frame.file_count) |
| 1007 | commit_list(rows: rows, lang: lang) |
| 1008 | ) |
| 1009 | }) |
| 1010 | } |
| 1011 | |
| 1012 | /// Adds a comment and/or changes the state of a pull request. Shared by the comment and state |
| 1013 | /// routes. A merged pull request's state cannot change, and a refused comment re-renders the |
| 1014 | /// Conversation with its text. |
| 1015 | async fn pull_post(cx: &Cx, form: CommentForm) -> Result<impl View> { |
| 1016 | let number = parse_number(path_param::<Number>(cx))?; |
| 1017 | let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?; |
| 1018 | let (user, session) = require_user(cx).await?; |
| 1019 | check_write(&ctx, &session, &form.csrf)?; |
| 1020 | let state = app_context::<AppState>(cx); |
| 1021 | let pr = pull_for(state, &ctx, number).await?; |
| 1022 | let lang = i18n::lang(cx, Some(&user)); |
| 1023 | |
| 1024 | let changes_state = !matches!(form.action.as_str(), "" | "comment"); |
| 1025 | let posted = if changes_state && is_merged(&pr) { |
| 1026 | Posted::Refused { |
| 1027 | message: g::t(lang, K::MergedCannotChange).to_owned(), |
| 1028 | } |
| 1029 | } else { |
| 1030 | post_comment(lang, state, &ctx, &user, &pr.issue, true, &form).await? |
| 1031 | }; |
| 1032 | match posted { |
| 1033 | Posted::Saved { comment_id } => { |
| 1034 | let anchor = match comment_id { |
| 1035 | Some(id) => format!("comment-{id}"), |
| 1036 | None => format!("pull-{number}"), |
| 1037 | }; |
| 1038 | Err(see_other(format!( |
| 1039 | "{}#{anchor}", |
| 1040 | item_href(&ctx, ItemKind::Pull, number) |
| 1041 | )) |
| 1042 | .into()) |
| 1043 | } |
| 1044 | Posted::Refused { message } => { |
| 1045 | pull_conversation(cx, ctx, pr, form.body, Some(message), None).await |
| 1046 | } |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | /// Comments on a pull request (`/{owner}/{repo}/pulls/{n}/comments`). |
| 1051 | #[page(POST "/{owner}/{repo}/pulls/{number}/comments")] |
| 1052 | async fn pull_comment(cx: &Cx, Form(form): Form<CommentForm>) -> Result<impl View> { |
| 1053 | pull_post(cx, form).await |
| 1054 | } |
| 1055 | |
| 1056 | /// Closes or reopens a pull request, with an optional comment (`/{owner}/{repo}/pulls/{n}/state`). |
| 1057 | #[page(POST "/{owner}/{repo}/pulls/{number}/state")] |
| 1058 | async fn pull_state(cx: &Cx, Form(form): Form<CommentForm>) -> Result<impl View> { |
| 1059 | pull_post(cx, form).await |
| 1060 | } |
| 1061 | |
| 1062 | #[cfg(test)] |
| 1063 | mod tests { |
| 1064 | use forge_core::{IssueState, Mergeable, PullRequest, ReviewState, Side, User, Visibility}; |
| 1065 | use forge_git::GitEnv; |
| 1066 | use topcoat::router::request::Request; |
| 1067 | use topcoat::router::{Body, Router, to_bytes}; |
| 1068 | |
| 1069 | use crate::auth::{SESSION_COOKIE, percent_encode}; |
| 1070 | use crate::pages::commits::test_support::{Fixture, OWNER, REPO, git}; |
| 1071 | |
| 1072 | fn cookie(token: &str) -> String { |
| 1073 | format!("__Host-{SESSION_COOKIE}={token}") |
| 1074 | } |
| 1075 | |
| 1076 | /// The page's own `<main>` element. The shell's header also echoes the request URL |
| 1077 | /// (theme form `back` field), so checks about the page body are scoped to `<main>`. |
| 1078 | fn page_main(body: &str) -> &str { |
| 1079 | body.split_once("<main tabindex=\"-1\">") |
| 1080 | .and_then(|(_, rest)| rest.split_once("</main>")) |
| 1081 | .map(|(main, _)| main) |
| 1082 | .expect("page has a <main> element") |
| 1083 | } |
| 1084 | |
| 1085 | /// Sends one request through the router and returns `(status, location, body)`. |
| 1086 | async fn send( |
| 1087 | router: &Router, |
| 1088 | method: &str, |
| 1089 | uri: &str, |
| 1090 | token: Option<&str>, |
| 1091 | form: Option<String>, |
| 1092 | ) -> (u16, Option<String>, String) { |
| 1093 | let mut req = Request::builder().method(method).uri(uri); |
| 1094 | if let Some(token) = token { |
| 1095 | req = req.header("cookie", cookie(token)); |
| 1096 | } |
| 1097 | let body = match form { |
| 1098 | Some(form) => { |
| 1099 | req = req.header("content-type", "application/x-www-form-urlencoded"); |
| 1100 | Body::from(form) |
| 1101 | } |
| 1102 | None => Body::empty(), |
| 1103 | }; |
| 1104 | let res = router.handle(req.body(body).unwrap()).await; |
| 1105 | let status = res.status().as_u16(); |
| 1106 | let location = res |
| 1107 | .headers() |
| 1108 | .get("location") |
| 1109 | .map(|v| v.to_str().unwrap().to_owned()); |
| 1110 | let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); |
| 1111 | ( |
| 1112 | status, |
| 1113 | location, |
| 1114 | String::from_utf8_lossy(&bytes).into_owned(), |
| 1115 | ) |
| 1116 | } |
| 1117 | |
| 1118 | /// A user with a session whose CSRF token is `{token}-csrf`. |
| 1119 | async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User { |
| 1120 | let user = fx |
| 1121 | .store |
| 1122 | .create_user(name, None, "not-a-real-hash", false) |
| 1123 | .await |
| 1124 | .unwrap(); |
| 1125 | crate::test_support::create_session(&fx.store, &user.id, token, &format!("{token}-csrf")) |
| 1126 | .await; |
| 1127 | user |
| 1128 | } |
| 1129 | |
| 1130 | /// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`). |
| 1131 | async fn owner_session(fx: &Fixture) { |
| 1132 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 1133 | crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await; |
| 1134 | } |
| 1135 | |
| 1136 | fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String { |
| 1137 | let mut form = format!("csrf={}", percent_encode(&format!("{token}-csrf"))); |
| 1138 | for (key, value) in pairs { |
| 1139 | form.push_str(&format!("&{key}={}", percent_encode(value))); |
| 1140 | } |
| 1141 | form |
| 1142 | } |
| 1143 | |
| 1144 | async fn pull(fx: &Fixture, number: i64) -> PullRequest { |
| 1145 | let repo = fx |
| 1146 | .store |
| 1147 | .repo_by_owner_and_name(OWNER, REPO) |
| 1148 | .await |
| 1149 | .unwrap() |
| 1150 | .unwrap(); |
| 1151 | fx.store |
| 1152 | .pull_by_number(&repo.id, number) |
| 1153 | .await |
| 1154 | .unwrap() |
| 1155 | .unwrap() |
| 1156 | } |
| 1157 | |
| 1158 | /// Pushes a `feature` branch (one commit on top of the root, adding `feat.txt`) and opens a |
| 1159 | /// pull request for it against `main`. Returns the pull request number. |
| 1160 | async fn open_pull(fx: &Fixture) -> i64 { |
| 1161 | let base_oid = git(&fx.work, &["rev-parse", "HEAD"]); |
| 1162 | git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); |
| 1163 | std::fs::write(fx.work.join("feat.txt"), "feature\n").unwrap(); |
| 1164 | git(&fx.work, &["add", "-A"]); |
| 1165 | git(&fx.work, &["commit", "-q", "-m", "Add feature file"]); |
| 1166 | let head_oid = git(&fx.work, &["rev-parse", "HEAD"]); |
| 1167 | git( |
| 1168 | &fx.work, |
| 1169 | &[ |
| 1170 | "push", |
| 1171 | "-q", |
| 1172 | &fx.bare.to_string_lossy(), |
| 1173 | "HEAD:refs/heads/feature", |
| 1174 | ], |
| 1175 | ); |
| 1176 | |
| 1177 | let repo = fx |
| 1178 | .store |
| 1179 | .repo_by_owner_and_name(OWNER, REPO) |
| 1180 | .await |
| 1181 | .unwrap() |
| 1182 | .unwrap(); |
| 1183 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 1184 | let pr = fx |
| 1185 | .store |
| 1186 | .create_pull( |
| 1187 | &repo.id, |
| 1188 | &owner.id, |
| 1189 | "Add feature", |
| 1190 | "Body text", |
| 1191 | "main", |
| 1192 | &repo.id, |
| 1193 | "feature", |
| 1194 | &head_oid, |
| 1195 | &base_oid, |
| 1196 | ) |
| 1197 | .await |
| 1198 | .unwrap(); |
| 1199 | let env = GitEnv { |
| 1200 | git_bin: "git".into(), |
| 1201 | data_dir: fx.work.clone(), |
| 1202 | }; |
| 1203 | forge_git::pulls::fetch_into_pull_ref(&env, &fx.bare, &fx.bare, &head_oid, pr.issue.number) |
| 1204 | .await |
| 1205 | .unwrap(); |
| 1206 | pr.issue.number |
| 1207 | } |
| 1208 | |
| 1209 | /// Conversation tab, merge box, merge and review error codes, and the read-only tabs, on one |
| 1210 | /// open pull. Mergeability is set by each scenario right before it is checked. |
| 1211 | #[tokio::test] |
| 1212 | async fn conversation_merge_box_and_error_codes_on_one_pull() { |
| 1213 | let fx = Fixture::new(Visibility::Public).await; |
| 1214 | owner_session(&fx).await; |
| 1215 | sign_in(&fx, "bob", "bob-token").await; |
| 1216 | let number = open_pull(&fx).await; |
| 1217 | let pr = pull(&fx, number).await; |
| 1218 | let uri = format!("/tahinli/demo/pulls/{number}"); |
| 1219 | |
| 1220 | // Turkish viewers get the translated tabs. |
| 1221 | let req = Request::builder() |
| 1222 | .method("GET") |
| 1223 | .uri(uri.as_str()) |
| 1224 | .header("accept-language", "tr") |
| 1225 | .body(Body::empty()) |
| 1226 | .unwrap(); |
| 1227 | let res = fx.router.handle(req).await; |
| 1228 | let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); |
| 1229 | let body = String::from_utf8_lossy(&bytes).into_owned(); |
| 1230 | assert!(body.contains("Tartışma</a>"), "turkish conversation tab"); |
| 1231 | assert!(body.contains("Commitler "), "turkish commits tab"); |
| 1232 | assert!(body.contains("Değişen dosyalar "), "turkish files tab"); |
| 1233 | assert!(!body.contains(">Conversation<"), "no English tab label"); |
| 1234 | |
| 1235 | // A conflict lists the files and offers no merge. |
| 1236 | fx.store |
| 1237 | .set_mergeability( |
| 1238 | &pr.issue.id, |
| 1239 | &pr.base_oid, |
| 1240 | Some(&fx.root), |
| 1241 | Mergeable::Conflict, |
| 1242 | &["feat.txt".to_owned()], |
| 1243 | ) |
| 1244 | .await |
| 1245 | .unwrap(); |
| 1246 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1247 | assert_eq!(status, 200, "conflict"); |
| 1248 | assert!( |
| 1249 | body.contains("This branch has conflicts that must be resolved"), |
| 1250 | "conflict: {body}" |
| 1251 | ); |
| 1252 | assert!(body.contains("<code>feat.txt</code>"), "conflict: {body}"); |
| 1253 | assert!( |
| 1254 | !body.contains(&format!("action=\"{uri}/merge\"")), |
| 1255 | "conflict: {body}" |
| 1256 | ); |
| 1257 | assert!(!body.contains("name=\"style\""), "conflict: {body}"); |
| 1258 | |
| 1259 | // A clean branch shows the title, badge, merge box and conversation form. |
| 1260 | fx.store |
| 1261 | .set_mergeability( |
| 1262 | &pr.issue.id, |
| 1263 | &pr.base_oid, |
| 1264 | Some(&fx.root), |
| 1265 | Mergeable::Clean, |
| 1266 | &[], |
| 1267 | ) |
| 1268 | .await |
| 1269 | .unwrap(); |
| 1270 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1271 | assert_eq!(status, 200, "clean"); |
| 1272 | assert!(body.contains("Add feature"), "clean: {body}"); |
| 1273 | assert!( |
| 1274 | body.contains("issue-badge issue-badge-open"), |
| 1275 | "clean: {body}" |
| 1276 | ); |
| 1277 | assert!( |
| 1278 | body.contains("This branch has no conflicts with the base branch"), |
| 1279 | "clean: {body}" |
| 1280 | ); |
| 1281 | assert!( |
| 1282 | body.contains(&format!("action=\"{uri}/merge\"")), |
| 1283 | "clean: {body}" |
| 1284 | ); |
| 1285 | assert!(body.contains("name=\"style\""), "clean: {body}"); |
| 1286 | assert!( |
| 1287 | body.contains(&format!("action=\"{uri}/comments\"")), |
| 1288 | "clean: {body}" |
| 1289 | ); |
| 1290 | assert!(body.contains("Commits 1"), "clean: {body}"); |
| 1291 | assert!(body.contains("Files changed 1"), "clean: {body}"); |
| 1292 | |
| 1293 | // A reader sees the clean status but no merge form. |
| 1294 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("bob-token"), None).await; |
| 1295 | assert_eq!(status, 200, "reader"); |
| 1296 | assert!( |
| 1297 | body.contains("This branch has no conflicts with the base branch"), |
| 1298 | "reader: {body}" |
| 1299 | ); |
| 1300 | assert!(!body.contains("name=\"style\""), "reader: {body}"); |
| 1301 | assert!(!body.contains("Merge pull request"), "reader: {body}"); |
| 1302 | |
| 1303 | // Known merge error codes show their message, unknown ones show nothing. |
| 1304 | let (status, _, body) = send( |
| 1305 | &fx.router, |
| 1306 | "GET", |
| 1307 | &format!("{uri}?merge_error=conflict"), |
| 1308 | Some("tahinli"), |
| 1309 | None, |
| 1310 | ) |
| 1311 | .await; |
| 1312 | assert_eq!(status, 200, "merge error"); |
| 1313 | assert!( |
| 1314 | body.contains("class=\"alert merge-error\""), |
| 1315 | "merge error: {body}" |
| 1316 | ); |
| 1317 | assert!( |
| 1318 | body.contains("This branch has conflicts that must be resolved"), |
| 1319 | "merge error: {body}" |
| 1320 | ); |
| 1321 | let (status, _, body) = send( |
| 1322 | &fx.router, |
| 1323 | "GET", |
| 1324 | &format!("{uri}?merge_error=%3Cscript%3Ealert(1)%3C%2Fscript%3E"), |
| 1325 | Some("tahinli"), |
| 1326 | None, |
| 1327 | ) |
| 1328 | .await; |
| 1329 | assert_eq!(status, 200, "unknown merge error"); |
| 1330 | assert!(!body.contains("merge-error"), "unknown merge error: {body}"); |
| 1331 | assert!( |
| 1332 | !page_main(&body).contains("alert(1)"), |
| 1333 | "unknown merge error: {body}" |
| 1334 | ); |
| 1335 | |
| 1336 | // Known review error codes show their message, unknown ones show nothing. |
| 1337 | let (status, _, body) = send( |
| 1338 | &fx.router, |
| 1339 | "GET", |
| 1340 | &format!("{uri}?review_error=own_pr"), |
| 1341 | Some("tahinli"), |
| 1342 | None, |
| 1343 | ) |
| 1344 | .await; |
| 1345 | assert_eq!(status, 200, "review error"); |
| 1346 | assert!( |
| 1347 | body.contains("You cannot approve or request changes on your own pull request."), |
| 1348 | "review error: {body}" |
| 1349 | ); |
| 1350 | let (_, _, body) = send( |
| 1351 | &fx.router, |
| 1352 | "GET", |
| 1353 | &format!("{uri}?review_error=%3Cscript%3E"), |
| 1354 | Some("tahinli"), |
| 1355 | None, |
| 1356 | ) |
| 1357 | .await; |
| 1358 | assert!(!body.contains("<script>"), "unknown review error: {body}"); |
| 1359 | assert!( |
| 1360 | !body.contains("You cannot approve"), |
| 1361 | "unknown review error: {body}" |
| 1362 | ); |
| 1363 | |
| 1364 | // The issue URL of a pull redirects to the pull. |
| 1365 | let (status, location, _) = send( |
| 1366 | &fx.router, |
| 1367 | "GET", |
| 1368 | &format!("/tahinli/demo/issues/{number}"), |
| 1369 | None, |
| 1370 | None, |
| 1371 | ) |
| 1372 | .await; |
| 1373 | assert_eq!(status, 303, "issue url"); |
| 1374 | assert_eq!(location.as_deref(), Some(uri.as_str()), "issue url"); |
| 1375 | |
| 1376 | // The commits and files tabs list the change, for anonymous viewers too. |
| 1377 | let (status, _, body) = |
| 1378 | send(&fx.router, "GET", &format!("{uri}/commits"), None, None).await; |
| 1379 | assert_eq!(status, 200, "commits tab"); |
| 1380 | assert!(body.contains("Add feature file"), "commits tab: {body}"); |
| 1381 | let (status, _, body) = send(&fx.router, "GET", &format!("{uri}/files"), None, None).await; |
| 1382 | assert_eq!(status, 200, "files tab"); |
| 1383 | assert!(body.contains("feat.txt"), "files tab: {body}"); |
| 1384 | } |
| 1385 | |
| 1386 | /// Pull comments, state changes and title edits on one pull. The order matters: the comment |
| 1387 | /// count is checked while the pull has no other comments, the title is checked before the |
| 1388 | /// rename, and the state is reopened before the end. |
| 1389 | #[tokio::test] |
| 1390 | async fn comments_state_and_title_edits_on_one_pull() { |
| 1391 | let fx = Fixture::new(Visibility::Public).await; |
| 1392 | owner_session(&fx).await; |
| 1393 | sign_in(&fx, "bob", "bob-token").await; |
| 1394 | let number = open_pull(&fx).await; |
| 1395 | let uri = format!("/tahinli/demo/pulls/{number}"); |
| 1396 | let pr = pull(&fx, number).await; |
| 1397 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 1398 | |
| 1399 | // The author edits and deletes their own pull comment, and the count returns to zero. |
| 1400 | let comment = fx |
| 1401 | .store |
| 1402 | .add_comment(&pr.issue.id, &owner.id, "first draft") |
| 1403 | .await |
| 1404 | .unwrap(); |
| 1405 | let base = format!("{uri}/comments/{}", comment.id); |
| 1406 | let (status, _, _) = send( |
| 1407 | &fx.router, |
| 1408 | "GET", |
| 1409 | &format!("{base}/edit"), |
| 1410 | Some("tahinli"), |
| 1411 | None, |
| 1412 | ) |
| 1413 | .await; |
| 1414 | assert_eq!(status, 200, "comment edit form"); |
| 1415 | let form = csrf_form("tahinli", &[("body", "edited text")]); |
| 1416 | let (status, location, _) = send( |
| 1417 | &fx.router, |
| 1418 | "POST", |
| 1419 | &format!("{base}/edit"), |
| 1420 | Some("tahinli"), |
| 1421 | Some(form), |
| 1422 | ) |
| 1423 | .await; |
| 1424 | assert_eq!(status, 303, "comment edit"); |
| 1425 | assert_eq!( |
| 1426 | location, |
| 1427 | Some(format!( |
| 1428 | "/tahinli/demo/pulls/{number}#comment-{}", |
| 1429 | comment.id |
| 1430 | )), |
| 1431 | "comment edit" |
| 1432 | ); |
| 1433 | let saved = fx |
| 1434 | .store |
| 1435 | .comment_by_id(&pr.issue.id, &comment.id) |
| 1436 | .await |
| 1437 | .unwrap() |
| 1438 | .unwrap(); |
| 1439 | assert_eq!(saved.body, "edited text", "comment edit"); |
| 1440 | assert!(saved.edited, "comment edit"); |
| 1441 | let (status, location, _) = send( |
| 1442 | &fx.router, |
| 1443 | "POST", |
| 1444 | &format!("{base}/delete"), |
| 1445 | Some("tahinli"), |
| 1446 | Some(csrf_form("tahinli", &[])), |
| 1447 | ) |
| 1448 | .await; |
| 1449 | assert_eq!(status, 303, "comment delete"); |
| 1450 | assert_eq!( |
| 1451 | location, |
| 1452 | Some(format!("/tahinli/demo/pulls/{number}")), |
| 1453 | "comment delete" |
| 1454 | ); |
| 1455 | assert!( |
| 1456 | fx.store |
| 1457 | .comment_by_id(&pr.issue.id, &comment.id) |
| 1458 | .await |
| 1459 | .unwrap() |
| 1460 | .is_none(), |
| 1461 | "comment delete" |
| 1462 | ); |
| 1463 | assert_eq!( |
| 1464 | pull(&fx, number).await.issue.comment_count, |
| 1465 | 0, |
| 1466 | "comment delete" |
| 1467 | ); |
| 1468 | |
| 1469 | // Posting a comment saves it. |
| 1470 | let form = csrf_form("tahinli", &[("body", "Looks good to me")]); |
| 1471 | let (status, location, _) = send( |
| 1472 | &fx.router, |
| 1473 | "POST", |
| 1474 | &format!("{uri}/comments"), |
| 1475 | Some("tahinli"), |
| 1476 | Some(form), |
| 1477 | ) |
| 1478 | .await; |
| 1479 | assert_eq!(status, 303, "post comment"); |
| 1480 | assert!( |
| 1481 | location |
| 1482 | .unwrap() |
| 1483 | .starts_with(&format!("/tahinli/demo/pulls/{number}#comment-")), |
| 1484 | "post comment" |
| 1485 | ); |
| 1486 | let comments = fx.store.list_comments(&pr.issue.id).await.unwrap(); |
| 1487 | assert_eq!(comments.len(), 1, "post comment"); |
| 1488 | assert_eq!(comments[0].body, "Looks good to me", "post comment"); |
| 1489 | |
| 1490 | // The issue routes do not accept a pull number. |
| 1491 | let keep = fx |
| 1492 | .store |
| 1493 | .add_comment(&pr.issue.id, &owner.id, "keep me") |
| 1494 | .await |
| 1495 | .unwrap(); |
| 1496 | let (status, _, _) = send( |
| 1497 | &fx.router, |
| 1498 | "GET", |
| 1499 | &format!("/tahinli/demo/issues/{number}/edit"), |
| 1500 | Some("tahinli"), |
| 1501 | None, |
| 1502 | ) |
| 1503 | .await; |
| 1504 | assert_eq!(status, 404, "issue edit route"); |
| 1505 | let form = csrf_form("tahinli", &[("title", "Nope"), ("body", "x")]); |
| 1506 | let (status, _, _) = send( |
| 1507 | &fx.router, |
| 1508 | "POST", |
| 1509 | &format!("/tahinli/demo/issues/{number}/edit"), |
| 1510 | Some("tahinli"), |
| 1511 | Some(form), |
| 1512 | ) |
| 1513 | .await; |
| 1514 | assert_eq!(status, 404, "issue edit post"); |
| 1515 | let issue_base = format!("/tahinli/demo/issues/{number}/comments/{}", keep.id); |
| 1516 | let (status, _, _) = send( |
| 1517 | &fx.router, |
| 1518 | "GET", |
| 1519 | &format!("{issue_base}/edit"), |
| 1520 | Some("tahinli"), |
| 1521 | None, |
| 1522 | ) |
| 1523 | .await; |
| 1524 | assert_eq!(status, 404, "issue comment edit"); |
| 1525 | let (status, _, _) = send( |
| 1526 | &fx.router, |
| 1527 | "POST", |
| 1528 | &format!("{issue_base}/delete"), |
| 1529 | Some("tahinli"), |
| 1530 | Some(csrf_form("tahinli", &[])), |
| 1531 | ) |
| 1532 | .await; |
| 1533 | assert_eq!(status, 404, "issue comment delete"); |
| 1534 | let pr = pull(&fx, number).await; |
| 1535 | assert_eq!(pr.issue.title, "Add feature", "issue routes"); |
| 1536 | assert!( |
| 1537 | fx.store |
| 1538 | .comment_by_id(&pr.issue.id, &keep.id) |
| 1539 | .await |
| 1540 | .unwrap() |
| 1541 | .is_some(), |
| 1542 | "issue routes kept the comment" |
| 1543 | ); |
| 1544 | |
| 1545 | // Close and reopen the pull. |
| 1546 | let uri_state = format!("{uri}/state"); |
| 1547 | let form = csrf_form("tahinli", &[("action", "close_not_planned")]); |
| 1548 | let (status, _, _) = |
| 1549 | send(&fx.router, "POST", &uri_state, Some("tahinli"), Some(form)).await; |
| 1550 | assert_eq!(status, 303, "close"); |
| 1551 | assert!( |
| 1552 | matches!(pull(&fx, number).await.issue.state, IssueState::Closed), |
| 1553 | "close" |
| 1554 | ); |
| 1555 | let form = csrf_form("tahinli", &[("action", "reopen")]); |
| 1556 | let (status, _, _) = |
| 1557 | send(&fx.router, "POST", &uri_state, Some("tahinli"), Some(form)).await; |
| 1558 | assert_eq!(status, 303, "reopen"); |
| 1559 | assert!( |
| 1560 | matches!(pull(&fx, number).await.issue.state, IssueState::Open), |
| 1561 | "reopen" |
| 1562 | ); |
| 1563 | |
| 1564 | // A reader cannot see the edit link, open the edit form, or change the title. |
| 1565 | let (_, _, body) = send(&fx.router, "GET", &uri, Some("bob-token"), None).await; |
| 1566 | assert!( |
| 1567 | !body.contains(&format!("href=\"{uri}/edit\"")), |
| 1568 | "reader edit link" |
| 1569 | ); |
| 1570 | let (status, _, _) = send( |
| 1571 | &fx.router, |
| 1572 | "GET", |
| 1573 | &format!("{uri}/edit"), |
| 1574 | Some("bob-token"), |
| 1575 | None, |
| 1576 | ) |
| 1577 | .await; |
| 1578 | assert_eq!(status, 403, "reader edit form"); |
| 1579 | let form = csrf_form("bob-token", &[("title", "Hijacked"), ("body", "x")]); |
| 1580 | let (status, _, _) = send( |
| 1581 | &fx.router, |
| 1582 | "POST", |
| 1583 | &format!("{uri}/edit"), |
| 1584 | Some("bob-token"), |
| 1585 | Some(form), |
| 1586 | ) |
| 1587 | .await; |
| 1588 | assert_eq!(status, 403, "reader edit post"); |
| 1589 | assert_eq!( |
| 1590 | pull(&fx, number).await.issue.title, |
| 1591 | "Add feature", |
| 1592 | "reader edit" |
| 1593 | ); |
| 1594 | |
| 1595 | // The author edits the title and body. This runs last because it renames the pull. |
| 1596 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1597 | assert_eq!(status, 200, "author edit link"); |
| 1598 | assert!( |
| 1599 | body.contains(&format!("href=\"{uri}/edit\"")), |
| 1600 | "author edit link" |
| 1601 | ); |
| 1602 | let (status, _, body) = send( |
| 1603 | &fx.router, |
| 1604 | "GET", |
| 1605 | &format!("{uri}/edit"), |
| 1606 | Some("tahinli"), |
| 1607 | None, |
| 1608 | ) |
| 1609 | .await; |
| 1610 | assert_eq!(status, 200, "author edit form"); |
| 1611 | assert!(body.contains("Edit pull request"), "author edit form"); |
| 1612 | let form = csrf_form( |
| 1613 | "tahinli", |
| 1614 | &[("title", "Renamed pull"), ("body", "New text")], |
| 1615 | ); |
| 1616 | let (status, location, _) = send( |
| 1617 | &fx.router, |
| 1618 | "POST", |
| 1619 | &format!("{uri}/edit"), |
| 1620 | Some("tahinli"), |
| 1621 | Some(form), |
| 1622 | ) |
| 1623 | .await; |
| 1624 | assert_eq!(status, 303, "author edit"); |
| 1625 | assert_eq!(location.as_deref(), Some(uri.as_str()), "author edit"); |
| 1626 | let pr = pull(&fx, number).await; |
| 1627 | assert_eq!(pr.issue.title, "Renamed pull", "author edit"); |
| 1628 | assert_eq!(pr.issue.body, "New text", "author edit"); |
| 1629 | let events = fx.store.list_events(&pr.issue.id).await.unwrap(); |
| 1630 | assert!( |
| 1631 | events.iter().any(|e| e.kind == "renamed"), |
| 1632 | "author edit event" |
| 1633 | ); |
| 1634 | } |
| 1635 | |
| 1636 | /// A pending review comment by `user`, submitted as a review with `state` and `body`. |
| 1637 | /// Returns the root comment's id. |
| 1638 | async fn submit_thread( |
| 1639 | fx: &Fixture, |
| 1640 | number: i64, |
| 1641 | user: &User, |
| 1642 | state: ReviewState, |
| 1643 | body: &str, |
| 1644 | ) -> String { |
| 1645 | let pr = pull(fx, number).await; |
| 1646 | let root = fx |
| 1647 | .store |
| 1648 | .add_review_comment( |
| 1649 | &pr.issue.id, |
| 1650 | &user.id, |
| 1651 | true, |
| 1652 | "feat.txt", |
| 1653 | Side::New, |
| 1654 | 1, |
| 1655 | &pr.head_oid, |
| 1656 | "@@ -0,0 +1 @@\n+feature", |
| 1657 | "Please rename this", |
| 1658 | ) |
| 1659 | .await |
| 1660 | .unwrap(); |
| 1661 | fx.store |
| 1662 | .submit_review(&pr.issue.id, &user.id, state, body, &pr.head_oid) |
| 1663 | .await |
| 1664 | .unwrap(); |
| 1665 | root.id |
| 1666 | } |
| 1667 | |
| 1668 | async fn all_reviews(fx: &Fixture, number: i64) -> Vec<forge_core::Review> { |
| 1669 | let pr = pull(fx, number).await; |
| 1670 | fx.store.list_reviews(&pr.issue.id).await.unwrap() |
| 1671 | } |
| 1672 | |
| 1673 | /// Review summary, outdated threads and a dismissal on one pull. Bob approves with a thread |
| 1674 | /// that goes outdated, Carol requests changes, then the approval is dismissed. |
| 1675 | #[tokio::test] |
| 1676 | async fn review_summary_outdated_thread_and_dismissal() { |
| 1677 | let fx = Fixture::new(Visibility::Public).await; |
| 1678 | owner_session(&fx).await; |
| 1679 | let bob = sign_in(&fx, "bob", "bob-token").await; |
| 1680 | let carol = sign_in(&fx, "carol", "carol-token").await; |
| 1681 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 1682 | let number = open_pull(&fx).await; |
| 1683 | let pr = pull(&fx, number).await; |
| 1684 | let root = submit_thread(&fx, number, &bob, ReviewState::Approved, "LGTM").await; |
| 1685 | fx.store |
| 1686 | .mark_outdated(&pr.issue.id, std::slice::from_ref(&root)) |
| 1687 | .await |
| 1688 | .unwrap(); |
| 1689 | |
| 1690 | let uri = format!("/tahinli/demo/pulls/{number}"); |
| 1691 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1692 | assert_eq!(status, 200, "approval"); |
| 1693 | assert!(body.contains("approved these changes"), "approval: {body}"); |
| 1694 | assert!(body.contains("LGTM"), "approval: {body}"); |
| 1695 | assert!(body.contains("review-thread"), "approval: {body}"); |
| 1696 | assert!(body.contains("Please rename this"), "approval: {body}"); |
| 1697 | assert!(body.contains("feat.txt:1"), "approval: {body}"); |
| 1698 | assert!(body.contains("@@ -0,0 +1 @@"), "approval: {body}"); |
| 1699 | assert!(body.contains("review-badge-outdated"), "approval: {body}"); |
| 1700 | assert!(body.contains("Approved by bob"), "approval: {body}"); |
| 1701 | |
| 1702 | fx.store |
| 1703 | .submit_review( |
| 1704 | &pr.issue.id, |
| 1705 | &carol.id, |
| 1706 | ReviewState::ChangesRequested, |
| 1707 | "Needs tests", |
| 1708 | &pr.head_oid, |
| 1709 | ) |
| 1710 | .await |
| 1711 | .unwrap(); |
| 1712 | let approval = all_reviews(&fx, number).await.remove(0); |
| 1713 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1714 | assert_eq!(status, 200, "summary"); |
| 1715 | assert!(body.contains("Approved by bob"), "summary: {body}"); |
| 1716 | assert!( |
| 1717 | body.contains("Changes requested by carol"), |
| 1718 | "summary: {body}" |
| 1719 | ); |
| 1720 | assert!( |
| 1721 | body.contains(&format!("action=\"{uri}/reviews/{}/dismiss\"", approval.id)), |
| 1722 | "summary: {body}" |
| 1723 | ); |
| 1724 | |
| 1725 | // A reader sees the summary but no dismiss form. |
| 1726 | let (_, _, body) = send(&fx.router, "GET", &uri, Some("carol-token"), None).await; |
| 1727 | assert!(body.contains("Approved by bob"), "reader summary: {body}"); |
| 1728 | assert!(!body.contains("/dismiss\""), "reader summary: {body}"); |
| 1729 | |
| 1730 | // Dismissing the approval strikes it with its reason. |
| 1731 | fx.store |
| 1732 | .dismiss_review(&approval.id, &owner.id, "superseded") |
| 1733 | .await |
| 1734 | .unwrap(); |
| 1735 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1736 | assert_eq!(status, 200, "dismissal"); |
| 1737 | assert!( |
| 1738 | body.contains("review-verb review-verb-dismissed"), |
| 1739 | "dismissal: {body}" |
| 1740 | ); |
| 1741 | assert!(body.contains("dismissed: superseded"), "dismissal: {body}"); |
| 1742 | assert!(body.contains("LGTM"), "dismissal: {body}"); |
| 1743 | assert!(!body.contains("Approved by bob"), "dismissal: {body}"); |
| 1744 | } |
| 1745 | |
| 1746 | /// A comment-only review gets no entry of its own, and another user's pending comment stays |
| 1747 | /// hidden from the author's view. |
| 1748 | #[tokio::test] |
| 1749 | async fn comment_only_review_and_hidden_pending_comments() { |
| 1750 | let fx = Fixture::new(Visibility::Public).await; |
| 1751 | owner_session(&fx).await; |
| 1752 | let bob = sign_in(&fx, "bob", "bob-token").await; |
| 1753 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 1754 | let number = open_pull(&fx).await; |
| 1755 | let pr = pull(&fx, number).await; |
| 1756 | let root = submit_thread(&fx, number, &bob, ReviewState::Commented, "").await; |
| 1757 | fx.store |
| 1758 | .reply_review_comment(&pr.issue.id, &owner.id, &root, "Done, thanks") |
| 1759 | .await |
| 1760 | .unwrap(); |
| 1761 | assert_eq!( |
| 1762 | all_reviews(&fx, number).await.len(), |
| 1763 | 2, |
| 1764 | "comment-only review" |
| 1765 | ); |
| 1766 | |
| 1767 | let uri = format!("/tahinli/demo/pulls/{number}"); |
| 1768 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1769 | assert_eq!(status, 200, "comment-only review"); |
| 1770 | assert_eq!( |
| 1771 | body.matches("id=\"review-").count(), |
| 1772 | 1, |
| 1773 | "comment-only review: {body}" |
| 1774 | ); |
| 1775 | assert!(body.contains("Done, thanks"), "comment-only review: {body}"); |
| 1776 | assert!( |
| 1777 | body.contains("Please rename this"), |
| 1778 | "comment-only review: {body}" |
| 1779 | ); |
| 1780 | |
| 1781 | fx.store |
| 1782 | .add_review_comment( |
| 1783 | &pr.issue.id, |
| 1784 | &bob.id, |
| 1785 | true, |
| 1786 | "feat.txt", |
| 1787 | Side::New, |
| 1788 | 1, |
| 1789 | &pr.head_oid, |
| 1790 | "@@ -0,0 +1 @@\n+feature", |
| 1791 | "secret draft", |
| 1792 | ) |
| 1793 | .await |
| 1794 | .unwrap(); |
| 1795 | let (status, _, body) = send(&fx.router, "GET", &uri, Some("tahinli"), None).await; |
| 1796 | assert_eq!(status, 200, "hidden pending"); |
| 1797 | assert!(!body.contains("secret draft"), "hidden pending: {body}"); |
| 1798 | } |
| 1799 | } |