forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBbcaef90Tahinli1 month ago164 commits

gitea.rs1006 lines, 34.0 KiBHistoryRawDownload
1//! A read-only subset of the Gitea REST API, so a Forgejo or Gitea server can migrate a repo out
2//! of forge ("New migration", then "Gitea", with this server's URL and a token). The routes and
3//! JSON shapes are the ones the Forgejo Gitea downloader (services/migrations/gitea_downloader.go)
4//! and the Gitea Go SDK read. See docs/api.md, "Moving to Forgejo or Gitea".
5//!
6//! Gitea ids are integers while forge ids are ULIDs. Ids shown here come from [`numeric_id`], a
7//! stable 48 bit digest, and routes that take such an id find the row by scanning the (already
8//! scoped) parent list. Comment ids encode the issue number and the position instead, so the
9//! comment reaction route, which has no issue in its path, can find its comment.
10//!
11//! Reads follow the token: a caller sees what its user may read, drafts only with write access.
12//! What forge does not have (topics, reactions beyond the first ten users of an emoji) comes back
13//! empty rather than as an error.
14
15use std::collections::HashMap;
16
17use forge_core::issues::{
18 Comment, IssueFilter, IssueListItem, IssueSort, IssueState, Label, Milestone,
19};
20use forge_core::pulls::PullRequest;
21use forge_core::reactions::ReactionTarget;
22use forge_core::reviews::{Review, ReviewComment, ReviewState, Side};
23use forge_core::token::hash_token;
24use forge_core::{Action, Repo as CoreRepo, User, Visibility};
25use http::HeaderMap;
26use http::header::{AUTHORIZATION, HeaderName, HeaderValue};
27use serde_json::{Value, json};
28use topcoat::context::{Cx, app_context};
29use topcoat::router::request::{headers, uri};
30use topcoat::router::response::Response;
31use topcoat::router::{StatusCode, path_param, route};
32
33use crate::api::{self, Refusal};
34use crate::client_ip::client_ip;
35use crate::state::AppState;
36
37path_param!(owner);
38path_param!(repo);
39path_param!(index);
40path_param!(id);
41path_param!(review_id);
42
43/// The version reported by `GET /api/v1/version`. Forgejo's downloader gates reactions on 1.11,
44/// reviews and pagination on 1.12 and PR head shas on 1.14, so this unlocks all of them.
45pub const GITEA_VERSION: &str = "1.22.0";
46/// Largest page a caller can ask for, announced by `GET /api/v1/settings/api`.
47pub const MAX_PAGE: usize = 50;
48/// Page size when the caller names none.
49const DEFAULT_PAGE: usize = 30;
50
51/// A stable positive integer for a forge id, below 2^48 so JSON numbers stay exact.
52pub fn numeric_id(id: &str) -> i64 {
53 let digest = hash_token(id);
54 i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1
55}
56
57/// True when `raw` is a Gitea style integer id (as opposed to a ULID).
58pub fn is_numeric(raw: &str) -> bool {
59 !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit())
60}
61
62/// Comment id: the issue number in the high bits, the 1-based position in the low 20.
63fn comment_id(number: i64, position: usize) -> i64 {
64 (number << 20) | (position as i64 + 1)
65}
66
67fn split_comment_id(id: i64) -> Option<(i64, usize)> {
68 let position = (id & 0xF_FFFF) as usize;
69 let number = id >> 20;
70 (number > 0 && position > 0).then_some((number, position - 1))
71}
72
73/// The user object. Only what the downloader and the SDK read; emails are never revealed.
74pub fn user_json(base: &str, id: &str, name: &str) -> Value {
75 json!({
76 "id": numeric_id(id),
77 "login": name,
78 "username": name,
79 "login_name": "",
80 "full_name": "",
81 "email": "",
82 "avatar_url": "",
83 "html_url": format!("{}/{}", base.trim_end_matches('/'), name),
84 "is_admin": false,
85 })
86}
87
88/// One value of the query string.
89fn query_value(cx: &Cx, key: &str) -> Option<String> {
90 let query = uri(cx).query()?;
91 form_urlencoded::parse(query.as_bytes())
92 .find(|(k, _)| k == key)
93 .map(|(_, v)| v.into_owned())
94}
95
96/// The headers with `?access_token=` or `?token=` folded into an `Authorization` header when the
97/// request carries none, so every Gitea auth style reaches the same code.
98fn effective_headers(cx: &Cx) -> HeaderMap {
99 let mut map = headers(cx).clone();
100 if !map.contains_key(AUTHORIZATION)
101 && let Some(token) = query_value(cx, "access_token").or_else(|| query_value(cx, "token"))
102 && let Ok(value) = HeaderValue::from_str(&format!("token {token}"))
103 {
104 map.insert(AUTHORIZATION, value);
105 }
106 map
107}
108
109/// Who is asking, and the raw token they used (for the clone URL of a private repo).
110async fn caller(cx: &Cx) -> Result<(Option<User>, Option<String>), Refusal> {
111 let state = app_context::<AppState>(cx);
112 let map = effective_headers(cx);
113 let actor = api::authenticate(state, client_ip(cx), &map).await?;
114 let token = api::presented_token(&map).flatten();
115 Ok((actor, token))
116}
117
118struct Ctx {
119 repo: CoreRepo,
120 token: Option<String>,
121 base: String,
122}
123
124async fn read_ctx(cx: &Cx) -> Result<Ctx, Refusal> {
125 let state = app_context::<AppState>(cx);
126 let (actor, token) = caller(cx).await?;
127 let repo = api::load_repo(
128 state,
129 actor.as_ref(),
130 path_param::<Owner>(cx),
131 path_param::<Repo>(cx),
132 Action::Read,
133 )
134 .await?;
135 Ok(Ctx {
136 repo,
137 token: actor.and(token),
138 base: state.config.base_url.trim_end_matches('/').to_owned(),
139 })
140}
141
142fn bad(message: &str) -> Refusal {
143 Box::new(api::error(StatusCode::BAD_REQUEST, message))
144}
145
146fn not_found(what: &str) -> Refusal {
147 Box::new(api::error(StatusCode::NOT_FOUND, what))
148}
149
150/// `page` and `limit` of the request. `default_limit` applies when `limit` is absent; an explicit
151/// one is capped at [`MAX_PAGE`].
152pub struct Paging {
153 pub page: usize,
154 pub limit: usize,
155}
156
157pub fn paging(cx: &Cx, default_limit: usize) -> Paging {
158 let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::<usize>().ok());
159 Paging {
160 page: number("page").filter(|p| *p > 0).unwrap_or(1),
161 limit: number("limit")
162 .filter(|l| *l > 0)
163 .map_or(default_limit, |l| l.min(MAX_PAGE)),
164 }
165}
166
167/// The slice of `items` for this page, and the total.
168pub fn slice<T>(items: Vec<T>, pg: &Paging) -> (Vec<T>, usize) {
169 let total = items.len();
170 let start = pg.page.saturating_sub(1).saturating_mul(pg.limit);
171 (
172 items.into_iter().skip(start).take(pg.limit).collect(),
173 total,
174 )
175}
176
177/// A 200 JSON array with `X-Total-Count` and a `Link` header (next, prev, first, last).
178pub fn page_response(cx: &Cx, items: Vec<Value>, total: usize, pg: &Paging) -> Response {
179 let mut res = api::json(StatusCode::OK, &Value::Array(items));
180 let last = total.div_ceil(pg.limit.max(1)).max(1);
181 let state = app_context::<AppState>(cx);
182 let base = state.config.base_url.trim_end_matches('/');
183 let mut rest = String::new();
184 if let Some(query) = uri(cx).query() {
185 for (k, v) in form_urlencoded::parse(query.as_bytes()) {
186 if k != "page" && k != "limit" {
187 rest.push_str(&format!(
188 "{}={}&",
189 form_urlencoded::byte_serialize(k.as_bytes()).collect::<String>(),
190 form_urlencoded::byte_serialize(v.as_bytes()).collect::<String>()
191 ));
192 }
193 }
194 }
195 let link = |page: usize, rel: &str| {
196 format!(
197 "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"",
198 uri(cx).path(),
199 pg.limit
200 )
201 };
202 let mut links = Vec::new();
203 if pg.page < last {
204 links.push(link(pg.page + 1, "next"));
205 links.push(link(last, "last"));
206 }
207 if pg.page > 1 {
208 links.push(link(pg.page - 1, "prev"));
209 links.push(link(1, "first"));
210 }
211 let map = res.headers_mut();
212 map.insert(
213 HeaderName::from_static("x-total-count"),
214 HeaderValue::from(total),
215 );
216 if !links.is_empty()
217 && let Ok(value) = HeaderValue::from_str(&links.join(", "))
218 {
219 map.insert(HeaderName::from_static("link"), value);
220 }
221 map.insert(
222 HeaderName::from_static("access-control-expose-headers"),
223 HeaderValue::from_static("Link, X-Total-Count"),
224 );
225 res
226}
227
228fn internal(e: impl std::fmt::Display) -> Refusal {
229 api::internal(e)
230}
231
232#[route(GET "/api/v1/version")]
233async fn version_route(_cx: &Cx) -> topcoat::Result<Response> {
234 Ok(api::json(
235 StatusCode::OK,
236 &json!({ "version": GITEA_VERSION }),
237 ))
238}
239
240#[route(GET "/api/v1/settings/api")]
241async fn settings_api(_cx: &Cx) -> topcoat::Result<Response> {
242 Ok(api::json(
243 StatusCode::OK,
244 &json!({
245 "max_response_items": MAX_PAGE,
246 "default_paging_num": DEFAULT_PAGE,
247 "default_git_trees_per_page": 1000,
248 "default_max_blob_size": 10_485_760,
249 }),
250 ))
251}
252
253/// The clone URL; a private repo read with a token carries the token as the password so the
254/// server doing the migration can clone with it (git here accepts `oauth2` as the user name).
255fn clone_url(base: &str, repo: &CoreRepo, token: Option<&str>) -> String {
256 let plain = format!("{base}/{}/{}.git", repo.owner_name, repo.name);
257 match (repo.visibility, token) {
258 (Visibility::Private, Some(token)) => match plain.split_once("://") {
259 Some((scheme, rest)) => format!("{scheme}://oauth2:{token}@{rest}"),
260 None => plain,
261 },
262 _ => plain,
263 }
264}
265
266/// The Gitea repository object. `token` embeds credentials in `clone_url` for private repos.
267pub async fn repo_json(
268 state: &AppState,
269 base: &str,
270 repo: &CoreRepo,
271 token: Option<&str>,
272) -> Result<Value, Refusal> {
273 let empty = repo.default_branch.is_empty();
274 let ssh_host = &state.config.ssh_public_host;
275 Ok(json!({
276 "id": numeric_id(&repo.id),
277 "owner": user_json(base, &repo.owner_id, &repo.owner_name),
278 "name": repo.name,
279 "full_name": format!("{}/{}", repo.owner_name, repo.name),
280 "description": repo.description,
281 "empty": empty,
282 "private": repo.visibility == Visibility::Private,
283 "fork": repo.fork_of.is_some(),
284 "template": false,
285 "mirror": false,
286 "archived": repo.archived,
287 "website": "",
288 "html_url": format!("{base}/{}/{}", repo.owner_name, repo.name),
289 "clone_url": clone_url(base, repo, token),
290 "ssh_url": format!("git@{ssh_host}:{}/{}.git", repo.owner_name, repo.name),
291 "original_url": "",
292 "default_branch": repo.default_branch,
293 "avatar_url": "",
294 "has_issues": true,
295 "has_pull_requests": true,
296 "has_wiki": true,
297 "has_releases": true,
298 "created_at": repo.created_at,
299 "updated_at": repo.created_at,
300 }))
301}
302
303#[route(GET "/api/v1/repos/{owner}/{repo}")]
304async fn get_repo(cx: &Cx) -> topcoat::Result<Response> {
305 let state = app_context::<AppState>(cx);
306 let ctx = match read_ctx(cx).await {
307 Ok(ctx) => ctx,
308 Err(res) => return Ok(*res),
309 };
310 match repo_json(state, &ctx.base, &ctx.repo, ctx.token.as_deref()).await {
311 Ok(value) => Ok(api::json(StatusCode::OK, &value)),
312 Err(res) => Ok(*res),
313 }
314}
315
316/// Forge repos have no topics yet; the list is empty.
317#[route(GET "/api/v1/repos/{owner}/{repo}/topics")]
318async fn topics_route(cx: &Cx) -> topcoat::Result<Response> {
319 match read_ctx(cx).await {
320 Ok(_) => Ok(api::json(StatusCode::OK, &json!({ "topics": [] }))),
321 Err(res) => Ok(*res),
322 }
323}
324
325fn label_json(base: &str, repo: &CoreRepo, label: &Label) -> Value {
326 json!({
327 "id": numeric_id(&label.id),
328 "name": label.name,
329 "exclusive": false,
330 "is_archived": false,
331 "color": label.color.trim_start_matches('#'),
332 "description": label.description,
333 "url": format!("{base}/api/v1/repos/{}/{}/labels/{}", repo.owner_name, repo.name, numeric_id(&label.id)),
334 })
335}
336
337#[route(GET "/api/v1/repos/{owner}/{repo}/labels")]
338async fn list_labels_route(cx: &Cx) -> topcoat::Result<Response> {
339 let state = app_context::<AppState>(cx);
340 let ctx = match read_ctx(cx).await {
341 Ok(ctx) => ctx,
342 Err(res) => return Ok(*res),
343 };
344 let all = match state.store.list_labels(&ctx.repo.id).await {
345 Ok(all) => all,
346 Err(e) => return Ok(*internal(e)),
347 };
348 let pg = paging(cx, DEFAULT_PAGE);
349 let (page, total) = slice(all, &pg);
350 let items = page
351 .iter()
352 .map(|l| label_json(&ctx.base, &ctx.repo, l))
353 .collect();
354 Ok(page_response(cx, items, total, &pg))
355}
356
357fn date_time(date: &str) -> String {
358 if date.len() == 10 {
359 format!("{date}T00:00:00Z")
360 } else {
361 date.to_owned()
362 }
363}
364
365fn milestone_json(m: &Milestone) -> Value {
366 json!({
367 "id": numeric_id(&m.id),
368 "title": m.title,
369 "description": m.description,
370 "state": m.state.as_str(),
371 "open_issues": m.open_issues,
372 "closed_issues": m.closed_issues,
373 "created_at": m.created_at,
374 "updated_at": m.closed_at.clone().unwrap_or_else(|| m.created_at.clone()),
375 "closed_at": m.closed_at,
376 "due_on": m.due_on.as_deref().map(date_time),
377 })
378}
379
380/// `state` of a Gitea list: `open` (the default), `closed` or `all`.
381fn state_filter(cx: &Cx) -> Result<Option<IssueState>, Refusal> {
382 match query_value(cx, "state").as_deref() {
383 None | Some("") | Some("open") => Ok(Some(IssueState::Open)),
384 Some("closed") => Ok(Some(IssueState::Closed)),
385 Some("all") => Ok(None),
386 Some(other) => Err(bad(&format!("unknown state {other:?}"))),
387 }
388}
389
390#[route(GET "/api/v1/repos/{owner}/{repo}/milestones")]
391async fn list_milestones_route(cx: &Cx) -> topcoat::Result<Response> {
392 let state = app_context::<AppState>(cx);
393 let ctx = match read_ctx(cx).await {
394 Ok(ctx) => ctx,
395 Err(res) => return Ok(*res),
396 };
397 let wanted = match state_filter(cx) {
398 Ok(wanted) => wanted,
399 Err(res) => return Ok(*res),
400 };
401 let all = match state.store.list_milestones(&ctx.repo.id, wanted).await {
402 Ok(all) => all,
403 Err(e) => return Ok(*internal(e)),
404 };
405 let pg = paging(cx, DEFAULT_PAGE);
406 let (page, total) = slice(all, &pg);
407 let items = page.iter().map(milestone_json).collect();
408 Ok(page_response(cx, items, total, &pg))
409}
410
411/// Usernames by user id, with `ghost` for an id that no longer resolves.
412async fn names(state: &AppState, ids: Vec<String>) -> Result<HashMap<String, String>, Refusal> {
413 let found = state.store.usernames_by_ids(&ids).await.map_err(internal)?;
414 Ok(found
415 .into_iter()
416 .map(|(id, (name, _))| (id, name))
417 .collect())
418}
419
420fn user_of(base: &str, names: &HashMap<String, String>, id: &str) -> Value {
421 let name = names.get(id).map_or("ghost", String::as_str);
422 user_json(base, id, name)
423}
424
425/// Shared by issues and pull requests: the fields both lists carry.
426async fn issue_core(
427 state: &AppState,
428 ctx: &Ctx,
429 item: &IssueListItem,
430 milestones: &HashMap<String, Milestone>,
431 pull: bool,
432) -> Result<Value, Refusal> {
433 let issue = &item.issue;
434 let assignees = state
435 .store
436 .issue_assignees(&issue.id)
437 .await
438 .map_err(internal)?;
439 let assignees: Vec<Value> = assignees
440 .iter()
441 .map(|(id, name)| user_json(&ctx.base, id, name))
442 .collect();
443 let url = format!(
444 "{}/{}/{}/{}/{}",
445 ctx.base,
446 ctx.repo.owner_name,
447 ctx.repo.name,
448 if pull { "pulls" } else { "issues" },
449 issue.number
450 );
451 Ok(json!({
452 "id": numeric_id(&issue.id),
453 "number": issue.number,
454 "user": user_json(&ctx.base, &issue.author_id, &item.author),
455 "title": issue.title,
456 "body": issue.body,
457 "labels": item.labels.iter().map(|l| label_json(&ctx.base, &ctx.repo, l)).collect::<Vec<_>>(),
458 "milestone": issue.milestone_id.as_ref().and_then(|m| milestones.get(m)).map(milestone_json),
459 "assignee": assignees.first(),
460 "assignees": assignees,
461 "state": issue.state.as_str(),
462 "is_locked": issue.locked,
463 "comments": issue.comment_count,
464 "created_at": issue.created_at,
465 "updated_at": issue.updated_at,
466 "closed_at": issue.closed_at,
467 "due_date": null,
468 "html_url": url,
469 "url": format!("{}/api/v1/repos/{}/{}/issues/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, issue.number),
470 "pull_request": if pull { json!({"merged": false, "merged_at": null, "html_url": url}) } else { Value::Null },
471 }))
472}
473
474async fn milestone_map(
475 state: &AppState,
476 repo: &CoreRepo,
477) -> Result<HashMap<String, Milestone>, Refusal> {
478 let all = state
479 .store
480 .list_milestones(&repo.id, None)
481 .await
482 .map_err(internal)?;
483 Ok(all.into_iter().map(|m| (m.id.clone(), m)).collect())
484}
485
486fn filter_of(cx: &Cx, pg: &Paging) -> Result<IssueFilter, Refusal> {
487 Ok(IssueFilter {
488 state: state_filter(cx)?,
489 sort: IssueSort::Oldest,
490 page: pg.page as u32,
491 per_page: pg.limit as u32,
492 ..IssueFilter::default()
493 })
494}
495
496#[route(GET "/api/v1/repos/{owner}/{repo}/issues")]
497async fn list_issues_route(cx: &Cx) -> topcoat::Result<Response> {
498 let state = app_context::<AppState>(cx);
499 let ctx = match read_ctx(cx).await {
500 Ok(ctx) => ctx,
501 Err(res) => return Ok(*res),
502 };
503 match issues_inner(cx, state, &ctx).await {
504 Ok(res) => Ok(res),
505 Err(res) => Ok(*res),
506 }
507}
508
509async fn issues_inner(cx: &Cx, state: &AppState, ctx: &Ctx) -> Result<Response, Refusal> {
510 let pg = paging(cx, DEFAULT_PAGE);
511 let filter = filter_of(cx, &pg)?;
512 let pulls = query_value(cx, "type").as_deref() == Some("pulls");
513 let (rows, total) = if pulls {
514 state.store.list_pulls(&ctx.repo.id, &filter).await
515 } else {
516 state.store.list_issues(&ctx.repo.id, &filter).await
517 }
518 .map_err(internal)?;
519 let milestones = milestone_map(state, &ctx.repo).await?;
520 let mut out = Vec::with_capacity(rows.len());
521 for item in &rows {
522 out.push(issue_core(state, ctx, item, &milestones, pulls).await?);
523 }
524 Ok(page_response(cx, out, total as usize, &pg))
525}
526
527/// The issue row with this number. A pull request is an issue row too, so its comments and
528/// reactions are found through here as well.
529async fn issue_row(
530 state: &AppState,
531 repo: &CoreRepo,
532 raw: &str,
533) -> Result<forge_core::issues::Issue, Refusal> {
534 let number: i64 = raw.parse().map_err(|_| bad("invalid issue index"))?;
535 match state.store.issue_by_number(&repo.id, number).await {
536 Ok(Some(issue)) => return Ok(issue),
537 Ok(None) => {}
538 Err(e) => return Err(internal(e)),
539 }
540 match state.store.pull_by_number(&repo.id, number).await {
541 Ok(Some(pull)) => Ok(pull.issue),
542 Ok(None) => Err(not_found("issue not found")),
543 Err(e) => Err(internal(e)),
544 }
545}
546
547fn comment_json(
548 ctx: &Ctx,
549 issue_number: i64,
550 position: usize,
551 comment: &Comment,
552 names: &HashMap<String, String>,
553) -> Value {
554 let id = comment_id(issue_number, position);
555 let issue_url = format!(
556 "{}/{}/{}/issues/{issue_number}",
557 ctx.base, ctx.repo.owner_name, ctx.repo.name
558 );
559 json!({
560 "id": id,
561 "html_url": format!("{issue_url}#comment-{id}"),
562 "issue_url": issue_url,
563 "pull_request_url": "",
564 "user": user_of(&ctx.base, names, &comment.author_id),
565 "original_author": "",
566 "original_author_id": 0,
567 "body": comment.body,
568 "created_at": comment.created_at,
569 "updated_at": comment.updated_at,
570 })
571}
572
573#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")]
574async fn issue_comments(cx: &Cx) -> topcoat::Result<Response> {
575 let state = app_context::<AppState>(cx);
576 let ctx = match read_ctx(cx).await {
577 Ok(ctx) => ctx,
578 Err(res) => return Ok(*res),
579 };
580 let result: Result<Response, Refusal> = async {
581 let issue = issue_row(state, &ctx.repo, path_param::<Index>(cx)).await?;
582 let all = state
583 .store
584 .list_comments(&issue.id)
585 .await
586 .map_err(internal)?;
587 let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect();
588 let pg = paging(cx, DEFAULT_PAGE);
589 let (page, total) = slice(numbered, &pg);
590 let authors = names(
591 state,
592 page.iter().map(|(_, c)| c.author_id.clone()).collect(),
593 )
594 .await?;
595 let items = page
596 .iter()
597 .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors))
598 .collect();
599 Ok(page_response(cx, items, total, &pg))
600 }
601 .await;
602 Ok(result.unwrap_or_else(|res| *res))
603}
604
605/// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji.
606async fn reactions_json(
607 state: &AppState,
608 ctx: &Ctx,
609 kind: ReactionTarget,
610 target_id: &str,
611 created_at: &str,
612) -> Result<Vec<Value>, Refusal> {
613 let map = state
614 .store
615 .reactions_for(kind, &[target_id.to_owned()], None)
616 .await
617 .map_err(internal)?;
618 let mut out = Vec::new();
619 for summary in map.get(target_id).into_iter().flatten() {
620 for username in &summary.users {
621 let id = match state.store.user_by_username(username).await {
622 Ok(Some(user)) => user.id,
623 _ => continue,
624 };
625 out.push(json!({
626 "user": user_json(&ctx.base, &id, username),
627 "reaction": summary.reaction.name(),
628 "created_at": created_at,
629 }));
630 }
631 }
632 Ok(out)
633}
634
635#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")]
636async fn issue_reactions(cx: &Cx) -> topcoat::Result<Response> {
637 let state = app_context::<AppState>(cx);
638 let ctx = match read_ctx(cx).await {
639 Ok(ctx) => ctx,
640 Err(res) => return Ok(*res),
641 };
642 let result: Result<Response, Refusal> = async {
643 let issue = issue_row(state, &ctx.repo, path_param::<Index>(cx)).await?;
644 let all = reactions_json(
645 state,
646 &ctx,
647 ReactionTarget::Issue,
648 &issue.id,
649 &issue.created_at,
650 )
651 .await?;
652 let pg = paging(cx, 1000);
653 let (page, total) = slice(all, &pg);
654 Ok(page_response(cx, page, total, &pg))
655 }
656 .await;
657 Ok(result.unwrap_or_else(|res| *res))
658}
659
660#[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")]
661async fn comment_reactions(cx: &Cx) -> topcoat::Result<Response> {
662 let state = app_context::<AppState>(cx);
663 let ctx = match read_ctx(cx).await {
664 Ok(ctx) => ctx,
665 Err(res) => return Ok(*res),
666 };
667 let result: Result<Response, Refusal> = async {
668 let id: i64 = path_param::<Id>(cx)
669 .parse()
670 .map_err(|_| bad("invalid comment id"))?;
671 let (number, position) =
672 split_comment_id(id).ok_or_else(|| not_found("comment not found"))?;
673 let issue = issue_row(state, &ctx.repo, &number.to_string()).await?;
674 let all = state
675 .store
676 .list_comments(&issue.id)
677 .await
678 .map_err(internal)?;
679 let comment = all
680 .get(position)
681 .ok_or_else(|| not_found("comment not found"))?;
682 let items = reactions_json(
683 state,
684 &ctx,
685 ReactionTarget::Comment,
686 &comment.id,
687 &comment.created_at,
688 )
689 .await?;
690 let pg = paging(cx, 1000);
691 let (page, total) = slice(items, &pg);
692 Ok(page_response(cx, page, total, &pg))
693 }
694 .await;
695 Ok(result.unwrap_or_else(|res| *res))
696}
697
698fn pr_branch(
699 ctx: &Ctx,
700 label_owner: &str,
701 repo: Option<&CoreRepo>,
702 branch: &str,
703 sha: &str,
704) -> Value {
705 json!({
706 "label": format!("{label_owner}:{branch}"),
707 "ref": branch,
708 "sha": sha,
709 "repo_id": repo.map(|r| numeric_id(&r.id)),
710 "repo": repo.map(|r| json!({
711 "id": numeric_id(&r.id),
712 "owner": user_json(&ctx.base, &r.owner_id, &r.owner_name),
713 "name": r.name,
714 "full_name": format!("{}/{}", r.owner_name, r.name),
715 "private": r.visibility == Visibility::Private,
716 "html_url": format!("{}/{}/{}", ctx.base, r.owner_name, r.name),
717 "clone_url": format!("{}/{}/{}.git", ctx.base, r.owner_name, r.name),
718 "default_branch": r.default_branch,
719 })),
720 })
721}
722
723async fn pull_json(
724 state: &AppState,
725 ctx: &Ctx,
726 item: &IssueListItem,
727 pull: &PullRequest,
728 milestones: &HashMap<String, Milestone>,
729) -> Result<Value, Refusal> {
730 let mut value = issue_core(state, ctx, item, milestones, true).await?;
731 let head_repo = match &pull.head_repo_id {
732 Some(id) if *id == ctx.repo.id => Some(ctx.repo.clone()),
733 Some(id) => state.store.repo_by_id(id).await.map_err(internal)?,
734 None => None,
735 };
736 // A head repo the caller cannot read is shown without its repo object.
737 let head_repo = match head_repo {
738 Some(r) if r.id == ctx.repo.id || r.visibility == Visibility::Public => Some(r),
739 _ => None,
740 };
741 let head_owner = head_repo
742 .as_ref()
743 .map_or(ctx.repo.owner_name.as_str(), |r| r.owner_name.as_str());
744 let merged_by = match &pull.merged_by {
745 Some(id) => state
746 .store
747 .usernames_by_ids(std::slice::from_ref(id))
748 .await
749 .map_err(internal)?
750 .get(id)
751 .map(|(name, _)| user_json(&ctx.base, id, name)),
752 None => None,
753 };
754 let html = format!(
755 "{}/{}/{}/pulls/{}",
756 ctx.base, ctx.repo.owner_name, ctx.repo.name, pull.issue.number
757 );
758 let obj = value.as_object_mut().expect("object");
759 obj.insert("merged".into(), json!(pull.merged_at.is_some()));
760 obj.insert("merged_at".into(), json!(pull.merged_at));
761 obj.insert("merged_by".into(), json!(merged_by));
762 obj.insert("merge_commit_sha".into(), json!(pull.merge_commit));
763 obj.insert("merged_commit_id".into(), json!(pull.merge_commit));
764 obj.insert("merge_base".into(), json!(pull.merge_base));
765 obj.insert(
766 "mergeable".into(),
767 json!(matches!(
768 pull.mergeable,
769 forge_core::pulls::Mergeable::Clean
770 )),
771 );
772 obj.insert("draft".into(), json!(pull.draft));
773 obj.insert("allow_maintainer_edit".into(), json!(false));
774 obj.insert("diff_url".into(), json!(format!("{html}.diff")));
775 obj.insert("patch_url".into(), json!(format!("{html}.patch")));
776 obj.insert("flow".into(), json!(0));
777 obj.insert(
778 "base".into(),
779 pr_branch(
780 ctx,
781 &ctx.repo.owner_name,
782 Some(&ctx.repo),
783 &pull.base_branch,
784 &pull.base_oid,
785 ),
786 );
787 obj.insert(
788 "head".into(),
789 pr_branch(
790 ctx,
791 head_owner,
792 head_repo.as_ref(),
793 &pull.head_branch,
794 &pull.head_oid,
795 ),
796 );
797 obj.insert(
798 "pull_request".into(),
799 json!({"merged": pull.merged_at.is_some(), "merged_at": pull.merged_at, "html_url": html}),
800 );
801 Ok(value)
802}
803
804#[route(GET "/api/v1/repos/{owner}/{repo}/pulls")]
805async fn list_pulls_route(cx: &Cx) -> topcoat::Result<Response> {
806 let state = app_context::<AppState>(cx);
807 let ctx = match read_ctx(cx).await {
808 Ok(ctx) => ctx,
809 Err(res) => return Ok(*res),
810 };
811 let result: Result<Response, Refusal> = async {
812 let pg = paging(cx, DEFAULT_PAGE);
813 let filter = filter_of(cx, &pg)?;
814 let (rows, total) = state
815 .store
816 .list_pulls(&ctx.repo.id, &filter)
817 .await
818 .map_err(internal)?;
819 let milestones = milestone_map(state, &ctx.repo).await?;
820 let mut out = Vec::with_capacity(rows.len());
821 for item in &rows {
822 let Some(pull) = state
823 .store
824 .pull_by_number(&ctx.repo.id, item.issue.number)
825 .await
826 .map_err(internal)?
827 else {
828 continue;
829 };
830 out.push(pull_json(state, &ctx, item, &pull, &milestones).await?);
831 }
832 Ok(page_response(cx, out, total as usize, &pg))
833 }
834 .await;
835 Ok(result.unwrap_or_else(|res| *res))
836}
837
838/// The review state as Forgejo's uploader reads it (`CHANGES_REQUESTED`, `COMMENTED`). The Go SDK
839/// names are `REQUEST_CHANGES` and `COMMENT`, which the uploader maps to a pending review, found
840/// by migrating for real.
841fn review_state(review: &Review) -> &'static str {
842 let effective = if review.state == ReviewState::Dismissed {
843 review.dismissed_from.unwrap_or(ReviewState::Commented)
844 } else {
845 review.state
846 };
847 match effective {
848 ReviewState::Approved => "APPROVED",
849 ReviewState::ChangesRequested => "CHANGES_REQUESTED",
850 ReviewState::Pending => "PENDING",
851 ReviewState::Commented | ReviewState::Dismissed => "COMMENTED",
852 }
853}
854
855fn review_json(ctx: &Ctx, number: i64, review: &Review, comment_count: usize) -> Value {
856 let html = format!(
857 "{}/{}/{}/pulls/{number}",
858 ctx.base, ctx.repo.owner_name, ctx.repo.name
859 );
860 json!({
861 "id": numeric_id(&review.id),
862 "user": user_json(&ctx.base, &review.author_id, &review.author_name),
863 "team": null,
864 "state": review_state(review),
865 "body": review.body,
866 "commit_id": review.commit_oid,
867 "stale": false,
868 "official": matches!(review_state(review), "APPROVED" | "CHANGES_REQUESTED"),
869 "dismissed": review.state == ReviewState::Dismissed,
870 "comments_count": comment_count,
871 "submitted_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()),
872 "updated_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()),
873 "html_url": format!("{html}#{}", numeric_id(&review.id)),
874 "pull_request_url": html,
875 })
876}
877
878/// Every non-pending review comment of the pull request, roots and replies, oldest first.
879async fn review_comments(state: &AppState, issue_id: &str) -> Result<Vec<ReviewComment>, Refusal> {
880 let threads = state
881 .store
882 .review_threads(issue_id, None)
883 .await
884 .map_err(internal)?;
885 let mut all: Vec<ReviewComment> = threads
886 .into_iter()
887 .flat_map(|t| std::iter::once(t.root).chain(t.replies))
888 .filter(|c| !c.pending)
889 .collect();
890 all.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
891 Ok(all)
892}
893
894#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")]
895async fn pull_reviews(cx: &Cx) -> topcoat::Result<Response> {
896 let state = app_context::<AppState>(cx);
897 let ctx = match read_ctx(cx).await {
898 Ok(ctx) => ctx,
899 Err(res) => return Ok(*res),
900 };
901 let result: Result<Response, Refusal> = async {
902 let issue = pull_issue(state, &ctx.repo, path_param::<Index>(cx)).await?;
903 let reviews = state
904 .store
905 .list_reviews(&issue.id)
906 .await
907 .map_err(internal)?;
908 let comments = review_comments(state, &issue.id).await?;
909 let pg = paging(cx, DEFAULT_PAGE);
910 let (page, total) = slice(reviews, &pg);
911 let items = page
912 .iter()
913 .map(|r| {
914 let count = comments.iter().filter(|c| c.review_id == r.id).count();
915 review_json(&ctx, issue.number, r, count)
916 })
917 .collect();
918 Ok(page_response(cx, items, total, &pg))
919 }
920 .await;
921 Ok(result.unwrap_or_else(|res| *res))
922}
923
924/// The issue row of a number that must be a pull request.
925async fn pull_issue(
926 state: &AppState,
927 repo: &CoreRepo,
928 raw: &str,
929) -> Result<forge_core::issues::Issue, Refusal> {
930 let number: i64 = raw.parse().map_err(|_| bad("invalid pull request index"))?;
931 match state.store.pull_by_number(&repo.id, number).await {
932 Ok(Some(pull)) => Ok(pull.issue),
933 Ok(None) => Err(not_found("pull request not found")),
934 Err(e) => Err(internal(e)),
935 }
936}
937
938fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value {
939 let html = format!(
940 "{}/{}/{}/pulls/{number}",
941 ctx.base, ctx.repo.owner_name, ctx.repo.name
942 );
943 let (line, old_line) = match c.side {
944 Side::New => (c.line, 0),
945 Side::Old => (0, c.line),
946 };
947 json!({
948 "id": numeric_id(&c.id),
949 "body": c.body,
950 "user": user_json(&ctx.base, &c.author_id, &c.author_name),
951 "resolver": null,
952 "pull_request_review_id": numeric_id(&c.review_id),
953 "created_at": c.created_at,
954 "updated_at": c.updated_at,
955 "path": c.path,
956 "commit_id": c.commit_oid,
957 "original_commit_id": c.commit_oid,
958 "diff_hunk": c.diff_hunk,
959 "position": line,
960 "original_position": line,
961 "line_num": line,
962 "old_line_num": old_line,
963 "html_url": format!("{html}#{}", numeric_id(&c.id)),
964 "pull_request_url": html,
965 })
966}
967
968#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")]
969async fn pull_review_comments(cx: &Cx) -> topcoat::Result<Response> {
970 let state = app_context::<AppState>(cx);
971 let ctx = match read_ctx(cx).await {
972 Ok(ctx) => ctx,
973 Err(res) => return Ok(*res),
974 };
975 let result: Result<Response, Refusal> = async {
976 let issue = pull_issue(state, &ctx.repo, path_param::<Index>(cx)).await?;
977 let raw = path_param::<ReviewId>(cx);
978 let reviews = state
979 .store
980 .list_reviews(&issue.id)
981 .await
982 .map_err(internal)?;
983 let review = reviews
984 .iter()
985 .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id))))
986 .ok_or_else(|| not_found("review not found"))?;
987 let own: Vec<ReviewComment> = review_comments(state, &issue.id)
988 .await?
989 .into_iter()
990 .filter(|c| c.review_id == review.id)
991 .collect();
992 let items = own
993 .iter()
994 .map(|c| review_comment_json(&ctx, issue.number, c))
995 .collect::<Vec<_>>();
996 let total = items.len();
997 // Review comments are not paged by the downloader; return them whole.
998 let pg = Paging {
999 page: 1,
1000 limit: total.max(1),
1001 };
1002 Ok(page_response(cx, items, total, &pg))
1003 }
1004 .await;
1005 Ok(result.unwrap_or_else(|res| *res))
1006}