forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

api.rs1537 lines, 47.2 KiBHistoryRawDownload
1//! Remote forge APIs for imports. [`RemoteApi`] is the seam: the import job talks only to the
2//! trait, so tests use a fake and CI never needs the network. [`GitHub`] and [`GitLab`] are the real
3//! clients over REST. They paginate, wait out rate limits (and say so through the notice callback),
4//! and send the token only to the API host, never to a redirect target.
5
6use std::fmt;
7use std::future::Future;
8use std::io;
9use std::sync::Arc;
10use std::time::Duration;
11
12use bytes::Bytes;
13use futures_util::stream::{BoxStream, StreamExt};
14use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER};
15use serde::Deserialize;
16use serde::de::DeserializeOwned;
17
18use crate::webhooks::client::{WebhookPolicy, validate_url};
19
20/// A release asset's bytes as they arrive from the server, ready for the blob writer.
21pub type AssetStream = BoxStream<'static, io::Result<Bytes>>;
22
23const PER_PAGE: usize = 100;
24/// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
25/// Forgejo and Gitea cap `limit` at 50 by default.
26const FORGEJO_LIMIT: usize = 50;
27const MAX_PAGES: usize = 500;
28/// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues.
29const MAX_RATE_WAIT: u64 = 15 * 60;
30/// Largest JSON page read.
31const MAX_JSON_BYTES: usize = 32 * 1024 * 1024;
32const MAX_REDIRECTS: usize = 5;
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum ApiError {
36 NotFound(String),
37 Unauthorized(String),
38 RateLimited { wait_secs: u64 },
39 TooLarge,
40 Http(String),
41 Parse(String),
42}
43
44impl fmt::Display for ApiError {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 ApiError::NotFound(what) => write!(f, "not found: {what}"),
48 ApiError::Unauthorized(what) => write!(f, "access denied: {what}"),
49 ApiError::RateLimited { wait_secs } => write!(
50 f,
51 "the rate limit is used up and resets in {}; retry then, nothing imported is lost",
52 wait_text(*wait_secs)
53 ),
54 ApiError::TooLarge => write!(f, "the file is larger than the allowed size"),
55 ApiError::Http(msg) => write!(f, "request failed: {msg}"),
56 ApiError::Parse(msg) => write!(f, "unexpected response: {msg}"),
57 }
58 }
59}
60
61/// `secs` as a reader would say it, rounded up to the minute so a retry at that time is not early.
62fn wait_text(secs: u64) -> String {
63 let plural = |n: u64| if n == 1 { "" } else { "s" };
64 if secs < 60 {
65 return format!("{secs} second{}", plural(secs));
66 }
67 let minutes = secs.div_ceil(60);
68 let (hours, rest) = (minutes / 60, minutes % 60);
69 match (hours, rest) {
70 (0, m) => format!("{m} minute{}", plural(m)),
71 (h, 0) => format!("{h} hour{}", plural(h)),
72 (h, m) => format!("{h} hour{} {m} minute{}", plural(h), plural(m)),
73 }
74}
75
76pub type ApiResult<T> = Result<T, ApiError>;
77
78#[derive(Debug, Clone, PartialEq, Eq, Default)]
79pub struct ExtLabel {
80 pub name: String,
81 pub color: String,
82 pub description: String,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub struct ExtMilestone {
87 pub id: String,
88 pub title: String,
89 pub description: String,
90 pub closed: bool,
91 /// `YYYY-MM-DD`.
92 pub due_on: Option<String>,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Default)]
96pub struct ExtIssue {
97 pub number: i64,
98 pub title: String,
99 pub body: String,
100 pub closed: bool,
101 pub not_planned: bool,
102 pub merged: bool,
103 pub author: String,
104 pub labels: Vec<String>,
105 pub milestone: Option<String>,
106 pub created_at: String,
107 pub url: String,
108 pub is_pr: bool,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Default)]
112pub struct ExtComment {
113 pub id: String,
114 pub author: String,
115 pub body: String,
116 pub created_at: String,
117 pub url: String,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Default)]
121pub struct ExtAsset {
122 pub id: String,
123 pub name: String,
124 pub size: u64,
125 pub content_type: String,
126 pub url: String,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Default)]
130pub struct ExtRelease {
131 pub id: String,
132 pub tag: String,
133 pub title: String,
134 pub body: String,
135 pub draft: bool,
136 pub prerelease: bool,
137 pub author: String,
138 pub created_at: String,
139 pub url: String,
140 pub assets: Vec<ExtAsset>,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Default)]
144pub struct ExtRepo {
145 pub name: String,
146 /// `owner/name`, or the GitLab project path.
147 pub full_name: String,
148 pub description: String,
149 pub private: bool,
150 pub fork: bool,
151 pub archived: bool,
152 pub default_branch: String,
153 pub web_url: String,
154}
155
156/// What an import needs from a remote forge. `repo` is `owner/name` for GitHub and the full
157/// project path for GitLab.
158pub trait RemoteApi: Send + Sync {
159 fn list_repos(&self, owner: &str) -> impl Future<Output = ApiResult<Vec<ExtRepo>>> + Send;
160 fn labels(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtLabel>>> + Send;
161 fn milestones(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtMilestone>>> + Send;
162 /// Issues and pull (merge) requests, every state, with `is_pr` set on the latter.
163 fn issues(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtIssue>>> + Send;
164 fn comments(
165 &self,
166 repo: &str,
167 issue: &ExtIssue,
168 ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;
169 fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;
170 /// The bytes of a release asset, at most `max_bytes`, streamed as they arrive.
171 fn download(
172 &self,
173 asset: &ExtAsset,
174 max_bytes: u64,
175 ) -> impl Future<Output = ApiResult<AssetStream>> + Send;
176}
177
178/// True for one URL path segment of an owner, repo or group name.
179pub fn valid_segment(s: &str) -> bool {
180 !s.is_empty()
181 && s.len() <= 100
182 && s != "."
183 && s != ".."
184 && s.bytes()
185 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
186}
187
188/// `owner/name` made of valid segments, `min..=max` of them.
189pub fn valid_path(path: &str, min: usize, max: usize) -> bool {
190 let parts: Vec<&str> = path.split('/').collect();
191 (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p))
192}
193
194/// How long to wait after a 403 or 429. `None` when the response is not a rate limit.
195pub fn rate_wait(
196 retry_after: Option<&str>,
197 remaining: Option<&str>,
198 reset_unix: Option<&str>,
199 now_unix: i64,
200) -> Option<u64> {
201 if let Some(secs) = retry_after.and_then(|v| v.trim().parse::<u64>().ok()) {
202 return Some(secs.max(1));
203 }
204 if remaining.map(str::trim) == Some("0") {
205 let reset = reset_unix.and_then(|v| v.trim().parse::<i64>().ok())?;
206 return Some(u64::try_from(reset - now_unix).unwrap_or(0).max(1));
207 }
208 None
209}
210
211pub type Notice = Arc<dyn Fn(String) + Send + Sync>;
212
213/// How the token is presented to the API host.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum Auth {
216 /// `Authorization: Bearer`.
217 GitHub,
218 /// `PRIVATE-TOKEN`.
219 GitLab,
220 /// `Authorization: token`.
221 Forgejo,
222}
223
224/// A client under the outbound policy, with the token kept private to the API host.
225pub struct Http {
226 client: reqwest::Client,
227 policy: WebhookPolicy,
228 token: Option<String>,
229 auth: Auth,
230 auth_host: String,
231 notice: Notice,
232}
233
234impl Http {
235 pub fn new(
236 client: reqwest::Client,
237 policy: WebhookPolicy,
238 token: Option<String>,
239 auth: Auth,
240 auth_host: String,
241 notice: Notice,
242 ) -> Self {
243 let token = token.filter(|t| !t.trim().is_empty());
244 Http {
245 client,
246 policy,
247 token,
248 auth,
249 auth_host,
250 notice,
251 }
252 }
253
254 fn host_of(url: &str) -> String {
255 reqwest::Url::parse(url)
256 .ok()
257 .and_then(|u| u.host_str().map(str::to_ascii_lowercase))
258 .unwrap_or_default()
259 }
260
261 fn request(&self, url: &str, accept: &str, authed: bool) -> reqwest::RequestBuilder {
262 let mut req = self.client.get(url).header(ACCEPT, accept);
263 if authed
264 && Self::host_of(url) == self.auth_host
265 && let Some(token) = &self.token
266 {
267 req = match self.auth {
268 Auth::GitLab => req.header("PRIVATE-TOKEN", token),
269 Auth::GitHub => req
270 .header(AUTHORIZATION, format!("Bearer {token}"))
271 .header("X-GitHub-Api-Version", "2022-11-28"),
272 Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")),
273 };
274 }
275 req
276 }
277
278 fn header(headers: &HeaderMap, name: &str) -> Option<String> {
279 headers
280 .get(name)
281 .and_then(|v| v.to_str().ok())
282 .map(str::to_owned)
283 }
284
285 /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx.
286 async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {
287 // Every URL, including one taken from an API answer or a redirect: the client's resolver
288 // filters host names, but an address literal never reaches it.
289 validate_url(url, &self.policy)
290 .map_err(|e| ApiError::Http(format!("address refused: {e}")))?;
291 let mut attempt = 0u32;
292 loop {
293 attempt += 1;
294 let resp = self
295 .request(url, accept, authed)
296 .send()
297 .await
298 .map_err(|e| ApiError::Http(e.without_url().to_string()))?;
299 let status = resp.status();
300 if status.is_success() || status.is_redirection() {
301 return Ok(resp);
302 }
303 let headers = resp.headers();
304 match status.as_u16() {
305 401 => return Err(ApiError::Unauthorized("the token was refused".into())),
306 404 => return Err(ApiError::NotFound(Self::host_of(url))),
307 403 | 429 => {
308 let wait = rate_wait(
309 Self::header(headers, RETRY_AFTER.as_str()).as_deref(),
310 Self::header(headers, "x-ratelimit-remaining").as_deref(),
311 Self::header(headers, "x-ratelimit-reset").as_deref(),
312 jiff::Timestamp::now().as_second(),
313 )
314 .or_else(|| (status.as_u16() == 429).then_some(60));
315 let Some(wait) = wait else {
316 return Err(ApiError::Unauthorized(
317 "the server refused the request (is the token valid and allowed to read this?)"
318 .into(),
319 ));
320 };
321 if wait > MAX_RATE_WAIT || attempt > 4 {
322 return Err(ApiError::RateLimited { wait_secs: wait });
323 }
324 (self.notice)(format!("Rate limited, waiting {wait} seconds"));
325 tokio::time::sleep(Duration::from_secs(wait)).await;
326 }
327 500..=599 if attempt <= 3 => {
328 tokio::time::sleep(Duration::from_secs(u64::from(attempt) * 2)).await;
329 }
330 code => return Err(ApiError::Http(format!("status {code}"))),
331 }
332 }
333 }
334
335 async fn body(resp: reqwest::Response, max: usize) -> ApiResult<Vec<u8>> {
336 let mut resp = resp;
337 let mut out = Vec::new();
338 while let Some(chunk) = resp
339 .chunk()
340 .await
341 .map_err(|e| ApiError::Http(e.without_url().to_string()))?
342 {
343 if out.len() + chunk.len() > max {
344 return Err(ApiError::TooLarge);
345 }
346 out.extend_from_slice(&chunk);
347 }
348 Ok(out)
349 }
350
351 pub async fn json<T: DeserializeOwned>(&self, url: &str) -> ApiResult<T> {
352 let resp = self.send(url, "application/json", true).await?;
353 let bytes = Self::body(resp, MAX_JSON_BYTES).await?;
354 serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))
355 }
356
357 /// Every page of a list endpoint, 100 per page, stopping at the first short page.
358 pub async fn pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
359 let sep = if base.contains('?') { '&' } else { '?' };
360 let mut out = Vec::new();
361 for page in 1..=MAX_PAGES {
362 let url = format!("{base}{sep}per_page={PER_PAGE}&page={page}");
363 let items: Vec<T> = self.json(&url).await?;
364 let short = items.len() < PER_PAGE;
365 out.extend(items);
366 if short {
367 break;
368 }
369 }
370 Ok(out)
371 }
372
373 /// Every page of a Forgejo/Gitea list endpoint (`limit`, `page`). The `Link` header decides
374 /// when it ends; without one, `X-Total-Count`; without either, the first short page.
375 pub async fn limit_pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
376 let sep = if base.contains('?') { '&' } else { '?' };
377 let mut out: Vec<T> = Vec::new();
378 for page in 1..=MAX_PAGES {
379 let url = format!("{base}{sep}limit={FORGEJO_LIMIT}&page={page}");
380 let resp = self.send(&url, "application/json", true).await?;
381 let link = Self::header(resp.headers(), "link");
382 let total = Self::header(resp.headers(), "x-total-count")
383 .and_then(|v| v.trim().parse::<usize>().ok());
384 let bytes = Self::body(resp, MAX_JSON_BYTES).await?;
385 let items: Vec<T> =
386 serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))?;
387 let got = items.len();
388 out.extend(items);
389 let done = got == 0
390 || match (&link, total) {
391 (Some(l), _) => !l.contains("rel=\"next\""),
392 (None, Some(total)) => out.len() >= total,
393 (None, None) => got < FORGEJO_LIMIT,
394 };
395 if done {
396 break;
397 }
398 }
399 Ok(out)
400 }
401
402 /// Downloads a file, following redirects by hand: the token goes to the API host only, and
403 /// each hop is fetched under the same address policy as every other request. The body is
404 /// streamed, so a large asset is never held in memory whole.
405 pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<AssetStream> {
406 let mut current = url.to_owned();
407 for _ in 0..=MAX_REDIRECTS {
408 let resp = self
409 .send(&current, "application/octet-stream", true)
410 .await?;
411 if resp.status().is_redirection() {
412 let next = resp
413 .headers()
414 .get(LOCATION)
415 .and_then(|v| v.to_str().ok())
416 .ok_or_else(|| ApiError::Http("redirect without a location".into()))?;
417 let base =
418 reqwest::Url::parse(&current).map_err(|e| ApiError::Http(e.to_string()))?;
419 current = base
420 .join(next)
421 .map_err(|e| ApiError::Http(e.to_string()))?
422 .to_string();
423 if !current.starts_with("https://") {
424 return Err(ApiError::Http("redirect to a non-https address".into()));
425 }
426 continue;
427 }
428 if let Some(len) = resp.content_length()
429 && len > max_bytes
430 {
431 return Err(ApiError::TooLarge);
432 }
433 return Ok(Self::stream(resp, max_bytes));
434 }
435 Err(ApiError::Http("too many redirects".into()))
436 }
437
438 /// The body as it arrives. Counting happens here, so the stream fails with `InvalidData` as
439 /// soon as more than `max` bytes have come, whether or not the server sent a length.
440 fn stream(resp: reqwest::Response, max: u64) -> AssetStream {
441 let mut seen: u64 = 0;
442 Box::pin(resp.bytes_stream().map(move |chunk| {
443 let chunk: reqwest::Result<Bytes> = chunk;
444 let chunk = chunk.map_err(|e| io::Error::other(e.without_url().to_string()))?;
445 seen = seen.saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX));
446 if seen > max {
447 return Err(io::Error::new(
448 io::ErrorKind::InvalidData,
449 "the file is larger than the allowed size",
450 ));
451 }
452 Ok(chunk)
453 }))
454 }
455}
456
457fn day(stamp: &str) -> Option<String> {
458 let d = stamp.get(..10)?;
459 let ok = d.as_bytes().iter().enumerate().all(|(i, b)| match i {
460 4 | 7 => *b == b'-',
461 _ => b.is_ascii_digit(),
462 });
463 ok.then(|| d.to_owned())
464}
465
466fn s(v: Option<String>) -> String {
467 v.unwrap_or_default()
468}
469
470// ---- GitHub ----
471
472pub struct GitHub {
473 http: Http,
474 base: String,
475}
476
477impl GitHub {
478 pub fn new(http: Http) -> Self {
479 GitHub {
480 http,
481 base: "https://api.github.com".into(),
482 }
483 }
484}
485
486#[derive(Deserialize)]
487struct GhUser {
488 login: Option<String>,
489}
490
491#[derive(Deserialize)]
492struct GhLabel {
493 name: String,
494 color: Option<String>,
495 description: Option<String>,
496}
497
498#[derive(Deserialize)]
499struct GhMilestone {
500 number: i64,
501 title: String,
502 description: Option<String>,
503 state: String,
504 due_on: Option<String>,
505}
506
507#[derive(Deserialize)]
508struct GhPull {
509 merged_at: Option<String>,
510}
511
512#[derive(Deserialize)]
513struct GhIssue {
514 number: i64,
515 title: String,
516 body: Option<String>,
517 state: String,
518 state_reason: Option<String>,
519 user: Option<GhUser>,
520 #[serde(default)]
521 labels: Vec<GhLabel>,
522 milestone: Option<GhMilestoneRef>,
523 created_at: Option<String>,
524 html_url: Option<String>,
525 pull_request: Option<GhPull>,
526}
527
528#[derive(Deserialize)]
529struct GhMilestoneRef {
530 title: String,
531}
532
533#[derive(Deserialize)]
534struct GhComment {
535 id: i64,
536 body: Option<String>,
537 user: Option<GhUser>,
538 created_at: Option<String>,
539 html_url: Option<String>,
540}
541
542#[derive(Deserialize)]
543struct GhAsset {
544 id: i64,
545 name: String,
546 size: Option<u64>,
547 content_type: Option<String>,
548 url: String,
549}
550
551#[derive(Deserialize)]
552struct GhRelease {
553 id: i64,
554 tag_name: String,
555 name: Option<String>,
556 body: Option<String>,
557 #[serde(default)]
558 draft: bool,
559 #[serde(default)]
560 prerelease: bool,
561 author: Option<GhUser>,
562 created_at: Option<String>,
563 html_url: Option<String>,
564 #[serde(default)]
565 assets: Vec<GhAsset>,
566}
567
568#[derive(Deserialize)]
569struct GhRepo {
570 name: String,
571 full_name: String,
572 description: Option<String>,
573 #[serde(default)]
574 private: bool,
575 #[serde(default)]
576 fork: bool,
577 #[serde(default)]
578 archived: bool,
579 default_branch: Option<String>,
580 html_url: Option<String>,
581}
582
583fn login(u: Option<GhUser>) -> String {
584 u.and_then(|u| u.login).unwrap_or_default()
585}
586
587#[cfg(any(test, feature = "test-support"))]
588pub fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {
589 let raw: Vec<GhLabel> = from_json(json)?;
590 Ok(raw.into_iter().map(label_of).collect())
591}
592
593fn label_of(l: GhLabel) -> ExtLabel {
594 ExtLabel {
595 name: l.name,
596 color: format!("#{}", s(l.color).trim_start_matches('#')),
597 description: s(l.description),
598 }
599}
600
601#[cfg(any(test, feature = "test-support"))]
602fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {
603 serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))
604}
605
606#[cfg(any(test, feature = "test-support"))]
607pub fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {
608 let raw: Vec<GhIssue> = from_json(json)?;
609 Ok(raw.into_iter().map(gh_issue).collect())
610}
611
612fn gh_issue(i: GhIssue) -> ExtIssue {
613 let merged = i
614 .pull_request
615 .as_ref()
616 .is_some_and(|p| p.merged_at.is_some());
617 ExtIssue {
618 number: i.number,
619 title: i.title,
620 body: s(i.body),
621 closed: i.state == "closed",
622 not_planned: i.state_reason.as_deref() == Some("not_planned"),
623 merged,
624 author: login(i.user),
625 labels: i.labels.into_iter().map(|l| l.name).collect(),
626 milestone: i.milestone.map(|m| m.title),
627 created_at: s(i.created_at),
628 url: s(i.html_url),
629 is_pr: i.pull_request.is_some(),
630 }
631}
632
633#[cfg(any(test, feature = "test-support"))]
634pub fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
635 let raw: Vec<GhRelease> = from_json(json)?;
636 Ok(raw
637 .into_iter()
638 .map(|r| ExtRelease {
639 id: r.id.to_string(),
640 title: r
641 .name
642 .filter(|n| !n.is_empty())
643 .unwrap_or_else(|| r.tag_name.clone()),
644 tag: r.tag_name,
645 body: s(r.body),
646 draft: r.draft,
647 prerelease: r.prerelease,
648 author: login(r.author),
649 created_at: s(r.created_at),
650 url: s(r.html_url),
651 assets: r
652 .assets
653 .into_iter()
654 .map(|a| ExtAsset {
655 id: a.id.to_string(),
656 name: a.name,
657 size: a.size.unwrap_or(0),
658 content_type: s(a.content_type),
659 url: a.url,
660 })
661 .collect(),
662 })
663 .collect())
664}
665
666impl RemoteApi for GitHub {
667 async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
668 if !valid_segment(owner) {
669 return Err(ApiError::NotFound("owner".into()));
670 }
671 let org: ApiResult<Vec<GhRepo>> = self
672 .http
673 .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base))
674 .await;
675 let raw = match org {
676 Ok(raw) => raw,
677 Err(ApiError::NotFound(_)) => {
678 self.http
679 .pages(&format!("{}/users/{owner}/repos?type=owner", self.base))
680 .await?
681 }
682 Err(e) => return Err(e),
683 };
684 Ok(raw
685 .into_iter()
686 .map(|r| ExtRepo {
687 name: r.name,
688 full_name: r.full_name,
689 description: s(r.description),
690 private: r.private,
691 fork: r.fork,
692 archived: r.archived,
693 default_branch: s(r.default_branch),
694 web_url: s(r.html_url),
695 })
696 .collect())
697 }
698
699 async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
700 check_repo(repo, 2, 2)?;
701 let raw: Vec<GhLabel> = self
702 .http
703 .pages(&format!("{}/repos/{repo}/labels", self.base))
704 .await?;
705 Ok(raw.into_iter().map(label_of).collect())
706 }
707
708 async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
709 check_repo(repo, 2, 2)?;
710 let raw: Vec<GhMilestone> = self
711 .http
712 .pages(&format!("{}/repos/{repo}/milestones?state=all", self.base))
713 .await?;
714 Ok(raw
715 .into_iter()
716 .map(|m| ExtMilestone {
717 id: m.number.to_string(),
718 title: m.title,
719 description: s(m.description),
720 closed: m.state == "closed",
721 due_on: m.due_on.as_deref().and_then(day),
722 })
723 .collect())
724 }
725
726 async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
727 check_repo(repo, 2, 2)?;
728 let raw: Vec<GhIssue> = self
729 .http
730 .pages(&format!(
731 "{}/repos/{repo}/issues?state=all&sort=created&direction=asc",
732 self.base
733 ))
734 .await?;
735 Ok(raw.into_iter().map(gh_issue).collect())
736 }
737
738 async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
739 check_repo(repo, 2, 2)?;
740 let raw: Vec<GhComment> = self
741 .http
742 .pages(&format!(
743 "{}/repos/{repo}/issues/{}/comments",
744 self.base, issue.number
745 ))
746 .await?;
747 Ok(raw
748 .into_iter()
749 .map(|c| ExtComment {
750 id: c.id.to_string(),
751 author: login(c.user),
752 body: s(c.body),
753 created_at: s(c.created_at),
754 url: s(c.html_url),
755 })
756 .collect())
757 }
758
759 async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
760 check_repo(repo, 2, 2)?;
761 let raw: Vec<GhRelease> = self
762 .http
763 .pages(&format!("{}/repos/{repo}/releases", self.base))
764 .await?;
765 // Reuse the one conversion by round-tripping through the parser's mapping.
766 Ok(raw.into_iter().map(gh_release).collect())
767 }
768
769 async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
770 if !asset.url.starts_with("https://api.github.com/") {
771 return Err(ApiError::Http("unexpected asset address".into()));
772 }
773 self.http.download(&asset.url, max_bytes).await
774 }
775}
776
777fn gh_release(r: GhRelease) -> ExtRelease {
778 ExtRelease {
779 id: r.id.to_string(),
780 title: r
781 .name
782 .filter(|n| !n.is_empty())
783 .unwrap_or_else(|| r.tag_name.clone()),
784 tag: r.tag_name,
785 body: s(r.body),
786 draft: r.draft,
787 prerelease: r.prerelease,
788 author: login(r.author),
789 created_at: s(r.created_at),
790 url: s(r.html_url),
791 assets: r
792 .assets
793 .into_iter()
794 .map(|a| ExtAsset {
795 id: a.id.to_string(),
796 name: a.name,
797 size: a.size.unwrap_or(0),
798 content_type: s(a.content_type),
799 url: a.url,
800 })
801 .collect(),
802 }
803}
804
805fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> {
806 if valid_path(repo, min, max) {
807 Ok(())
808 } else {
809 Err(ApiError::NotFound("repository path".into()))
810 }
811}
812
813// ---- GitLab ----
814
815pub struct GitLab {
816 http: Http,
817 /// `https://host/api/v4`.
818 base: String,
819}
820
821impl GitLab {
822 /// `instance` is the instance's web address, e.g. `https://gitlab.com`.
823 pub fn new(http: Http, instance: &str) -> Self {
824 GitLab {
825 http,
826 base: format!("{}/api/v4", instance.trim_end_matches('/')),
827 }
828 }
829
830 fn project(&self, repo: &str) -> ApiResult<String> {
831 check_repo(repo, 2, 20)?;
832 Ok(format!(
833 "{}/projects/{}",
834 self.base,
835 repo.replace('/', "%2F")
836 ))
837 }
838}
839
840#[derive(Deserialize)]
841struct GlUser {
842 username: Option<String>,
843}
844
845#[derive(Deserialize)]
846struct GlLabel {
847 name: String,
848 color: Option<String>,
849 description: Option<String>,
850}
851
852#[derive(Deserialize)]
853struct GlMilestone {
854 id: i64,
855 title: String,
856 description: Option<String>,
857 state: String,
858 due_date: Option<String>,
859}
860
861#[derive(Deserialize)]
862struct GlMilestoneRef {
863 title: String,
864}
865
866#[derive(Deserialize)]
867struct GlIssue {
868 iid: i64,
869 title: String,
870 description: Option<String>,
871 state: String,
872 author: Option<GlUser>,
873 #[serde(default)]
874 labels: Vec<String>,
875 milestone: Option<GlMilestoneRef>,
876 created_at: Option<String>,
877 web_url: Option<String>,
878}
879
880#[derive(Deserialize)]
881struct GlNote {
882 id: i64,
883 body: Option<String>,
884 author: Option<GlUser>,
885 created_at: Option<String>,
886 #[serde(default)]
887 system: bool,
888}
889
890#[derive(Deserialize)]
891struct GlLink {
892 id: i64,
893 name: String,
894 url: String,
895 direct_asset_url: Option<String>,
896}
897
898#[derive(Deserialize, Default)]
899struct GlAssets {
900 #[serde(default)]
901 links: Vec<GlLink>,
902}
903
904#[derive(Deserialize)]
905struct GlRelease {
906 tag_name: String,
907 name: Option<String>,
908 description: Option<String>,
909 created_at: Option<String>,
910 #[serde(default)]
911 upcoming_release: bool,
912 author: Option<GlUser>,
913 #[serde(default)]
914 assets: GlAssets,
915 #[serde(rename = "_links")]
916 links: Option<GlSelf>,
917}
918
919#[derive(Deserialize)]
920struct GlSelf {
921 #[serde(rename = "self")]
922 self_url: Option<String>,
923}
924
925#[derive(Deserialize)]
926struct GlProject {
927 path: String,
928 path_with_namespace: String,
929 description: Option<String>,
930 visibility: Option<String>,
931 default_branch: Option<String>,
932 web_url: Option<String>,
933 #[serde(default)]
934 archived: bool,
935 forked_from_project: Option<serde_json::Value>,
936}
937
938fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue {
939 ExtIssue {
940 number: i.iid,
941 title: i.title,
942 body: s(i.description),
943 closed: i.state != "opened",
944 not_planned: false,
945 merged: i.state == "merged",
946 author: i.author.and_then(|a| a.username).unwrap_or_default(),
947 labels: i.labels,
948 milestone: i.milestone.map(|m| m.title),
949 created_at: s(i.created_at),
950 url: s(i.web_url),
951 is_pr,
952 }
953}
954
955#[cfg(any(test, feature = "test-support"))]
956pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {
957 let raw: Vec<GlIssue> = from_json(json)?;
958 Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())
959}
960
961#[cfg(any(test, feature = "test-support"))]
962pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
963 let raw: Vec<GlRelease> = from_json(json)?;
964 Ok(raw.into_iter().map(gl_release).collect())
965}
966
967fn gl_release(r: GlRelease) -> ExtRelease {
968 ExtRelease {
969 id: r.tag_name.clone(),
970 title: r
971 .name
972 .filter(|n| !n.is_empty())
973 .unwrap_or_else(|| r.tag_name.clone()),
974 tag: r.tag_name,
975 body: s(r.description),
976 draft: r.upcoming_release,
977 prerelease: false,
978 author: r.author.and_then(|a| a.username).unwrap_or_default(),
979 created_at: s(r.created_at),
980 url: r.links.and_then(|l| l.self_url).unwrap_or_default(),
981 assets: r
982 .assets
983 .links
984 .into_iter()
985 .map(|l| ExtAsset {
986 id: l.id.to_string(),
987 name: l.name,
988 size: 0,
989 content_type: String::new(),
990 url: l
991 .direct_asset_url
992 .filter(|u| !u.is_empty())
993 .unwrap_or(l.url),
994 })
995 .collect(),
996 }
997}
998
999impl RemoteApi for GitLab {
1000 async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
1001 check_repo(owner, 1, 20)?;
1002 let enc = owner.replace('/', "%2F");
1003 let group: ApiResult<Vec<GlProject>> = self
1004 .http
1005 .pages(&format!(
1006 "{}/groups/{enc}/projects?include_subgroups=false&simple=false",
1007 self.base
1008 ))
1009 .await;
1010 let raw = match group {
1011 Ok(raw) => raw,
1012 Err(ApiError::NotFound(_)) => {
1013 self.http
1014 .pages(&format!("{}/users/{enc}/projects", self.base))
1015 .await?
1016 }
1017 Err(e) => return Err(e),
1018 };
1019 Ok(raw
1020 .into_iter()
1021 .map(|p| ExtRepo {
1022 name: p.path,
1023 full_name: p.path_with_namespace,
1024 description: s(p.description),
1025 private: p.visibility.as_deref() != Some("public"),
1026 fork: p.forked_from_project.is_some(),
1027 archived: p.archived,
1028 default_branch: s(p.default_branch),
1029 web_url: s(p.web_url),
1030 })
1031 .collect())
1032 }
1033
1034 async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
1035 let raw: Vec<GlLabel> = self
1036 .http
1037 .pages(&format!("{}/labels", self.project(repo)?))
1038 .await?;
1039 Ok(raw
1040 .into_iter()
1041 .map(|l| ExtLabel {
1042 name: l.name,
1043 color: s(l.color),
1044 description: s(l.description),
1045 })
1046 .collect())
1047 }
1048
1049 async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
1050 let raw: Vec<GlMilestone> = self
1051 .http
1052 .pages(&format!("{}/milestones", self.project(repo)?))
1053 .await?;
1054 Ok(raw
1055 .into_iter()
1056 .map(|m| ExtMilestone {
1057 id: m.id.to_string(),
1058 title: m.title,
1059 description: s(m.description),
1060 closed: m.state == "closed",
1061 due_on: m.due_date.as_deref().and_then(day),
1062 })
1063 .collect())
1064 }
1065
1066 async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
1067 let project = self.project(repo)?;
1068 let issues: Vec<GlIssue> = self
1069 .http
1070 .pages(&format!(
1071 "{project}/issues?state=all&order_by=created_at&sort=asc"
1072 ))
1073 .await?;
1074 let pulls: Vec<GlIssue> = self
1075 .http
1076 .pages(&format!(
1077 "{project}/merge_requests?state=all&order_by=created_at&sort=asc"
1078 ))
1079 .await?;
1080 let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| gl_issue(i, false)).collect();
1081 out.extend(pulls.into_iter().map(|i| gl_issue(i, true)));
1082 Ok(out)
1083 }
1084
1085 async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
1086 let kind = if issue.is_pr {
1087 "merge_requests"
1088 } else {
1089 "issues"
1090 };
1091 let raw: Vec<GlNote> = self
1092 .http
1093 .pages(&format!(
1094 "{}/{kind}/{}/notes?sort=asc&order_by=created_at",
1095 self.project(repo)?,
1096 issue.number
1097 ))
1098 .await?;
1099 Ok(raw
1100 .into_iter()
1101 .filter(|n| !n.system)
1102 .map(|n| ExtComment {
1103 id: n.id.to_string(),
1104 author: n.author.and_then(|a| a.username).unwrap_or_default(),
1105 body: s(n.body),
1106 created_at: s(n.created_at),
1107 url: format!("{}#note_{}", issue.url, n.id),
1108 })
1109 .collect())
1110 }
1111
1112 async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
1113 let raw: Vec<GlRelease> = self
1114 .http
1115 .pages(&format!("{}/releases", self.project(repo)?))
1116 .await?;
1117 Ok(raw.into_iter().map(gl_release).collect())
1118 }
1119
1120 async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
1121 if !asset.url.starts_with("https://") {
1122 return Err(ApiError::Http("unexpected asset address".into()));
1123 }
1124 self.http.download(&asset.url, max_bytes).await
1125 }
1126}
1127
1128// ---- Forgejo and Gitea ----
1129
1130/// A Forgejo or Gitea instance (Codeberg among them), over `/api/v1`.
1131pub struct Forgejo {
1132 http: Http,
1133 /// `https://host`, the web address the asset links must start with.
1134 origin: String,
1135 /// `https://host/api/v1`.
1136 base: String,
1137}
1138
1139impl Forgejo {
1140 /// `instance` is the instance's web address, e.g. `https://codeberg.org`.
1141 pub fn new(http: Http, instance: &str) -> Self {
1142 let origin = instance.trim_end_matches('/').to_owned();
1143 Forgejo {
1144 http,
1145 base: format!("{origin}/api/v1"),
1146 origin,
1147 }
1148 }
1149}
1150
1151#[derive(Deserialize)]
1152struct FjUser {
1153 login: Option<String>,
1154 username: Option<String>,
1155}
1156
1157fn fj_user(u: Option<FjUser>) -> String {
1158 u.and_then(|u| u.login.filter(|l| !l.is_empty()).or(u.username))
1159 .unwrap_or_default()
1160}
1161
1162#[derive(Deserialize)]
1163struct FjLabel {
1164 name: String,
1165 color: Option<String>,
1166 description: Option<String>,
1167}
1168
1169#[derive(Deserialize)]
1170struct FjMilestone {
1171 id: i64,
1172 title: String,
1173 description: Option<String>,
1174 state: String,
1175 due_on: Option<String>,
1176}
1177
1178#[derive(Deserialize)]
1179struct FjMilestoneRef {
1180 title: String,
1181}
1182
1183#[derive(Deserialize)]
1184struct FjIssue {
1185 number: i64,
1186 title: String,
1187 body: Option<String>,
1188 state: String,
1189 user: Option<FjUser>,
1190 #[serde(default)]
1191 labels: Vec<FjLabel>,
1192 milestone: Option<FjMilestoneRef>,
1193 created_at: Option<String>,
1194 html_url: Option<String>,
1195 /// Set on `/pulls` items.
1196 #[serde(default)]
1197 merged: bool,
1198}
1199
1200#[derive(Deserialize)]
1201struct FjComment {
1202 id: i64,
1203 body: Option<String>,
1204 user: Option<FjUser>,
1205 created_at: Option<String>,
1206 html_url: Option<String>,
1207}
1208
1209#[derive(Deserialize)]
1210struct FjAsset {
1211 id: i64,
1212 name: String,
1213 size: Option<u64>,
1214 browser_download_url: String,
1215}
1216
1217#[derive(Deserialize)]
1218struct FjRelease {
1219 id: i64,
1220 tag_name: String,
1221 name: Option<String>,
1222 body: Option<String>,
1223 #[serde(default)]
1224 draft: bool,
1225 #[serde(default)]
1226 prerelease: bool,
1227 author: Option<FjUser>,
1228 created_at: Option<String>,
1229 html_url: Option<String>,
1230 #[serde(default)]
1231 assets: Vec<FjAsset>,
1232}
1233
1234#[derive(Deserialize)]
1235struct FjRepo {
1236 name: String,
1237 full_name: String,
1238 description: Option<String>,
1239 #[serde(default)]
1240 private: bool,
1241 #[serde(default)]
1242 fork: bool,
1243 #[serde(default)]
1244 archived: bool,
1245 default_branch: Option<String>,
1246 html_url: Option<String>,
1247}
1248
1249fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue {
1250 ExtIssue {
1251 number: i.number,
1252 title: i.title,
1253 body: s(i.body),
1254 closed: i.state != "open",
1255 not_planned: false,
1256 merged: is_pr && i.merged,
1257 author: fj_user(i.user),
1258 labels: i.labels.into_iter().map(|l| l.name).collect(),
1259 milestone: i.milestone.map(|m| m.title),
1260 created_at: s(i.created_at),
1261 url: s(i.html_url),
1262 is_pr,
1263 }
1264}
1265
1266fn fj_release(r: FjRelease) -> ExtRelease {
1267 ExtRelease {
1268 id: r.id.to_string(),
1269 title: r
1270 .name
1271 .filter(|n| !n.is_empty())
1272 .unwrap_or_else(|| r.tag_name.clone()),
1273 tag: r.tag_name,
1274 body: s(r.body),
1275 draft: r.draft,
1276 prerelease: r.prerelease,
1277 author: fj_user(r.author),
1278 created_at: s(r.created_at),
1279 url: s(r.html_url),
1280 assets: r
1281 .assets
1282 .into_iter()
1283 .map(|a| ExtAsset {
1284 id: a.id.to_string(),
1285 name: a.name,
1286 size: a.size.unwrap_or(0),
1287 content_type: String::new(),
1288 url: a.browser_download_url,
1289 })
1290 .collect(),
1291 }
1292}
1293
1294impl RemoteApi for Forgejo {
1295 async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
1296 // An empty owner means "mine", which needs a token.
1297 let raw: Vec<FjRepo> = if owner.is_empty() {
1298 self.http
1299 .limit_pages(&format!("{}/user/repos", self.base))
1300 .await?
1301 } else {
1302 if !valid_segment(owner) {
1303 return Err(ApiError::NotFound("owner".into()));
1304 }
1305 let org: ApiResult<Vec<FjRepo>> = self
1306 .http
1307 .limit_pages(&format!("{}/orgs/{owner}/repos", self.base))
1308 .await;
1309 match org {
1310 Ok(raw) => raw,
1311 Err(ApiError::NotFound(_)) => {
1312 self.http
1313 .limit_pages(&format!("{}/users/{owner}/repos", self.base))
1314 .await?
1315 }
1316 Err(e) => return Err(e),
1317 }
1318 };
1319 Ok(raw
1320 .into_iter()
1321 .map(|r| ExtRepo {
1322 name: r.name,
1323 full_name: r.full_name,
1324 description: s(r.description),
1325 private: r.private,
1326 fork: r.fork,
1327 archived: r.archived,
1328 default_branch: s(r.default_branch),
1329 web_url: s(r.html_url),
1330 })
1331 .collect())
1332 }
1333
1334 async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
1335 check_repo(repo, 2, 2)?;
1336 let raw: Vec<FjLabel> = self
1337 .http
1338 .limit_pages(&format!("{}/repos/{repo}/labels", self.base))
1339 .await?;
1340 Ok(raw
1341 .into_iter()
1342 .map(|l| ExtLabel {
1343 name: l.name,
1344 color: format!("#{}", s(l.color).trim_start_matches('#')),
1345 description: s(l.description),
1346 })
1347 .collect())
1348 }
1349
1350 async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
1351 check_repo(repo, 2, 2)?;
1352 let raw: Vec<FjMilestone> = self
1353 .http
1354 .limit_pages(&format!("{}/repos/{repo}/milestones?state=all", self.base))
1355 .await?;
1356 Ok(raw
1357 .into_iter()
1358 .map(|m| ExtMilestone {
1359 id: m.id.to_string(),
1360 title: m.title,
1361 description: s(m.description),
1362 closed: m.state == "closed",
1363 due_on: m.due_on.as_deref().and_then(day),
1364 })
1365 .collect())
1366 }
1367
1368 async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
1369 check_repo(repo, 2, 2)?;
1370 let issues: Vec<FjIssue> = self
1371 .http
1372 .limit_pages(&format!(
1373 "{}/repos/{repo}/issues?type=issues&state=all&sort=oldest",
1374 self.base
1375 ))
1376 .await?;
1377 let pulls: Vec<FjIssue> = self
1378 .http
1379 .limit_pages(&format!(
1380 "{}/repos/{repo}/pulls?state=all&sort=oldest",
1381 self.base
1382 ))
1383 .await?;
1384 let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| fj_issue(i, false)).collect();
1385 out.extend(pulls.into_iter().map(|i| fj_issue(i, true)));
1386 Ok(out)
1387 }
1388
1389 async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
1390 check_repo(repo, 2, 2)?;
1391 let raw: Vec<FjComment> = self
1392 .http
1393 .limit_pages(&format!(
1394 "{}/repos/{repo}/issues/{}/comments",
1395 self.base, issue.number
1396 ))
1397 .await?;
1398 Ok(raw
1399 .into_iter()
1400 .map(|c| ExtComment {
1401 id: c.id.to_string(),
1402 author: fj_user(c.user),
1403 body: s(c.body),
1404 created_at: s(c.created_at),
1405 url: s(c.html_url),
1406 })
1407 .collect())
1408 }
1409
1410 async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
1411 check_repo(repo, 2, 2)?;
1412 let raw: Vec<FjRelease> = self
1413 .http
1414 .limit_pages(&format!("{}/repos/{repo}/releases", self.base))
1415 .await?;
1416 // The list embeds each release's assets, so `/releases/{id}/assets` is not needed.
1417 Ok(raw.into_iter().map(fj_release).collect())
1418 }
1419
1420 async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> {
1421 if !asset.url.starts_with(&format!("{}/", self.origin)) {
1422 return Err(ApiError::Http("unexpected asset address".into()));
1423 }
1424 self.http.download(&asset.url, max_bytes).await
1425 }
1426}
1427
1428#[cfg(test)]
1429mod tests {
1430 use super::*;
1431
1432 #[test]
1433 fn segments_reject_traversal_and_separators() {
1434 assert!(valid_segment("tahinli"));
1435 assert!(valid_segment("my-repo_1.rs"));
1436 assert!(!valid_segment(".."));
1437 assert!(!valid_segment("a/b"));
1438 assert!(!valid_segment("a?b"));
1439 assert!(!valid_segment(""));
1440 assert!(valid_path("tahinli/forge", 2, 2));
1441 assert!(!valid_path("tahinli", 2, 2));
1442 assert!(!valid_path("a/b/c", 2, 2));
1443 assert!(valid_path("grp/sub/proj", 2, 20));
1444 }
1445
1446 #[test]
1447 fn wait_text_reads_naturally() {
1448 assert_eq!(wait_text(45), "45 seconds");
1449 assert_eq!(wait_text(60), "1 minute");
1450 assert_eq!(wait_text(3188), "54 minutes");
1451 assert_eq!(wait_text(3600), "1 hour");
1452 assert_eq!(wait_text(3661), "1 hour 2 minutes");
1453 }
1454
1455 #[test]
1456 fn rate_limit_waits_follow_the_headers() {
1457 assert_eq!(rate_wait(Some("30"), None, None, 100), Some(30));
1458 assert_eq!(rate_wait(None, Some("0"), Some("160"), 100), Some(60));
1459 assert_eq!(rate_wait(None, Some("0"), Some("90"), 100), Some(1));
1460 assert_eq!(rate_wait(None, Some("12"), Some("160"), 100), None);
1461 assert_eq!(rate_wait(None, None, None, 100), None);
1462 assert_eq!(rate_wait(None, Some("0"), None, 100), None);
1463 }
1464
1465 #[test]
1466 fn github_issues_and_pulls_parse() {
1467 let json = br##"[
1468 {"number":1,"title":"Bug","body":"it breaks","state":"closed","state_reason":"not_planned",
1469 "user":{"login":"octocat"},"labels":[{"name":"bug","color":"d73a4a"}],
1470 "milestone":{"title":"v1"},"created_at":"2020-01-02T03:04:05Z",
1471 "html_url":"https://github.com/o/r/issues/1"},
1472 {"number":2,"title":"Add x","body":null,"state":"closed","user":{"login":"hubot"},
1473 "labels":[],"milestone":null,"created_at":"2020-02-02T00:00:00Z",
1474 "html_url":"https://github.com/o/r/pull/2","pull_request":{"merged_at":"2020-02-03T00:00:00Z"}}
1475 ]"##;
1476 let items = parse_github_issues(json).unwrap();
1477 assert_eq!(items.len(), 2);
1478 assert!(items[0].closed && items[0].not_planned && !items[0].is_pr);
1479 assert_eq!(items[0].labels, vec!["bug"]);
1480 assert_eq!(items[0].milestone.as_deref(), Some("v1"));
1481 assert!(items[1].is_pr && items[1].merged);
1482 assert_eq!(items[1].body, "");
1483 assert_eq!(items[1].author, "hubot");
1484 }
1485
1486 #[test]
1487 fn github_labels_get_a_hash() {
1488 let labels =
1489 parse_github_labels(br#"[{"name":"bug","color":"d73a4a","description":null}]"#)
1490 .unwrap();
1491 assert_eq!(labels[0].color, "#d73a4a");
1492 assert_eq!(labels[0].description, "");
1493 }
1494
1495 #[test]
1496 fn github_releases_carry_assets() {
1497 let json = br#"[{"id":7,"tag_name":"v1.0","name":"","body":"notes","draft":false,
1498 "prerelease":true,"author":{"login":"octocat"},"created_at":"2021-01-01T00:00:00Z",
1499 "html_url":"https://github.com/o/r/releases/tag/v1.0",
1500 "assets":[{"id":9,"name":"app.tar.gz","size":12,"content_type":"application/gzip",
1501 "url":"https://api.github.com/repos/o/r/releases/assets/9"}]}]"#;
1502 let rel = parse_github_releases(json).unwrap();
1503 assert_eq!(rel[0].title, "v1.0", "a blank name falls back to the tag");
1504 assert!(rel[0].prerelease);
1505 assert_eq!(rel[0].assets[0].name, "app.tar.gz");
1506 assert_eq!(rel[0].assets[0].size, 12);
1507 }
1508
1509 #[test]
1510 fn gitlab_states_map() {
1511 let json = br#"[
1512 {"iid":3,"title":"MR","description":"d","state":"merged","author":{"username":"tahinli"},
1513 "labels":["x"],"milestone":null,"created_at":"2022-01-01T00:00:00Z","web_url":"https://gl/x/-/merge_requests/3"},
1514 {"iid":4,"title":"open","description":null,"state":"opened","author":null,"labels":[],
1515 "created_at":null,"web_url":null}]"#;
1516 let items = parse_gitlab_issues(json, true).unwrap();
1517 assert!(items[0].closed && items[0].merged && items[0].is_pr);
1518 assert!(!items[1].closed);
1519 assert_eq!(items[1].author, "");
1520 }
1521
1522 #[test]
1523 fn gitlab_release_links_become_assets() {
1524 let json = br#"[{"tag_name":"v2","name":"Two","description":"n","created_at":"2022-01-01T00:00:00Z",
1525 "assets":{"links":[{"id":1,"name":"bin","url":"https://x/a","direct_asset_url":"https://x/direct"}]}}]"#;
1526 let rel = parse_gitlab_releases(json).unwrap();
1527 assert_eq!(rel[0].assets[0].url, "https://x/direct");
1528 assert_eq!(rel[0].tag, "v2");
1529 }
1530
1531 #[test]
1532 fn day_keeps_only_a_valid_date_prefix() {
1533 assert_eq!(day("2020-05-06T00:00:00Z").as_deref(), Some("2020-05-06"));
1534 assert_eq!(day("garbage!!!").as_deref(), None);
1535 assert_eq!(day("x").as_deref(), None);
1536 }
1537}