//! A read-only subset of the Gitea REST API, so a Forgejo or Gitea server can migrate a repo out //! of forge ("New migration", then "Gitea", with this server's URL and a token). The routes and //! JSON shapes are the ones the Forgejo Gitea downloader (services/migrations/gitea_downloader.go) //! and the Gitea Go SDK read. See docs/api.md, "Moving to Forgejo or Gitea". //! //! Gitea ids are integers while forge ids are ULIDs. Ids shown here come from [`numeric_id`], a //! stable 48 bit digest, and routes that take such an id find the row by scanning the (already //! scoped) parent list. Comment ids encode the issue number and the position instead, so the //! comment reaction route, which has no issue in its path, can find its comment. //! //! Reads follow the token: a caller sees what its user may read, drafts only with write access. //! What forge does not have (topics, reactions beyond the first ten users of an emoji) comes back //! empty rather than as an error. use std::collections::HashMap; use forge_core::issues::{ Comment, IssueFilter, IssueListItem, IssueSort, IssueState, Label, Milestone, }; use forge_core::pulls::PullRequest; use forge_core::reactions::ReactionTarget; use forge_core::reviews::{Review, ReviewComment, ReviewState, Side}; use forge_core::token::hash_token; use forge_core::{Action, Repo as CoreRepo, User, Visibility}; use http::HeaderMap; use http::header::{AUTHORIZATION, HeaderName, HeaderValue}; use serde_json::{Value, json}; use topcoat::context::{Cx, app_context}; use topcoat::router::request::{headers, uri}; use topcoat::router::response::Response; use topcoat::router::{StatusCode, path_param, route}; use crate::api::{self, Refusal}; use crate::client_ip::client_ip; use crate::state::AppState; path_param!(owner); path_param!(repo); path_param!(index); path_param!(id); path_param!(review_id); /// The version reported by `GET /api/v1/version`. Forgejo's downloader gates reactions on 1.11, /// reviews and pagination on 1.12 and PR head shas on 1.14, so this unlocks all of them. pub const GITEA_VERSION: &str = "1.22.0"; /// Largest page a caller can ask for, announced by `GET /api/v1/settings/api`. pub const MAX_PAGE: usize = 50; /// Page size when the caller names none. const DEFAULT_PAGE: usize = 30; /// A stable positive integer for a forge id, below 2^48 so JSON numbers stay exact. pub fn numeric_id(id: &str) -> i64 { let digest = hash_token(id); i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1 } /// True when `raw` is a Gitea style integer id (as opposed to a ULID). pub fn is_numeric(raw: &str) -> bool { !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit()) } /// Comment id: the issue number in the high bits, the 1-based position in the low 20. fn comment_id(number: i64, position: usize) -> i64 { (number << 20) | (position as i64 + 1) } fn split_comment_id(id: i64) -> Option<(i64, usize)> { let position = (id & 0xF_FFFF) as usize; let number = id >> 20; (number > 0 && position > 0).then_some((number, position - 1)) } /// The user object. Only what the downloader and the SDK read; emails are never revealed. pub fn user_json(base: &str, id: &str, name: &str) -> Value { json!({ "id": numeric_id(id), "login": name, "username": name, "login_name": "", "full_name": "", "email": "", "avatar_url": "", "html_url": format!("{}/{}", base.trim_end_matches('/'), name), "is_admin": false, }) } /// One value of the query string. fn query_value(cx: &Cx, key: &str) -> Option { let query = uri(cx).query()?; form_urlencoded::parse(query.as_bytes()) .find(|(k, _)| k == key) .map(|(_, v)| v.into_owned()) } /// The headers with `?access_token=` or `?token=` folded into an `Authorization` header when the /// request carries none, so every Gitea auth style reaches the same code. fn effective_headers(cx: &Cx) -> HeaderMap { let mut map = headers(cx).clone(); if !map.contains_key(AUTHORIZATION) && let Some(token) = query_value(cx, "access_token").or_else(|| query_value(cx, "token")) && let Ok(value) = HeaderValue::from_str(&format!("token {token}")) { map.insert(AUTHORIZATION, value); } map } /// Who is asking, and the raw token they used (for the clone URL of a private repo). async fn caller(cx: &Cx) -> Result<(Option, Option), Refusal> { let state = app_context::(cx); let map = effective_headers(cx); let actor = api::authenticate(state, client_ip(cx), &map).await?; let token = api::presented_token(&map).flatten(); Ok((actor, token)) } struct Ctx { repo: CoreRepo, token: Option, base: String, } async fn read_ctx(cx: &Cx) -> Result { let state = app_context::(cx); let (actor, token) = caller(cx).await?; let repo = api::load_repo( state, actor.as_ref(), path_param::(cx), path_param::(cx), Action::Read, ) .await?; Ok(Ctx { repo, token: actor.and(token), base: state.config.base_url.trim_end_matches('/').to_owned(), }) } fn bad(message: &str) -> Refusal { Box::new(api::error(StatusCode::BAD_REQUEST, message)) } fn not_found(what: &str) -> Refusal { Box::new(api::error(StatusCode::NOT_FOUND, what)) } /// `page` and `limit` of the request. `default_limit` applies when `limit` is absent; an explicit /// one is capped at [`MAX_PAGE`]. pub struct Paging { pub page: usize, pub limit: usize, } pub fn paging(cx: &Cx, default_limit: usize) -> Paging { let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::().ok()); Paging { page: number("page").filter(|p| *p > 0).unwrap_or(1), limit: number("limit") .filter(|l| *l > 0) .map_or(default_limit, |l| l.min(MAX_PAGE)), } } /// The slice of `items` for this page, and the total. pub fn slice(items: Vec, pg: &Paging) -> (Vec, usize) { let total = items.len(); let start = pg.page.saturating_sub(1).saturating_mul(pg.limit); ( items.into_iter().skip(start).take(pg.limit).collect(), total, ) } /// A 200 JSON array with `X-Total-Count` and a `Link` header (next, prev, first, last). pub fn page_response(cx: &Cx, items: Vec, total: usize, pg: &Paging) -> Response { let mut res = api::json(StatusCode::OK, &Value::Array(items)); let last = total.div_ceil(pg.limit.max(1)).max(1); let state = app_context::(cx); let base = state.config.base_url.trim_end_matches('/'); let mut rest = String::new(); if let Some(query) = uri(cx).query() { for (k, v) in form_urlencoded::parse(query.as_bytes()) { if k != "page" && k != "limit" { rest.push_str(&format!( "{}={}&", form_urlencoded::byte_serialize(k.as_bytes()).collect::(), form_urlencoded::byte_serialize(v.as_bytes()).collect::() )); } } } let link = |page: usize, rel: &str| { format!( "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"", uri(cx).path(), pg.limit ) }; let mut links = Vec::new(); if pg.page < last { links.push(link(pg.page + 1, "next")); links.push(link(last, "last")); } if pg.page > 1 { links.push(link(pg.page - 1, "prev")); links.push(link(1, "first")); } let map = res.headers_mut(); map.insert( HeaderName::from_static("x-total-count"), HeaderValue::from(total), ); if !links.is_empty() && let Ok(value) = HeaderValue::from_str(&links.join(", ")) { map.insert(HeaderName::from_static("link"), value); } map.insert( HeaderName::from_static("access-control-expose-headers"), HeaderValue::from_static("Link, X-Total-Count"), ); res } fn internal(e: impl std::fmt::Display) -> Refusal { api::internal(e) } #[route(GET "/api/v1/version")] async fn version_route(_cx: &Cx) -> topcoat::Result { Ok(api::json( StatusCode::OK, &json!({ "version": GITEA_VERSION }), )) } #[route(GET "/api/v1/settings/api")] async fn settings_api(_cx: &Cx) -> topcoat::Result { Ok(api::json( StatusCode::OK, &json!({ "max_response_items": MAX_PAGE, "default_paging_num": DEFAULT_PAGE, "default_git_trees_per_page": 1000, "default_max_blob_size": 10_485_760, }), )) } /// The clone URL; a private repo read with a token carries the token as the password so the /// server doing the migration can clone with it (git here accepts `oauth2` as the user name). fn clone_url(base: &str, repo: &CoreRepo, token: Option<&str>) -> String { let plain = format!("{base}/{}/{}.git", repo.owner_name, repo.name); match (repo.visibility, token) { (Visibility::Private, Some(token)) => match plain.split_once("://") { Some((scheme, rest)) => format!("{scheme}://oauth2:{token}@{rest}"), None => plain, }, _ => plain, } } /// The Gitea repository object. `token` embeds credentials in `clone_url` for private repos. pub async fn repo_json( state: &AppState, base: &str, repo: &CoreRepo, token: Option<&str>, ) -> Result { let empty = repo.default_branch.is_empty(); let ssh_host = &state.config.ssh_public_host; Ok(json!({ "id": numeric_id(&repo.id), "owner": user_json(base, &repo.owner_id, &repo.owner_name), "name": repo.name, "full_name": format!("{}/{}", repo.owner_name, repo.name), "description": repo.description, "empty": empty, "private": repo.visibility == Visibility::Private, "fork": repo.fork_of.is_some(), "template": false, "mirror": false, "archived": repo.archived, "website": "", "html_url": format!("{base}/{}/{}", repo.owner_name, repo.name), "clone_url": clone_url(base, repo, token), "ssh_url": format!("git@{ssh_host}:{}/{}.git", repo.owner_name, repo.name), "original_url": "", "default_branch": repo.default_branch, "avatar_url": "", "has_issues": true, "has_pull_requests": true, "has_wiki": true, "has_releases": true, "created_at": repo.created_at, "updated_at": repo.created_at, })) } #[route(GET "/api/v1/repos/{owner}/{repo}")] async fn get_repo(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; match repo_json(state, &ctx.base, &ctx.repo, ctx.token.as_deref()).await { Ok(value) => Ok(api::json(StatusCode::OK, &value)), Err(res) => Ok(*res), } } /// Forge repos have no topics yet; the list is empty. #[route(GET "/api/v1/repos/{owner}/{repo}/topics")] async fn topics_route(cx: &Cx) -> topcoat::Result { match read_ctx(cx).await { Ok(_) => Ok(api::json(StatusCode::OK, &json!({ "topics": [] }))), Err(res) => Ok(*res), } } fn label_json(base: &str, repo: &CoreRepo, label: &Label) -> Value { json!({ "id": numeric_id(&label.id), "name": label.name, "exclusive": false, "is_archived": false, "color": label.color.trim_start_matches('#'), "description": label.description, "url": format!("{base}/api/v1/repos/{}/{}/labels/{}", repo.owner_name, repo.name, numeric_id(&label.id)), }) } #[route(GET "/api/v1/repos/{owner}/{repo}/labels")] async fn list_labels_route(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let all = match state.store.list_labels(&ctx.repo.id).await { Ok(all) => all, Err(e) => return Ok(*internal(e)), }; let pg = paging(cx, DEFAULT_PAGE); let (page, total) = slice(all, &pg); let items = page .iter() .map(|l| label_json(&ctx.base, &ctx.repo, l)) .collect(); Ok(page_response(cx, items, total, &pg)) } fn date_time(date: &str) -> String { if date.len() == 10 { format!("{date}T00:00:00Z") } else { date.to_owned() } } fn milestone_json(m: &Milestone) -> Value { json!({ "id": numeric_id(&m.id), "title": m.title, "description": m.description, "state": m.state.as_str(), "open_issues": m.open_issues, "closed_issues": m.closed_issues, "created_at": m.created_at, "updated_at": m.closed_at.clone().unwrap_or_else(|| m.created_at.clone()), "closed_at": m.closed_at, "due_on": m.due_on.as_deref().map(date_time), }) } /// `state` of a Gitea list: `open` (the default), `closed` or `all`. fn state_filter(cx: &Cx) -> Result, Refusal> { match query_value(cx, "state").as_deref() { None | Some("") | Some("open") => Ok(Some(IssueState::Open)), Some("closed") => Ok(Some(IssueState::Closed)), Some("all") => Ok(None), Some(other) => Err(bad(&format!("unknown state {other:?}"))), } } #[route(GET "/api/v1/repos/{owner}/{repo}/milestones")] async fn list_milestones_route(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let wanted = match state_filter(cx) { Ok(wanted) => wanted, Err(res) => return Ok(*res), }; let all = match state.store.list_milestones(&ctx.repo.id, wanted).await { Ok(all) => all, Err(e) => return Ok(*internal(e)), }; let pg = paging(cx, DEFAULT_PAGE); let (page, total) = slice(all, &pg); let items = page.iter().map(milestone_json).collect(); Ok(page_response(cx, items, total, &pg)) } /// Usernames by user id, with `ghost` for an id that no longer resolves. async fn names(state: &AppState, ids: Vec) -> Result, Refusal> { let found = state.store.usernames_by_ids(&ids).await.map_err(internal)?; Ok(found .into_iter() .map(|(id, (name, _))| (id, name)) .collect()) } fn user_of(base: &str, names: &HashMap, id: &str) -> Value { let name = names.get(id).map_or("ghost", String::as_str); user_json(base, id, name) } /// Shared by issues and pull requests: the fields both lists carry. async fn issue_core( state: &AppState, ctx: &Ctx, item: &IssueListItem, milestones: &HashMap, pull: bool, ) -> Result { let issue = &item.issue; let assignees = state .store .issue_assignees(&issue.id) .await .map_err(internal)?; let assignees: Vec = assignees .iter() .map(|(id, name)| user_json(&ctx.base, id, name)) .collect(); let url = format!( "{}/{}/{}/{}/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, if pull { "pulls" } else { "issues" }, issue.number ); Ok(json!({ "id": numeric_id(&issue.id), "number": issue.number, "user": user_json(&ctx.base, &issue.author_id, &item.author), "title": issue.title, "body": issue.body, "labels": item.labels.iter().map(|l| label_json(&ctx.base, &ctx.repo, l)).collect::>(), "milestone": issue.milestone_id.as_ref().and_then(|m| milestones.get(m)).map(milestone_json), "assignee": assignees.first(), "assignees": assignees, "state": issue.state.as_str(), "is_locked": issue.locked, "comments": issue.comment_count, "created_at": issue.created_at, "updated_at": issue.updated_at, "closed_at": issue.closed_at, "due_date": null, "html_url": url, "url": format!("{}/api/v1/repos/{}/{}/issues/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, issue.number), "pull_request": if pull { json!({"merged": false, "merged_at": null, "html_url": url}) } else { Value::Null }, })) } async fn milestone_map( state: &AppState, repo: &CoreRepo, ) -> Result, Refusal> { let all = state .store .list_milestones(&repo.id, None) .await .map_err(internal)?; Ok(all.into_iter().map(|m| (m.id.clone(), m)).collect()) } fn filter_of(cx: &Cx, pg: &Paging) -> Result { Ok(IssueFilter { state: state_filter(cx)?, sort: IssueSort::Oldest, page: pg.page as u32, per_page: pg.limit as u32, ..IssueFilter::default() }) } #[route(GET "/api/v1/repos/{owner}/{repo}/issues")] async fn list_issues_route(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; match issues_inner(cx, state, &ctx).await { Ok(res) => Ok(res), Err(res) => Ok(*res), } } async fn issues_inner(cx: &Cx, state: &AppState, ctx: &Ctx) -> Result { let pg = paging(cx, DEFAULT_PAGE); let filter = filter_of(cx, &pg)?; let pulls = query_value(cx, "type").as_deref() == Some("pulls"); let (rows, total) = if pulls { state.store.list_pulls(&ctx.repo.id, &filter).await } else { state.store.list_issues(&ctx.repo.id, &filter).await } .map_err(internal)?; let milestones = milestone_map(state, &ctx.repo).await?; let mut out = Vec::with_capacity(rows.len()); for item in &rows { out.push(issue_core(state, ctx, item, &milestones, pulls).await?); } Ok(page_response(cx, out, total as usize, &pg)) } /// The issue row with this number. A pull request is an issue row too, so its comments and /// reactions are found through here as well. async fn issue_row( state: &AppState, repo: &CoreRepo, raw: &str, ) -> Result { let number: i64 = raw.parse().map_err(|_| bad("invalid issue index"))?; match state.store.issue_by_number(&repo.id, number).await { Ok(Some(issue)) => return Ok(issue), Ok(None) => {} Err(e) => return Err(internal(e)), } match state.store.pull_by_number(&repo.id, number).await { Ok(Some(pull)) => Ok(pull.issue), Ok(None) => Err(not_found("issue not found")), Err(e) => Err(internal(e)), } } fn comment_json( ctx: &Ctx, issue_number: i64, position: usize, comment: &Comment, names: &HashMap, ) -> Value { let id = comment_id(issue_number, position); let issue_url = format!( "{}/{}/{}/issues/{issue_number}", ctx.base, ctx.repo.owner_name, ctx.repo.name ); json!({ "id": id, "html_url": format!("{issue_url}#comment-{id}"), "issue_url": issue_url, "pull_request_url": "", "user": user_of(&ctx.base, names, &comment.author_id), "original_author": "", "original_author_id": 0, "body": comment.body, "created_at": comment.created_at, "updated_at": comment.updated_at, }) } #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")] async fn issue_comments(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let issue = issue_row(state, &ctx.repo, path_param::(cx)).await?; let all = state .store .list_comments(&issue.id) .await .map_err(internal)?; let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect(); let pg = paging(cx, DEFAULT_PAGE); let (page, total) = slice(numbered, &pg); let authors = names( state, page.iter().map(|(_, c)| c.author_id.clone()).collect(), ) .await?; let items = page .iter() .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors)) .collect(); Ok(page_response(cx, items, total, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) } /// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji. async fn reactions_json( state: &AppState, ctx: &Ctx, kind: ReactionTarget, target_id: &str, created_at: &str, ) -> Result, Refusal> { let map = state .store .reactions_for(kind, &[target_id.to_owned()], None) .await .map_err(internal)?; let mut out = Vec::new(); for summary in map.get(target_id).into_iter().flatten() { for username in &summary.users { let id = match state.store.user_by_username(username).await { Ok(Some(user)) => user.id, _ => continue, }; out.push(json!({ "user": user_json(&ctx.base, &id, username), "reaction": summary.reaction.name(), "created_at": created_at, })); } } Ok(out) } #[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")] async fn issue_reactions(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let issue = issue_row(state, &ctx.repo, path_param::(cx)).await?; let all = reactions_json( state, &ctx, ReactionTarget::Issue, &issue.id, &issue.created_at, ) .await?; let pg = paging(cx, 1000); let (page, total) = slice(all, &pg); Ok(page_response(cx, page, total, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) } #[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")] async fn comment_reactions(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let id: i64 = path_param::(cx) .parse() .map_err(|_| bad("invalid comment id"))?; let (number, position) = split_comment_id(id).ok_or_else(|| not_found("comment not found"))?; let issue = issue_row(state, &ctx.repo, &number.to_string()).await?; let all = state .store .list_comments(&issue.id) .await .map_err(internal)?; let comment = all .get(position) .ok_or_else(|| not_found("comment not found"))?; let items = reactions_json( state, &ctx, ReactionTarget::Comment, &comment.id, &comment.created_at, ) .await?; let pg = paging(cx, 1000); let (page, total) = slice(items, &pg); Ok(page_response(cx, page, total, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) } fn pr_branch( ctx: &Ctx, label_owner: &str, repo: Option<&CoreRepo>, branch: &str, sha: &str, ) -> Value { json!({ "label": format!("{label_owner}:{branch}"), "ref": branch, "sha": sha, "repo_id": repo.map(|r| numeric_id(&r.id)), "repo": repo.map(|r| json!({ "id": numeric_id(&r.id), "owner": user_json(&ctx.base, &r.owner_id, &r.owner_name), "name": r.name, "full_name": format!("{}/{}", r.owner_name, r.name), "private": r.visibility == Visibility::Private, "html_url": format!("{}/{}/{}", ctx.base, r.owner_name, r.name), "clone_url": format!("{}/{}/{}.git", ctx.base, r.owner_name, r.name), "default_branch": r.default_branch, })), }) } async fn pull_json( state: &AppState, ctx: &Ctx, item: &IssueListItem, pull: &PullRequest, milestones: &HashMap, ) -> Result { let mut value = issue_core(state, ctx, item, milestones, true).await?; let head_repo = match &pull.head_repo_id { Some(id) if *id == ctx.repo.id => Some(ctx.repo.clone()), Some(id) => state.store.repo_by_id(id).await.map_err(internal)?, None => None, }; // A head repo the caller cannot read is shown without its repo object. let head_repo = match head_repo { Some(r) if r.id == ctx.repo.id || r.visibility == Visibility::Public => Some(r), _ => None, }; let head_owner = head_repo .as_ref() .map_or(ctx.repo.owner_name.as_str(), |r| r.owner_name.as_str()); let merged_by = match &pull.merged_by { Some(id) => state .store .usernames_by_ids(std::slice::from_ref(id)) .await .map_err(internal)? .get(id) .map(|(name, _)| user_json(&ctx.base, id, name)), None => None, }; let html = format!( "{}/{}/{}/pulls/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, pull.issue.number ); let obj = value.as_object_mut().expect("object"); obj.insert("merged".into(), json!(pull.merged_at.is_some())); obj.insert("merged_at".into(), json!(pull.merged_at)); obj.insert("merged_by".into(), json!(merged_by)); obj.insert("merge_commit_sha".into(), json!(pull.merge_commit)); obj.insert("merged_commit_id".into(), json!(pull.merge_commit)); obj.insert("merge_base".into(), json!(pull.merge_base)); obj.insert( "mergeable".into(), json!(matches!( pull.mergeable, forge_core::pulls::Mergeable::Clean )), ); obj.insert("draft".into(), json!(pull.draft)); obj.insert("allow_maintainer_edit".into(), json!(false)); obj.insert("diff_url".into(), json!(format!("{html}.diff"))); obj.insert("patch_url".into(), json!(format!("{html}.patch"))); obj.insert("flow".into(), json!(0)); obj.insert( "base".into(), pr_branch( ctx, &ctx.repo.owner_name, Some(&ctx.repo), &pull.base_branch, &pull.base_oid, ), ); obj.insert( "head".into(), pr_branch( ctx, head_owner, head_repo.as_ref(), &pull.head_branch, &pull.head_oid, ), ); obj.insert( "pull_request".into(), json!({"merged": pull.merged_at.is_some(), "merged_at": pull.merged_at, "html_url": html}), ); Ok(value) } #[route(GET "/api/v1/repos/{owner}/{repo}/pulls")] async fn list_pulls_route(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let pg = paging(cx, DEFAULT_PAGE); let filter = filter_of(cx, &pg)?; let (rows, total) = state .store .list_pulls(&ctx.repo.id, &filter) .await .map_err(internal)?; let milestones = milestone_map(state, &ctx.repo).await?; let mut out = Vec::with_capacity(rows.len()); for item in &rows { let Some(pull) = state .store .pull_by_number(&ctx.repo.id, item.issue.number) .await .map_err(internal)? else { continue; }; out.push(pull_json(state, &ctx, item, &pull, &milestones).await?); } Ok(page_response(cx, out, total as usize, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) } /// The review state as Forgejo's uploader reads it (`CHANGES_REQUESTED`, `COMMENTED`). The Go SDK /// names are `REQUEST_CHANGES` and `COMMENT`, which the uploader maps to a pending review, found /// by migrating for real. fn review_state(review: &Review) -> &'static str { let effective = if review.state == ReviewState::Dismissed { review.dismissed_from.unwrap_or(ReviewState::Commented) } else { review.state }; match effective { ReviewState::Approved => "APPROVED", ReviewState::ChangesRequested => "CHANGES_REQUESTED", ReviewState::Pending => "PENDING", ReviewState::Commented | ReviewState::Dismissed => "COMMENTED", } } fn review_json(ctx: &Ctx, number: i64, review: &Review, comment_count: usize) -> Value { let html = format!( "{}/{}/{}/pulls/{number}", ctx.base, ctx.repo.owner_name, ctx.repo.name ); json!({ "id": numeric_id(&review.id), "user": user_json(&ctx.base, &review.author_id, &review.author_name), "team": null, "state": review_state(review), "body": review.body, "commit_id": review.commit_oid, "stale": false, "official": matches!(review_state(review), "APPROVED" | "CHANGES_REQUESTED"), "dismissed": review.state == ReviewState::Dismissed, "comments_count": comment_count, "submitted_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), "updated_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), "html_url": format!("{html}#{}", numeric_id(&review.id)), "pull_request_url": html, }) } /// Every non-pending review comment of the pull request, roots and replies, oldest first. async fn review_comments(state: &AppState, issue_id: &str) -> Result, Refusal> { let threads = state .store .review_threads(issue_id, None) .await .map_err(internal)?; let mut all: Vec = threads .into_iter() .flat_map(|t| std::iter::once(t.root).chain(t.replies)) .filter(|c| !c.pending) .collect(); all.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id))); Ok(all) } #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")] async fn pull_reviews(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let issue = pull_issue(state, &ctx.repo, path_param::(cx)).await?; let reviews = state .store .list_reviews(&issue.id) .await .map_err(internal)?; let comments = review_comments(state, &issue.id).await?; let pg = paging(cx, DEFAULT_PAGE); let (page, total) = slice(reviews, &pg); let items = page .iter() .map(|r| { let count = comments.iter().filter(|c| c.review_id == r.id).count(); review_json(&ctx, issue.number, r, count) }) .collect(); Ok(page_response(cx, items, total, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) } /// The issue row of a number that must be a pull request. async fn pull_issue( state: &AppState, repo: &CoreRepo, raw: &str, ) -> Result { let number: i64 = raw.parse().map_err(|_| bad("invalid pull request index"))?; match state.store.pull_by_number(&repo.id, number).await { Ok(Some(pull)) => Ok(pull.issue), Ok(None) => Err(not_found("pull request not found")), Err(e) => Err(internal(e)), } } fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value { let html = format!( "{}/{}/{}/pulls/{number}", ctx.base, ctx.repo.owner_name, ctx.repo.name ); let (line, old_line) = match c.side { Side::New => (c.line, 0), Side::Old => (0, c.line), }; json!({ "id": numeric_id(&c.id), "body": c.body, "user": user_json(&ctx.base, &c.author_id, &c.author_name), "resolver": null, "pull_request_review_id": numeric_id(&c.review_id), "created_at": c.created_at, "updated_at": c.updated_at, "path": c.path, "commit_id": c.commit_oid, "original_commit_id": c.commit_oid, "diff_hunk": c.diff_hunk, "position": line, "original_position": line, "line_num": line, "old_line_num": old_line, "html_url": format!("{html}#{}", numeric_id(&c.id)), "pull_request_url": html, }) } #[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")] async fn pull_review_comments(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let ctx = match read_ctx(cx).await { Ok(ctx) => ctx, Err(res) => return Ok(*res), }; let result: Result = async { let issue = pull_issue(state, &ctx.repo, path_param::(cx)).await?; let raw = path_param::(cx); let reviews = state .store .list_reviews(&issue.id) .await .map_err(internal)?; let review = reviews .iter() .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id)))) .ok_or_else(|| not_found("review not found"))?; let own: Vec = review_comments(state, &issue.id) .await? .into_iter() .filter(|c| c.review_id == review.id) .collect(); let items = own .iter() .map(|c| review_comment_json(&ctx, issue.number, c)) .collect::>(); let total = items.len(); // Review comments are not paged by the downloader; return them whole. let pg = Paging { page: 1, limit: total.max(1), }; Ok(page_response(cx, items, total, &pg)) } .await; Ok(result.unwrap_or_else(|res| *res)) }