|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use anyhow::Context as _; |
| 4 | +use axum::{ |
| 5 | + extract::{Path, State}, |
| 6 | + response::{IntoResponse, Redirect, Response}, |
| 7 | +}; |
| 8 | +use hyper::StatusCode; |
| 9 | + |
| 10 | +use crate::{ |
| 11 | + github, |
| 12 | + handlers::Context, |
| 13 | + utils::{AppError, is_repo_autorized}, |
| 14 | +}; |
| 15 | + |
| 16 | +/// Redirects to either `/gh-range-diff` (when the base changed) or to GitHub's compare |
| 17 | +/// page (when the base is the same). |
| 18 | +/// |
| 19 | +/// Takes an PR number and an `oldbase..oldhead` representing the range we are starting from. |
| 20 | +pub async fn gh_changes_since( |
| 21 | + Path((owner, repo, pr_num, oldbasehead)): Path<(String, String, u64, String)>, |
| 22 | + State(ctx): State<Arc<Context>>, |
| 23 | +) -> axum::response::Result<Response, AppError> { |
| 24 | + let Some((oldbase, oldhead)) = oldbasehead.split_once("..") else { |
| 25 | + return Ok(( |
| 26 | + StatusCode::BAD_REQUEST, |
| 27 | + format!("`{oldbasehead}` is not in the form `base..head`"), |
| 28 | + ) |
| 29 | + .into_response()); |
| 30 | + }; |
| 31 | + |
| 32 | + if !is_repo_autorized(&ctx, &owner, &repo).await? { |
| 33 | + return Ok(( |
| 34 | + StatusCode::UNAUTHORIZED, |
| 35 | + format!("repository `{owner}/{repo}` is not part of the Rust Project team repos"), |
| 36 | + ) |
| 37 | + .into_response()); |
| 38 | + } |
| 39 | + |
| 40 | + let issue_repo = github::IssueRepository { |
| 41 | + organization: owner.to_string(), |
| 42 | + repository: repo.to_string(), |
| 43 | + }; |
| 44 | + |
| 45 | + let pr = ctx.github.pull_request(&issue_repo, pr_num).await?; |
| 46 | + |
| 47 | + let newbase = &pr.base.as_ref().context("no base")?.sha; |
| 48 | + let newhead = &pr.head.as_ref().context("no head")?.sha; |
| 49 | + |
| 50 | + // Has the base changed? |
| 51 | + if oldbase == newbase { |
| 52 | + // No, redirect to GitHub native compare page |
| 53 | + return Ok(Redirect::to(&format!( |
| 54 | + "https://github.com/{owner}/{repo}/compare/{oldhead}..{newhead}" |
| 55 | + )) |
| 56 | + .into_response()); |
| 57 | + } |
| 58 | + |
| 59 | + // Yes, use our Github range-diff instead |
| 60 | + Ok(Redirect::to(&format!( |
| 61 | + "/gh-range-diff/{owner}/{repo}/{oldbase}..{oldhead}/{newbase}..{newhead}" |
| 62 | + )) |
| 63 | + .into_response()) |
| 64 | +} |
0 commit comments