| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | use std::{collections::HashMap, time::SystemTime}; |
| 26 | |
| 27 | use crate::domain::{ |
| 28 | Actor, DomainError, IssueComment, IssueCommentId, MergeStrategy, ObjectId, OrgName, |
| 29 | PullRequest, PullRequestComment, PullRequestCommentId, PullRequestId, PullRequestState, |
| 30 | PushEvent, RefName, RepoName, RepoWrite, Repository, closes, |
| 31 | repository::{ |
| 32 | IssueRepository, LabelRepository, MembershipRepository, OrgRepository, PullRequestCounts, |
| 33 | PullRequestRepository, PushEventRepository, RepoRepository, UserRepository, |
| 34 | }, |
| 35 | }; |
| 36 | |
| 37 | use super::{ |
| 38 | access::{Stores, readable_repo, writable_repo}, |
| 39 | error::{Error, Result}, |
| 40 | issue::{CommentView, Handles}, |
| 41 | label::{LabelView, labels_by_pull}, |
| 42 | paging::{Paged, clamp, offset, page_count}, |
| 43 | port::{CommitTreeRequest, GitMerge, GitQuery, MergePreview}, |
| 44 | push::record_push, |
| 45 | }; |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | pub const PULL_LIMIT: usize = 50; |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | pub const MAX_SQUASHED_COMMITS: usize = 50; |
| 59 | |
| 60 | |
| 61 | |
| 62 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 63 | pub struct NewPull { |
| 64 | pub title: String, |
| 65 | pub body: String, |
| 66 | pub source: RefName, |
| 67 | pub target: RefName, |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 73 | pub struct PullEdit { |
| 74 | pub title: String, |
| 75 | pub body: String, |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 84 | pub struct PullSummary { |
| 85 | pub number: crate::domain::IssueNumber, |
| 86 | pub title: String, |
| 87 | pub state: PullRequestState, |
| 88 | |
| 89 | |
| 90 | pub author: Option<OrgName>, |
| 91 | pub created_at: SystemTime, |
| 92 | pub comments: u64, |
| 93 | pub source_branch: RefName, |
| 94 | pub target_branch: RefName, |
| 95 | |
| 96 | |
| 97 | pub labels: Vec<LabelView>, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 103 | pub struct PullList { |
| 104 | |
| 105 | |
| 106 | pub state: PullRequestState, |
| 107 | pub open: u64, |
| 108 | pub merged: u64, |
| 109 | pub closed: u64, |
| 110 | |
| 111 | pub pulls: Paged<PullSummary>, |
| 112 | pub viewer_is_owner: bool, |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | pub filter: Option<LabelView>, |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 128 | pub enum Mergeability { |
| 129 | |
| 130 | NotOpen, |
| 131 | |
| 132 | |
| 133 | |
| 134 | Unsupported, |
| 135 | |
| 136 | |
| 137 | MissingBranch { branch: RefName }, |
| 138 | |
| 139 | NothingToMerge, |
| 140 | |
| 141 | Unrelated, |
| 142 | |
| 143 | |
| 144 | Ready { fast_forward: bool }, |
| 145 | |
| 146 | Conflicted { paths: Vec<String> }, |
| 147 | } |
| 148 | |
| 149 | impl Mergeability { |
| 150 | pub fn is_ready(&self) -> bool { |
| 151 | matches!(self, Self::Ready { .. }) |
| 152 | } |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | pub fn strategies(&self) -> Vec<MergeStrategy> { |
| 161 | match self { |
| 162 | Self::Ready { fast_forward: true } => vec![ |
| 163 | MergeStrategy::FastForward, |
| 164 | MergeStrategy::Merge, |
| 165 | MergeStrategy::Squash, |
| 166 | ], |
| 167 | Self::Ready { |
| 168 | fast_forward: false, |
| 169 | } => vec![MergeStrategy::Merge, MergeStrategy::Squash], |
| 170 | _ => Vec::new(), |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | |
| 176 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 177 | pub struct PullDetail { |
| 178 | pub number: crate::domain::IssueNumber, |
| 179 | pub title: String, |
| 180 | pub body: String, |
| 181 | pub state: PullRequestState, |
| 182 | pub author: Option<OrgName>, |
| 183 | pub created_at: SystemTime, |
| 184 | pub closed_at: Option<SystemTime>, |
| 185 | pub merged_at: Option<SystemTime>, |
| 186 | |
| 187 | pub merge_commit: Option<ObjectId>, |
| 188 | pub source_branch: RefName, |
| 189 | pub target_branch: RefName, |
| 190 | |
| 191 | pub comments: Vec<CommentView>, |
| 192 | pub viewer_is_owner: bool, |
| 193 | pub merge: Mergeability, |
| 194 | |
| 195 | pub labels: Vec<LabelView>, |
| 196 | |
| 197 | |
| 198 | pub repo_labels: Vec<LabelView>, |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | pub source_is_default: bool, |
| 205 | } |
| 206 | |
| 207 | |
| 208 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 209 | pub struct Merged { |
| 210 | |
| 211 | pub commit: ObjectId, |
| 212 | |
| 213 | pub deleted_source: bool, |
| 214 | |
| 215 | |
| 216 | pub events: Vec<PushEvent>, |
| 217 | |
| 218 | |
| 219 | |
| 220 | pub closed: Vec<crate::domain::IssueNumber>, |
| 221 | } |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 229 | pub enum Numbered { |
| 230 | Issue, |
| 231 | PullRequest, |
| 232 | |
| 233 | |
| 234 | Neither, |
| 235 | } |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | #[allow(clippy::too_many_arguments)] |
| 250 | pub async fn list_pulls( |
| 251 | actor: &Actor, |
| 252 | handle: &OrgName, |
| 253 | name: &RepoName, |
| 254 | state: PullRequestState, |
| 255 | filter: Option<&str>, |
| 256 | page: usize, |
| 257 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 258 | pulls: &impl PullRequestRepository, |
| 259 | users: &impl UserRepository, |
| 260 | labels: &impl LabelRepository, |
| 261 | ) -> Result<Option<PullList>> { |
| 262 | let Some((repo, viewer_is_owner)) = readable_repo(actor, handle, name, stores).await? else { |
| 263 | return Ok(None); |
| 264 | }; |
| 265 | |
| 266 | |
| 267 | let on_pull = labels_by_pull(&repo, labels).await?; |
| 268 | |
| 269 | let filter = match filter { |
| 270 | Some(name) => Some(labels.find_by_name(&repo.id, name).await?), |
| 271 | None => None, |
| 272 | }; |
| 273 | |
| 274 | let mut counts: PullRequestCounts = pulls.counts(&repo.id).await?; |
| 275 | let mut page = page; |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | let mut listed = match filter.is_some() { |
| 281 | true => pulls.list_by_repo(&repo.id, state, 0, usize::MAX).await?, |
| 282 | false => { |
| 283 | let total = counts.of(state) as usize; |
| 284 | page = clamp(page, page_count(total, PULL_LIMIT)); |
| 285 | |
| 286 | pulls |
| 287 | .list_by_repo(&repo.id, state, offset(page, PULL_LIMIT), PULL_LIMIT) |
| 288 | .await? |
| 289 | } |
| 290 | }; |
| 291 | |
| 292 | if let Some(wanted) = &filter { |
| 293 | let carries = |pull: &PullRequest| { |
| 294 | wanted.as_ref().is_some_and(|wanted| { |
| 295 | on_pull |
| 296 | .get(&pull.id) |
| 297 | .is_some_and(|labels| labels.iter().any(|label| label.id == wanted.id)) |
| 298 | }) |
| 299 | }; |
| 300 | |
| 301 | let mut counted = PullRequestCounts::default(); |
| 302 | |
| 303 | for other in [ |
| 304 | PullRequestState::Open, |
| 305 | PullRequestState::Merged, |
| 306 | PullRequestState::Closed, |
| 307 | ] { |
| 308 | let total = match other == state { |
| 309 | true => { |
| 310 | listed.retain(&carries); |
| 311 | listed.len() as u64 |
| 312 | } |
| 313 | false => pulls |
| 314 | .list_by_repo(&repo.id, other, 0, usize::MAX) |
| 315 | .await? |
| 316 | .iter() |
| 317 | .filter(|pull| carries(pull)) |
| 318 | .count() as u64, |
| 319 | }; |
| 320 | |
| 321 | match other { |
| 322 | PullRequestState::Open => counted.open = total, |
| 323 | PullRequestState::Merged => counted.merged = total, |
| 324 | PullRequestState::Closed => counted.closed = total, |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | counts = counted; |
| 329 | } |
| 330 | |
| 331 | |
| 332 | |
| 333 | let total = match filter.is_some() { |
| 334 | true => listed.len(), |
| 335 | false => counts.of(state) as usize, |
| 336 | }; |
| 337 | let paged = match filter.is_some() { |
| 338 | true => Paged::slice(listed, page, PULL_LIMIT), |
| 339 | false => Paged::of(listed, total, page, PULL_LIMIT), |
| 340 | }; |
| 341 | |
| 342 | |
| 343 | let comments: HashMap<PullRequestId, u64> = |
| 344 | pulls.comment_counts(&repo.id).await?.into_iter().collect(); |
| 345 | |
| 346 | let mut handles = Handles::default(); |
| 347 | let mut summaries = Vec::with_capacity(paged.items.len()); |
| 348 | |
| 349 | for pull in paged.items { |
| 350 | summaries.push(PullSummary { |
| 351 | number: pull.number, |
| 352 | title: pull.title, |
| 353 | state: pull.state, |
| 354 | author: handles.of(&pull.author_id, stores.orgs, users).await?, |
| 355 | created_at: pull.created_at, |
| 356 | comments: comments.get(&pull.id).copied().unwrap_or(0), |
| 357 | source_branch: pull.source_branch, |
| 358 | target_branch: pull.target_branch, |
| 359 | labels: on_pull.get(&pull.id).cloned().unwrap_or_default(), |
| 360 | }); |
| 361 | } |
| 362 | |
| 363 | Ok(Some(PullList { |
| 364 | state, |
| 365 | open: counts.open, |
| 366 | merged: counts.merged, |
| 367 | closed: counts.closed, |
| 368 | pulls: Paged::of(summaries, paged.total, paged.page, PULL_LIMIT), |
| 369 | viewer_is_owner, |
| 370 | filter: filter.flatten().map(LabelView::from), |
| 371 | })) |
| 372 | } |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | #[allow(clippy::too_many_arguments)] |
| 386 | pub async fn view_pull( |
| 387 | actor: &Actor, |
| 388 | handle: &OrgName, |
| 389 | name: &RepoName, |
| 390 | number: crate::domain::IssueNumber, |
| 391 | merge_supported: bool, |
| 392 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 393 | pulls: &impl PullRequestRepository, |
| 394 | users: &impl UserRepository, |
| 395 | queries: &impl GitQuery, |
| 396 | labels: &impl LabelRepository, |
| 397 | ) -> Result<Option<PullDetail>> { |
| 398 | let Some((repo, viewer_is_owner)) = readable_repo(actor, handle, name, stores).await? else { |
| 399 | return Ok(None); |
| 400 | }; |
| 401 | |
| 402 | let Some(pull) = pulls.find_by_number(&repo.id, number).await? else { |
| 403 | return Ok(None); |
| 404 | }; |
| 405 | |
| 406 | let mut handles = Handles::default(); |
| 407 | let author = handles.of(&pull.author_id, stores.orgs, users).await?; |
| 408 | |
| 409 | let mut comments = Vec::new(); |
| 410 | for comment in pulls.list_comments(&pull.id).await? { |
| 411 | comments.push(CommentView { |
| 412 | author: handles.of(&comment.author_id, stores.orgs, users).await?, |
| 413 | body: comment.body, |
| 414 | created_at: comment.created_at, |
| 415 | }); |
| 416 | } |
| 417 | |
| 418 | let merge = mergeability(handle, name, &pull, merge_supported, queries).await?; |
| 419 | |
| 420 | |
| 421 | |
| 422 | let source_is_default = if merge.strategies().is_empty() { |
| 423 | false |
| 424 | } else { |
| 425 | queries |
| 426 | .default_branch(handle, name) |
| 427 | .await? |
| 428 | .is_some_and(|branch| branch == pull.source_branch) |
| 429 | }; |
| 430 | |
| 431 | Ok(Some(PullDetail { |
| 432 | number: pull.number, |
| 433 | title: pull.title, |
| 434 | body: pull.body, |
| 435 | state: pull.state, |
| 436 | author, |
| 437 | created_at: pull.created_at, |
| 438 | closed_at: pull.closed_at, |
| 439 | merged_at: pull.merged_at, |
| 440 | merge_commit: pull.merge_commit, |
| 441 | source_branch: pull.source_branch, |
| 442 | target_branch: pull.target_branch, |
| 443 | comments, |
| 444 | viewer_is_owner, |
| 445 | merge, |
| 446 | labels: labels |
| 447 | .labels_for_pull(&pull.id) |
| 448 | .await? |
| 449 | .into_iter() |
| 450 | .map(LabelView::from) |
| 451 | .collect(), |
| 452 | |
| 453 | |
| 454 | repo_labels: if viewer_is_owner { |
| 455 | labels |
| 456 | .list_by_repo(&repo.id) |
| 457 | .await? |
| 458 | .into_iter() |
| 459 | .map(LabelView::from) |
| 460 | .collect() |
| 461 | } else { |
| 462 | Vec::new() |
| 463 | }, |
| 464 | source_is_default, |
| 465 | })) |
| 466 | } |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | pub async fn suggested_title( |
| 482 | actor: &Actor, |
| 483 | handle: &OrgName, |
| 484 | name: &RepoName, |
| 485 | source: &RefName, |
| 486 | target: &RefName, |
| 487 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 488 | queries: &impl GitQuery, |
| 489 | ) -> Result<Option<String>> { |
| 490 | if readable_repo(actor, handle, name, stores).await?.is_none() { |
| 491 | return Ok(None); |
| 492 | } |
| 493 | |
| 494 | let (target_ref, source_ref) = (branch_ref(target), branch_ref(source)); |
| 495 | let (target_id, source_id) = tokio::try_join!( |
| 496 | queries.resolve(handle, name, &target_ref), |
| 497 | queries.resolve(handle, name, &source_ref), |
| 498 | )?; |
| 499 | |
| 500 | let (Some(target_id), Some(source_id)) = (target_id, source_id) else { |
| 501 | return Ok(None); |
| 502 | }; |
| 503 | |
| 504 | |
| 505 | let commits = queries |
| 506 | .log_between(handle, name, Some(&target_id), &source_id, 0, 2) |
| 507 | .await?; |
| 508 | |
| 509 | Ok(match commits.as_slice() { |
| 510 | [only] => Some(only.summary.clone()), |
| 511 | _ => None, |
| 512 | }) |
| 513 | } |
| 514 | |
| 515 | |
| 516 | |
| 517 | |
| 518 | |
| 519 | pub async fn numbered_thing( |
| 520 | actor: &Actor, |
| 521 | handle: &OrgName, |
| 522 | name: &RepoName, |
| 523 | number: crate::domain::IssueNumber, |
| 524 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 525 | issues: &impl IssueRepository, |
| 526 | pulls: &impl PullRequestRepository, |
| 527 | ) -> Result<Numbered> { |
| 528 | let Some((repo, _)) = readable_repo(actor, handle, name, stores).await? else { |
| 529 | return Ok(Numbered::Neither); |
| 530 | }; |
| 531 | |
| 532 | if issues.find_by_number(&repo.id, number).await?.is_some() { |
| 533 | return Ok(Numbered::Issue); |
| 534 | } |
| 535 | |
| 536 | if pulls.find_by_number(&repo.id, number).await?.is_some() { |
| 537 | return Ok(Numbered::PullRequest); |
| 538 | } |
| 539 | |
| 540 | Ok(Numbered::Neither) |
| 541 | } |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | #[allow(clippy::too_many_arguments)] |
| 558 | pub async fn create_pull( |
| 559 | actor: &Actor, |
| 560 | handle: &OrgName, |
| 561 | name: &RepoName, |
| 562 | spec: &NewPull, |
| 563 | now: SystemTime, |
| 564 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 565 | pulls: &impl PullRequestRepository, |
| 566 | queries: &impl GitQuery, |
| 567 | ) -> Result<PullRequest> { |
| 568 | let repo = writable_repo(actor, handle, name, stores).await?; |
| 569 | |
| 570 | |
| 571 | |
| 572 | let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone(); |
| 573 | |
| 574 | for (field, branch) in [ |
| 575 | ("source branch", &spec.source), |
| 576 | ("target branch", &spec.target), |
| 577 | ] { |
| 578 | if queries.resolve(handle, name, branch).await?.is_none() { |
| 579 | return Err(DomainError::validation( |
| 580 | field, |
| 581 | format!("there is no branch called {branch} in this repository"), |
| 582 | ) |
| 583 | .into()); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | let number = stores.repos.next_number(&repo.id).await?; |
| 588 | let pull = PullRequest::new( |
| 589 | PullRequestId::generate(), |
| 590 | repo.id.clone(), |
| 591 | number, |
| 592 | spec.title.clone(), |
| 593 | spec.body.clone(), |
| 594 | author_id, |
| 595 | spec.source.clone(), |
| 596 | spec.target.clone(), |
| 597 | now, |
| 598 | )?; |
| 599 | |
| 600 | pulls.save(&pull).await?; |
| 601 | |
| 602 | Ok(pull) |
| 603 | } |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | #[allow(clippy::too_many_arguments)] |
| 610 | pub async fn comment_on_pull( |
| 611 | actor: &Actor, |
| 612 | handle: &OrgName, |
| 613 | name: &RepoName, |
| 614 | number: crate::domain::IssueNumber, |
| 615 | body: &str, |
| 616 | now: SystemTime, |
| 617 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 618 | pulls: &impl PullRequestRepository, |
| 619 | ) -> Result<()> { |
| 620 | let repo = writable_repo(actor, handle, name, stores).await?; |
| 621 | let mut pull = existing_pull(&repo, number, pulls).await?; |
| 622 | let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone(); |
| 623 | |
| 624 | let comment = PullRequestComment::new( |
| 625 | PullRequestCommentId::generate(), |
| 626 | pull.id.clone(), |
| 627 | author_id, |
| 628 | body, |
| 629 | now, |
| 630 | )?; |
| 631 | |
| 632 | pulls.add_comment(&comment).await?; |
| 633 | |
| 634 | pull.touch(now); |
| 635 | pulls.save(&pull).await?; |
| 636 | |
| 637 | Ok(()) |
| 638 | } |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | #[allow(clippy::too_many_arguments)] |
| 646 | pub async fn set_pull_state( |
| 647 | actor: &Actor, |
| 648 | handle: &OrgName, |
| 649 | name: &RepoName, |
| 650 | number: crate::domain::IssueNumber, |
| 651 | state: PullRequestState, |
| 652 | now: SystemTime, |
| 653 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 654 | pulls: &impl PullRequestRepository, |
| 655 | ) -> Result<()> { |
| 656 | let repo = writable_repo(actor, handle, name, stores).await?; |
| 657 | let mut pull = existing_pull(&repo, number, pulls).await?; |
| 658 | |
| 659 | match state { |
| 660 | PullRequestState::Closed => pull.close(now), |
| 661 | PullRequestState::Open => pull.reopen(now), |
| 662 | PullRequestState::Merged => { |
| 663 | return Err(DomainError::validation( |
| 664 | "state", |
| 665 | "a pull request is merged by merging it, not by being marked merged", |
| 666 | ) |
| 667 | .into()); |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | pulls.save(&pull).await?; |
| 672 | |
| 673 | Ok(()) |
| 674 | } |
| 675 | |
| 676 | |
| 677 | #[allow(clippy::too_many_arguments)] |
| 678 | pub async fn edit_pull( |
| 679 | actor: &Actor, |
| 680 | handle: &OrgName, |
| 681 | name: &RepoName, |
| 682 | number: crate::domain::IssueNumber, |
| 683 | edit: &PullEdit, |
| 684 | now: SystemTime, |
| 685 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 686 | pulls: &impl PullRequestRepository, |
| 687 | ) -> Result<()> { |
| 688 | let repo = writable_repo(actor, handle, name, stores).await?; |
| 689 | let mut pull = existing_pull(&repo, number, pulls).await?; |
| 690 | |
| 691 | |
| 692 | |
| 693 | pull.edit(edit.title.clone(), edit.body.clone(), now)?; |
| 694 | pulls.save(&pull).await?; |
| 695 | |
| 696 | Ok(()) |
| 697 | } |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | #[allow(clippy::too_many_arguments)] |
| 723 | pub async fn merge_pull( |
| 724 | actor: &Actor, |
| 725 | handle: &OrgName, |
| 726 | name: &RepoName, |
| 727 | number: crate::domain::IssueNumber, |
| 728 | strategy: MergeStrategy, |
| 729 | delete_source: bool, |
| 730 | merge_supported: bool, |
| 731 | now: SystemTime, |
| 732 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 733 | pulls: &impl PullRequestRepository, |
| 734 | events: &impl PushEventRepository, |
| 735 | issues: &impl IssueRepository, |
| 736 | queries: &impl GitQuery, |
| 737 | merges: &impl GitMerge, |
| 738 | author: &MergeAuthor, |
| 739 | ) -> Result<Merged> { |
| 740 | let repo = writable_repo(actor, handle, name, stores).await?; |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | repo.refuse_writes(RepoWrite::Contents)?; |
| 746 | |
| 747 | let mut pull = existing_pull(&repo, number, pulls).await?; |
| 748 | |
| 749 | if !pull.state.is_open() { |
| 750 | return Err(DomainError::validation( |
| 751 | "state", |
| 752 | format!("this pull request is already {}", pull.state), |
| 753 | ) |
| 754 | .into()); |
| 755 | } |
| 756 | |
| 757 | let (target_id, source_id) = resolved_ends(handle, name, &pull, queries).await?; |
| 758 | let (target_id, source_id) = match (target_id, source_id) { |
| 759 | (Some(target), Some(source)) => (target, source), |
| 760 | _ => { |
| 761 | return Err(DomainError::validation( |
| 762 | "branch", |
| 763 | "one of the branches is no longer in this repository", |
| 764 | ) |
| 765 | .into()); |
| 766 | } |
| 767 | }; |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | let ready = mergeability(handle, name, &pull, merge_supported, queries).await?; |
| 773 | |
| 774 | if !ready.is_ready() { |
| 775 | return Err(DomainError::validation("merge", refusal(&ready)).into()); |
| 776 | } |
| 777 | |
| 778 | if !ready.strategies().contains(&strategy) { |
| 779 | return Err(DomainError::validation( |
| 780 | "strategy", |
| 781 | format!( |
| 782 | "{} is not available for this pull request", |
| 783 | strategy.label() |
| 784 | ), |
| 785 | ) |
| 786 | .into()); |
| 787 | } |
| 788 | |
| 789 | let landed = match strategy { |
| 790 | |
| 791 | |
| 792 | MergeStrategy::FastForward => source_id.clone(), |
| 793 | MergeStrategy::Merge | MergeStrategy::Squash => { |
| 794 | let MergePreview::Clean { tree } = queries |
| 795 | .merge_preview(handle, name, &target_id, &source_id) |
| 796 | .await? |
| 797 | else { |
| 798 | |
| 799 | |
| 800 | return Err(DomainError::validation("merge", refusal(&ready)).into()); |
| 801 | }; |
| 802 | |
| 803 | let (parents, message) = match strategy { |
| 804 | MergeStrategy::Squash => ( |
| 805 | vec![target_id.clone()], |
| 806 | squash_message(handle, name, &pull, &target_id, &source_id, queries).await?, |
| 807 | ), |
| 808 | _ => ( |
| 809 | vec![target_id.clone(), source_id.clone()], |
| 810 | merge_message(&pull), |
| 811 | ), |
| 812 | }; |
| 813 | |
| 814 | merges |
| 815 | .commit_tree( |
| 816 | handle, |
| 817 | name, |
| 818 | &CommitTreeRequest { |
| 819 | tree, |
| 820 | parents, |
| 821 | message, |
| 822 | author_name: author.name.clone(), |
| 823 | author_email: author.email.clone(), |
| 824 | now, |
| 825 | }, |
| 826 | ) |
| 827 | .await? |
| 828 | } |
| 829 | }; |
| 830 | |
| 831 | merges |
| 832 | .update_ref(handle, name, &pull.target_branch, &landed, &target_id) |
| 833 | .await?; |
| 834 | |
| 835 | |
| 836 | |
| 837 | let deleted_source = match delete_source { |
| 838 | true => { |
| 839 | merges |
| 840 | .delete_ref(handle, name, &pull.source_branch, &source_id) |
| 841 | .await?; |
| 842 | true |
| 843 | } |
| 844 | false => false, |
| 845 | }; |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | let mut before = vec![(branch_ref(&pull.target_branch), target_id.clone())]; |
| 853 | let mut after = vec![(branch_ref(&pull.target_branch), landed.clone())]; |
| 854 | |
| 855 | if deleted_source { |
| 856 | before.push((branch_ref(&pull.source_branch), source_id.clone())); |
| 857 | |
| 858 | } |
| 859 | |
| 860 | after.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); |
| 861 | before.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); |
| 862 | |
| 863 | let recorded = record_push(actor, handle, name, &before, &after, now, stores, events).await?; |
| 864 | |
| 865 | pull.merge(landed.clone(), now)?; |
| 866 | pulls.save(&pull).await?; |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | let closed = close_referenced(&repo, &pull, actor, now, issues).await?; |
| 873 | |
| 874 | Ok(Merged { |
| 875 | commit: landed, |
| 876 | deleted_source, |
| 877 | events: recorded, |
| 878 | closed, |
| 879 | }) |
| 880 | } |
| 881 | |
| 882 | |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | |
| 890 | |
| 891 | async fn close_referenced( |
| 892 | repo: &Repository, |
| 893 | pull: &PullRequest, |
| 894 | actor: &Actor, |
| 895 | now: SystemTime, |
| 896 | issues: &impl IssueRepository, |
| 897 | ) -> Result<Vec<crate::domain::IssueNumber>> { |
| 898 | |
| 899 | |
| 900 | let referenced = closes(&format!("{}\n{}", pull.title, pull.body)); |
| 901 | let mut closed = Vec::new(); |
| 902 | |
| 903 | |
| 904 | |
| 905 | let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone(); |
| 906 | |
| 907 | for number in referenced { |
| 908 | |
| 909 | if number == pull.number { |
| 910 | continue; |
| 911 | } |
| 912 | |
| 913 | let Some(mut issue) = issues.find_by_number(&repo.id, number).await? else { |
| 914 | continue; |
| 915 | }; |
| 916 | |
| 917 | if !issue.state.is_open() { |
| 918 | continue; |
| 919 | } |
| 920 | |
| 921 | issues |
| 922 | .add_comment(&IssueComment::new( |
| 923 | IssueCommentId::generate(), |
| 924 | issue.id.clone(), |
| 925 | author_id.clone(), |
| 926 | format!( |
| 927 | "Closed by pull request #{}, merged into `{}`.", |
| 928 | pull.number, pull.target_branch |
| 929 | ), |
| 930 | now, |
| 931 | )?) |
| 932 | .await?; |
| 933 | |
| 934 | issue.close(now); |
| 935 | issues.save(&issue).await?; |
| 936 | |
| 937 | closed.push(number); |
| 938 | } |
| 939 | |
| 940 | Ok(closed) |
| 941 | } |
| 942 | |
| 943 | |
| 944 | |
| 945 | |
| 946 | |
| 947 | |
| 948 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 949 | pub struct MergeAuthor { |
| 950 | pub name: String, |
| 951 | pub email: String, |
| 952 | } |
| 953 | |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | |
| 962 | |
| 963 | pub(super) fn branch_ref(branch: &RefName) -> RefName { |
| 964 | RefName::from_trusted(format!("refs/heads/{branch}")) |
| 965 | } |
| 966 | |
| 967 | |
| 968 | async fn resolved_ends( |
| 969 | handle: &OrgName, |
| 970 | name: &RepoName, |
| 971 | pull: &PullRequest, |
| 972 | queries: &impl GitQuery, |
| 973 | ) -> Result<(Option<ObjectId>, Option<ObjectId>)> { |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | let (target_ref, source_ref) = ( |
| 979 | branch_ref(&pull.target_branch), |
| 980 | branch_ref(&pull.source_branch), |
| 981 | ); |
| 982 | |
| 983 | let (target, source) = tokio::try_join!( |
| 984 | queries.resolve(handle, name, &target_ref), |
| 985 | queries.resolve(handle, name, &source_ref), |
| 986 | )?; |
| 987 | |
| 988 | Ok((target, source)) |
| 989 | } |
| 990 | |
| 991 | |
| 992 | |
| 993 | |
| 994 | |
| 995 | |
| 996 | |
| 997 | async fn mergeability( |
| 998 | handle: &OrgName, |
| 999 | name: &RepoName, |
| 1000 | pull: &PullRequest, |
| 1001 | merge_supported: bool, |
| 1002 | queries: &impl GitQuery, |
| 1003 | ) -> Result<Mergeability> { |
| 1004 | if !pull.state.is_open() { |
| 1005 | return Ok(Mergeability::NotOpen); |
| 1006 | } |
| 1007 | |
| 1008 | let (target_id, source_id) = resolved_ends(handle, name, pull, queries).await?; |
| 1009 | |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | let Some(target_id) = target_id else { |
| 1014 | return Ok(Mergeability::MissingBranch { |
| 1015 | branch: pull.target_branch.clone(), |
| 1016 | }); |
| 1017 | }; |
| 1018 | let Some(source_id) = source_id else { |
| 1019 | return Ok(Mergeability::MissingBranch { |
| 1020 | branch: pull.source_branch.clone(), |
| 1021 | }); |
| 1022 | }; |
| 1023 | |
| 1024 | let Some(base) = queries |
| 1025 | .merge_base(handle, name, &target_id, &source_id) |
| 1026 | .await? |
| 1027 | else { |
| 1028 | return Ok(Mergeability::Unrelated); |
| 1029 | }; |
| 1030 | |
| 1031 | if base == source_id { |
| 1032 | return Ok(Mergeability::NothingToMerge); |
| 1033 | } |
| 1034 | |
| 1035 | if base == target_id { |
| 1036 | return Ok(Mergeability::Ready { fast_forward: true }); |
| 1037 | } |
| 1038 | |
| 1039 | if !merge_supported { |
| 1040 | return Ok(Mergeability::Unsupported); |
| 1041 | } |
| 1042 | |
| 1043 | Ok( |
| 1044 | match queries |
| 1045 | .merge_preview(handle, name, &target_id, &source_id) |
| 1046 | .await? |
| 1047 | { |
| 1048 | MergePreview::Clean { .. } => Mergeability::Ready { |
| 1049 | fast_forward: false, |
| 1050 | }, |
| 1051 | MergePreview::Conflicted { paths } => Mergeability::Conflicted { paths }, |
| 1052 | }, |
| 1053 | ) |
| 1054 | } |
| 1055 | |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | fn refusal(ready: &Mergeability) -> String { |
| 1061 | match ready { |
| 1062 | Mergeability::NotOpen => "this pull request is not open".to_owned(), |
| 1063 | Mergeability::Unsupported => "merging needs git 2.38 or newer on the server".to_owned(), |
| 1064 | Mergeability::MissingBranch { branch } => { |
| 1065 | format!("there is no branch called {branch} in this repository any more") |
| 1066 | } |
| 1067 | Mergeability::NothingToMerge => { |
| 1068 | "there is nothing to merge — every commit is already on the target".to_owned() |
| 1069 | } |
| 1070 | Mergeability::Unrelated => { |
| 1071 | "the two branches share no history, so there is nothing to merge".to_owned() |
| 1072 | } |
| 1073 | Mergeability::Conflicted { paths } => match paths.len() { |
| 1074 | 1 => format!("there is a conflict in {}", paths[0]), |
| 1075 | other => format!("there are conflicts in {other} files"), |
| 1076 | }, |
| 1077 | Mergeability::Ready { .. } => "this pull request merges cleanly".to_owned(), |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | fn merge_message(pull: &PullRequest) -> String { |
| 1088 | let mut message = format!( |
| 1089 | "Merge pull request #{} from {}\n\n{}", |
| 1090 | pull.number, pull.source_branch, pull.title |
| 1091 | ); |
| 1092 | |
| 1093 | if !pull.body.is_empty() { |
| 1094 | message.push_str("\n\n"); |
| 1095 | message.push_str(&pull.body); |
| 1096 | } |
| 1097 | |
| 1098 | message |
| 1099 | } |
| 1100 | |
| 1101 | |
| 1102 | |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | async fn squash_message( |
| 1107 | handle: &OrgName, |
| 1108 | name: &RepoName, |
| 1109 | pull: &PullRequest, |
| 1110 | target_id: &ObjectId, |
| 1111 | source_id: &ObjectId, |
| 1112 | queries: &impl GitQuery, |
| 1113 | ) -> Result<String> { |
| 1114 | let mut message = format!("{} (#{})", pull.title, pull.number); |
| 1115 | |
| 1116 | if !pull.body.is_empty() { |
| 1117 | message.push_str("\n\n"); |
| 1118 | message.push_str(&pull.body); |
| 1119 | } |
| 1120 | |
| 1121 | |
| 1122 | |
| 1123 | let commits = queries |
| 1124 | .log_between( |
| 1125 | handle, |
| 1126 | name, |
| 1127 | Some(target_id), |
| 1128 | source_id, |
| 1129 | 0, |
| 1130 | MAX_SQUASHED_COMMITS + 1, |
| 1131 | ) |
| 1132 | .await?; |
| 1133 | |
| 1134 | if commits.is_empty() { |
| 1135 | return Ok(message); |
| 1136 | } |
| 1137 | |
| 1138 | message.push_str("\n\nSquashed commits:\n"); |
| 1139 | |
| 1140 | for commit in commits.iter().take(MAX_SQUASHED_COMMITS) { |
| 1141 | message.push_str(&format!("\n* {}", commit.summary)); |
| 1142 | } |
| 1143 | |
| 1144 | if commits.len() > MAX_SQUASHED_COMMITS { |
| 1145 | message.push_str("\n* …and more"); |
| 1146 | } |
| 1147 | |
| 1148 | Ok(message) |
| 1149 | } |
| 1150 | |
| 1151 | |
| 1152 | pub(super) async fn existing_pull( |
| 1153 | repo: &Repository, |
| 1154 | number: crate::domain::IssueNumber, |
| 1155 | pulls: &impl PullRequestRepository, |
| 1156 | ) -> Result<PullRequest> { |
| 1157 | pulls |
| 1158 | .find_by_number(&repo.id, number) |
| 1159 | .await? |
| 1160 | .ok_or(Error::Domain(DomainError::NotFound { |
| 1161 | entity: "pull request", |
| 1162 | })) |
| 1163 | } |
| 1164 | |
| 1165 | #[cfg(test)] |
| 1166 | #[path = "pull_request_tests.rs"] |
| 1167 | mod tests; |