github.rs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. use anyhow::Context;
  2. use async_trait::async_trait;
  3. use chrono::{DateTime, FixedOffset, Utc};
  4. use futures::{future::BoxFuture, FutureExt};
  5. use hyper::header::HeaderValue;
  6. use once_cell::sync::OnceCell;
  7. use reqwest::header::{AUTHORIZATION, USER_AGENT};
  8. use reqwest::{Client, Request, RequestBuilder, Response, StatusCode};
  9. use std::convert::TryInto;
  10. use std::{
  11. fmt,
  12. time::{Duration, SystemTime},
  13. };
  14. use tracing as log;
  15. pub mod graphql;
  16. #[derive(Debug, PartialEq, Eq, serde::Deserialize)]
  17. pub struct User {
  18. pub login: String,
  19. pub id: Option<i64>,
  20. }
  21. impl GithubClient {
  22. async fn _send_req(&self, req: RequestBuilder) -> anyhow::Result<(Response, String)> {
  23. const MAX_ATTEMPTS: usize = 2;
  24. log::debug!("_send_req with {:?}", req);
  25. let req_dbg = format!("{:?}", req);
  26. let req = req
  27. .build()
  28. .with_context(|| format!("building reqwest {}", req_dbg))?;
  29. let mut resp = self.client.execute(req.try_clone().unwrap()).await?;
  30. if let Some(sleep) = Self::needs_retry(&resp).await {
  31. resp = self.retry(req, sleep, MAX_ATTEMPTS).await?;
  32. }
  33. resp.error_for_status_ref()?;
  34. Ok((resp, req_dbg))
  35. }
  36. async fn needs_retry(resp: &Response) -> Option<Duration> {
  37. const REMAINING: &str = "X-RateLimit-Remaining";
  38. const RESET: &str = "X-RateLimit-Reset";
  39. if resp.status().is_success() {
  40. return None;
  41. }
  42. let headers = resp.headers();
  43. if !(headers.contains_key(REMAINING) && headers.contains_key(RESET)) {
  44. return None;
  45. }
  46. // Weird github api behavior. It asks us to retry but also has a remaining count above 1
  47. // Try again immediately and hope for the best...
  48. if headers[REMAINING] != "0" {
  49. return Some(Duration::from_secs(0));
  50. }
  51. let reset_time = headers[RESET].to_str().unwrap().parse::<u64>().unwrap();
  52. Some(Duration::from_secs(Self::calc_sleep(reset_time) + 10))
  53. }
  54. fn calc_sleep(reset_time: u64) -> u64 {
  55. let epoch_time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs();
  56. reset_time.saturating_sub(epoch_time)
  57. }
  58. fn retry(
  59. &self,
  60. req: Request,
  61. sleep: Duration,
  62. remaining_attempts: usize,
  63. ) -> BoxFuture<Result<Response, reqwest::Error>> {
  64. #[derive(Debug, serde::Deserialize)]
  65. struct RateLimit {
  66. #[allow(unused)]
  67. pub limit: u64,
  68. pub remaining: u64,
  69. pub reset: u64,
  70. }
  71. #[derive(Debug, serde::Deserialize)]
  72. struct RateLimitResponse {
  73. pub resources: Resources,
  74. }
  75. #[derive(Debug, serde::Deserialize)]
  76. struct Resources {
  77. pub core: RateLimit,
  78. pub search: RateLimit,
  79. #[allow(unused)]
  80. pub graphql: RateLimit,
  81. #[allow(unused)]
  82. pub source_import: RateLimit,
  83. }
  84. log::warn!(
  85. "Retrying after {} seconds, remaining attepts {}",
  86. sleep.as_secs(),
  87. remaining_attempts,
  88. );
  89. async move {
  90. tokio::time::sleep(sleep).await;
  91. // check rate limit
  92. let rate_resp = self
  93. .client
  94. .execute(
  95. self.client
  96. .get("https://api.github.com/rate_limit")
  97. .configure(self)
  98. .build()
  99. .unwrap(),
  100. )
  101. .await?;
  102. let rate_limit_response = rate_resp.json::<RateLimitResponse>().await?;
  103. // Check url for search path because github has different rate limits for the search api
  104. let rate_limit = if req
  105. .url()
  106. .path_segments()
  107. .map(|mut segments| matches!(segments.next(), Some("search")))
  108. .unwrap_or(false)
  109. {
  110. rate_limit_response.resources.search
  111. } else {
  112. rate_limit_response.resources.core
  113. };
  114. // If we still don't have any more remaining attempts, try sleeping for the remaining
  115. // period of time
  116. if rate_limit.remaining == 0 {
  117. let sleep = Self::calc_sleep(rate_limit.reset);
  118. if sleep > 0 {
  119. tokio::time::sleep(Duration::from_secs(sleep)).await;
  120. }
  121. }
  122. let resp = self.client.execute(req.try_clone().unwrap()).await?;
  123. if let Some(sleep) = Self::needs_retry(&resp).await {
  124. if remaining_attempts > 0 {
  125. return self.retry(req, sleep, remaining_attempts - 1).await;
  126. }
  127. }
  128. Ok(resp)
  129. }
  130. .boxed()
  131. }
  132. async fn send_req(&self, req: RequestBuilder) -> anyhow::Result<Vec<u8>> {
  133. let (mut resp, req_dbg) = self._send_req(req).await?;
  134. let mut body = Vec::new();
  135. while let Some(chunk) = resp.chunk().await.transpose() {
  136. let chunk = chunk
  137. .context("reading stream failed")
  138. .map_err(anyhow::Error::from)
  139. .context(req_dbg.clone())?;
  140. body.extend_from_slice(&chunk);
  141. }
  142. Ok(body)
  143. }
  144. pub async fn json<T>(&self, req: RequestBuilder) -> anyhow::Result<T>
  145. where
  146. T: serde::de::DeserializeOwned,
  147. {
  148. let (resp, req_dbg) = self._send_req(req).await?;
  149. Ok(resp.json().await.context(req_dbg)?)
  150. }
  151. }
  152. impl User {
  153. pub async fn current(client: &GithubClient) -> anyhow::Result<Self> {
  154. client.json(client.get("https://api.github.com/user")).await
  155. }
  156. pub async fn is_team_member<'a>(&'a self, client: &'a GithubClient) -> anyhow::Result<bool> {
  157. log::trace!("Getting team membership for {:?}", self.login);
  158. let permission = crate::team_data::teams(client).await?;
  159. let map = permission.teams;
  160. let is_triager = map
  161. .get("wg-triage")
  162. .map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
  163. let is_pri_member = map
  164. .get("wg-prioritization")
  165. .map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
  166. let is_async_member = map
  167. .get("wg-async")
  168. .map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
  169. let in_all = map["all"].members.iter().any(|g| g.github == self.login);
  170. log::trace!(
  171. "{:?} is all?={:?}, triager?={:?}, prioritizer?={:?}, async?={:?}",
  172. self.login,
  173. in_all,
  174. is_triager,
  175. is_pri_member,
  176. is_async_member,
  177. );
  178. Ok(in_all || is_triager || is_pri_member || is_async_member)
  179. }
  180. // Returns the ID of the given user, if the user is in the `all` team.
  181. pub async fn get_id<'a>(&'a self, client: &'a GithubClient) -> anyhow::Result<Option<usize>> {
  182. let permission = crate::team_data::teams(client).await?;
  183. let map = permission.teams;
  184. Ok(map["all"]
  185. .members
  186. .iter()
  187. .find(|g| g.github == self.login)
  188. .map(|u| u.github_id))
  189. }
  190. }
  191. pub async fn get_team(
  192. client: &GithubClient,
  193. team: &str,
  194. ) -> anyhow::Result<Option<rust_team_data::v1::Team>> {
  195. let permission = crate::team_data::teams(client).await?;
  196. let mut map = permission.teams;
  197. Ok(map.swap_remove(team))
  198. }
  199. #[derive(PartialEq, Eq, Debug, Clone, serde::Deserialize)]
  200. pub struct Label {
  201. pub name: String,
  202. }
  203. #[derive(Debug, serde::Deserialize)]
  204. pub struct PullRequestDetails {
  205. // none for now
  206. }
  207. #[derive(Debug, serde::Deserialize)]
  208. pub struct Issue {
  209. pub number: u64,
  210. #[serde(deserialize_with = "opt_string")]
  211. pub body: String,
  212. created_at: chrono::DateTime<Utc>,
  213. pub updated_at: chrono::DateTime<Utc>,
  214. #[serde(default)]
  215. pub merge_commit_sha: Option<String>,
  216. pub title: String,
  217. pub html_url: String,
  218. pub user: User,
  219. pub labels: Vec<Label>,
  220. pub assignees: Vec<User>,
  221. pub pull_request: Option<PullRequestDetails>,
  222. #[serde(default)]
  223. pub merged: bool,
  224. // API URL
  225. comments_url: String,
  226. #[serde(skip)]
  227. repository: OnceCell<IssueRepository>,
  228. #[serde(default)]
  229. base: Option<CommitBase>,
  230. #[serde(default)]
  231. head: Option<CommitBase>,
  232. }
  233. /// Contains only the parts of `Issue` that are needed for turning the issue title into a Zulip
  234. /// topic.
  235. #[derive(Clone, Debug, PartialEq, Eq)]
  236. pub struct ZulipGitHubReference {
  237. pub number: u64,
  238. pub title: String,
  239. pub repository: IssueRepository,
  240. }
  241. impl ZulipGitHubReference {
  242. pub fn zulip_topic_reference(&self) -> String {
  243. let repo = &self.repository;
  244. if repo.organization == "rust-lang" {
  245. if repo.repository == "rust" {
  246. format!("#{}", self.number)
  247. } else {
  248. format!("{}#{}", repo.repository, self.number)
  249. }
  250. } else {
  251. format!("{}/{}#{}", repo.organization, repo.repository, self.number)
  252. }
  253. }
  254. }
  255. #[derive(Debug, serde::Deserialize)]
  256. pub struct Comment {
  257. #[serde(deserialize_with = "opt_string")]
  258. pub body: String,
  259. pub html_url: String,
  260. pub user: User,
  261. #[serde(alias = "submitted_at")] // for pull request reviews
  262. pub updated_at: chrono::DateTime<Utc>,
  263. #[serde(default, rename = "state")]
  264. pub pr_review_state: Option<PullRequestReviewState>,
  265. }
  266. #[derive(Debug, serde::Deserialize, Eq, PartialEq)]
  267. #[serde(rename_all = "lowercase")]
  268. pub enum PullRequestReviewState {
  269. Approved,
  270. ChangesRequested,
  271. Commented,
  272. Dismissed,
  273. Pending,
  274. }
  275. fn opt_string<'de, D>(deserializer: D) -> Result<String, D::Error>
  276. where
  277. D: serde::de::Deserializer<'de>,
  278. {
  279. use serde::de::Deserialize;
  280. match <Option<String>>::deserialize(deserializer) {
  281. Ok(v) => Ok(v.unwrap_or_default()),
  282. Err(e) => Err(e),
  283. }
  284. }
  285. #[derive(Debug)]
  286. pub enum AssignmentError {
  287. InvalidAssignee,
  288. Http(anyhow::Error),
  289. }
  290. #[derive(Debug)]
  291. pub enum Selection<'a, T: ?Sized> {
  292. All,
  293. One(&'a T),
  294. Except(&'a T),
  295. }
  296. impl fmt::Display for AssignmentError {
  297. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  298. match self {
  299. AssignmentError::InvalidAssignee => write!(f, "invalid assignee"),
  300. AssignmentError::Http(e) => write!(f, "cannot assign: {}", e),
  301. }
  302. }
  303. }
  304. impl std::error::Error for AssignmentError {}
  305. #[derive(Debug, Clone, PartialEq, Eq)]
  306. pub struct IssueRepository {
  307. pub organization: String,
  308. pub repository: String,
  309. }
  310. impl fmt::Display for IssueRepository {
  311. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  312. write!(f, "{}/{}", self.organization, self.repository)
  313. }
  314. }
  315. impl IssueRepository {
  316. fn url(&self) -> String {
  317. format!(
  318. "https://api.github.com/repos/{}/{}",
  319. self.organization, self.repository
  320. )
  321. }
  322. async fn has_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<bool> {
  323. #[allow(clippy::redundant_pattern_matching)]
  324. let url = format!("{}/labels/{}", self.url(), label);
  325. match client._send_req(client.get(&url)).await {
  326. Ok((_, _)) => Ok(true),
  327. Err(e) => {
  328. if e.downcast_ref::<reqwest::Error>().map_or(false, |e| e.status() == Some(StatusCode::NOT_FOUND)) {
  329. Ok(false)
  330. } else {
  331. Err(e)
  332. }
  333. }
  334. }
  335. }
  336. }
  337. #[derive(Debug)]
  338. pub(crate) struct UnknownLabels {
  339. labels: Vec<String>,
  340. }
  341. // NOTE: This is used to post the Github comment; make sure it's valid markdown.
  342. impl fmt::Display for UnknownLabels {
  343. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  344. write!(f, "Unknown labels: {}", &self.labels.join(", "))
  345. }
  346. }
  347. impl std::error::Error for UnknownLabels {}
  348. impl Issue {
  349. pub fn to_zulip_github_reference(&self) -> ZulipGitHubReference {
  350. ZulipGitHubReference {
  351. number: self.number,
  352. title: self.title.clone(),
  353. repository: self.repository().clone(),
  354. }
  355. }
  356. pub fn repository(&self) -> &IssueRepository {
  357. self.repository.get_or_init(|| {
  358. // https://api.github.com/repos/rust-lang/rust/issues/69257/comments
  359. log::trace!("get repository for {}", self.comments_url);
  360. let url = url::Url::parse(&self.comments_url).unwrap();
  361. let mut segments = url.path_segments().unwrap();
  362. let _comments = segments.next_back().unwrap();
  363. let _number = segments.next_back().unwrap();
  364. let _issues_or_prs = segments.next_back().unwrap();
  365. let repository = segments.next_back().unwrap();
  366. let organization = segments.next_back().unwrap();
  367. IssueRepository {
  368. organization: organization.into(),
  369. repository: repository.into(),
  370. }
  371. })
  372. }
  373. pub fn global_id(&self) -> String {
  374. format!("{}#{}", self.repository(), self.number)
  375. }
  376. pub fn is_pr(&self) -> bool {
  377. self.pull_request.is_some()
  378. }
  379. pub async fn get_comment(&self, client: &GithubClient, id: usize) -> anyhow::Result<Comment> {
  380. let comment_url = format!("{}/issues/comments/{}", self.repository().url(), id);
  381. let comment = client.json(client.get(&comment_url)).await?;
  382. Ok(comment)
  383. }
  384. pub async fn edit_body(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  385. let edit_url = format!("{}/issues/{}", self.repository().url(), self.number);
  386. #[derive(serde::Serialize)]
  387. struct ChangedIssue<'a> {
  388. body: &'a str,
  389. }
  390. client
  391. ._send_req(client.patch(&edit_url).json(&ChangedIssue { body }))
  392. .await
  393. .context("failed to edit issue body")?;
  394. Ok(())
  395. }
  396. pub async fn edit_comment(
  397. &self,
  398. client: &GithubClient,
  399. id: usize,
  400. new_body: &str,
  401. ) -> anyhow::Result<()> {
  402. let comment_url = format!("{}/issues/comments/{}", self.repository().url(), id);
  403. #[derive(serde::Serialize)]
  404. struct NewComment<'a> {
  405. body: &'a str,
  406. }
  407. client
  408. ._send_req(
  409. client
  410. .patch(&comment_url)
  411. .json(&NewComment { body: new_body }),
  412. )
  413. .await
  414. .context("failed to edit comment")?;
  415. Ok(())
  416. }
  417. pub async fn post_comment(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  418. #[derive(serde::Serialize)]
  419. struct PostComment<'a> {
  420. body: &'a str,
  421. }
  422. client
  423. ._send_req(client.post(&self.comments_url).json(&PostComment { body }))
  424. .await
  425. .context("failed to post comment")?;
  426. Ok(())
  427. }
  428. pub async fn remove_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<()> {
  429. log::info!("remove_label from {}: {:?}", self.global_id(), label);
  430. // DELETE /repos/:owner/:repo/issues/:number/labels/{name}
  431. let url = format!(
  432. "{repo_url}/issues/{number}/labels/{name}",
  433. repo_url = self.repository().url(),
  434. number = self.number,
  435. name = label,
  436. );
  437. if !self.labels().iter().any(|l| l.name == label) {
  438. log::info!(
  439. "remove_label from {}: {:?} already not present, skipping",
  440. self.global_id(),
  441. label
  442. );
  443. return Ok(());
  444. }
  445. client
  446. ._send_req(client.delete(&url))
  447. .await
  448. .context("failed to delete label")?;
  449. Ok(())
  450. }
  451. pub async fn add_labels(
  452. &self,
  453. client: &GithubClient,
  454. labels: Vec<Label>,
  455. ) -> anyhow::Result<()> {
  456. log::info!("add_labels: {} +{:?}", self.global_id(), labels);
  457. // POST /repos/:owner/:repo/issues/:number/labels
  458. // repo_url = https://api.github.com/repos/Codertocat/Hello-World
  459. let url = format!(
  460. "{repo_url}/issues/{number}/labels",
  461. repo_url = self.repository().url(),
  462. number = self.number
  463. );
  464. // Don't try to add labels already present on this issue.
  465. let labels = labels
  466. .into_iter()
  467. .filter(|l| !self.labels().contains(&l))
  468. .map(|l| l.name)
  469. .collect::<Vec<_>>();
  470. log::info!("add_labels: {} filtered to {:?}", self.global_id(), labels);
  471. if labels.is_empty() {
  472. return Ok(());
  473. }
  474. let mut unknown_labels = vec![];
  475. let mut known_labels = vec![];
  476. for label in labels {
  477. if !self.repository().has_label(client, &label).await? {
  478. unknown_labels.push(label);
  479. } else {
  480. known_labels.push(label);
  481. }
  482. }
  483. if !unknown_labels.is_empty() {
  484. return Err(UnknownLabels { labels: unknown_labels }.into());
  485. }
  486. #[derive(serde::Serialize)]
  487. struct LabelsReq {
  488. labels: Vec<String>,
  489. }
  490. client
  491. ._send_req(client.post(&url).json(&LabelsReq { labels: known_labels }))
  492. .await
  493. .context("failed to add labels")?;
  494. Ok(())
  495. }
  496. pub fn labels(&self) -> &[Label] {
  497. &self.labels
  498. }
  499. pub fn contain_assignee(&self, user: &str) -> bool {
  500. self.assignees.iter().any(|a| a.login == user)
  501. }
  502. pub async fn remove_assignees(
  503. &self,
  504. client: &GithubClient,
  505. selection: Selection<'_, str>,
  506. ) -> Result<(), AssignmentError> {
  507. log::info!("remove {:?} assignees for {}", selection, self.global_id());
  508. let url = format!(
  509. "{repo_url}/issues/{number}/assignees",
  510. repo_url = self.repository().url(),
  511. number = self.number
  512. );
  513. let assignees = match selection {
  514. Selection::All => self
  515. .assignees
  516. .iter()
  517. .map(|u| u.login.as_str())
  518. .collect::<Vec<_>>(),
  519. Selection::One(user) => vec![user],
  520. Selection::Except(user) => self
  521. .assignees
  522. .iter()
  523. .map(|u| u.login.as_str())
  524. .filter(|&u| u != user)
  525. .collect::<Vec<_>>(),
  526. };
  527. #[derive(serde::Serialize)]
  528. struct AssigneeReq<'a> {
  529. assignees: &'a [&'a str],
  530. }
  531. client
  532. ._send_req(client.delete(&url).json(&AssigneeReq {
  533. assignees: &assignees[..],
  534. }))
  535. .await
  536. .map_err(AssignmentError::Http)?;
  537. Ok(())
  538. }
  539. pub async fn add_assignee(
  540. &self,
  541. client: &GithubClient,
  542. user: &str,
  543. ) -> Result<(), AssignmentError> {
  544. log::info!("add_assignee {} for {}", user, self.global_id());
  545. let url = format!(
  546. "{repo_url}/issues/{number}/assignees",
  547. repo_url = self.repository().url(),
  548. number = self.number
  549. );
  550. #[derive(serde::Serialize)]
  551. struct AssigneeReq<'a> {
  552. assignees: &'a [&'a str],
  553. }
  554. let result: Issue = client
  555. .json(client.post(&url).json(&AssigneeReq { assignees: &[user] }))
  556. .await
  557. .map_err(AssignmentError::Http)?;
  558. // Invalid assignees are silently ignored. We can just check if the user is now
  559. // contained in the assignees list.
  560. let success = result.assignees.iter().any(|u| u.login.as_str() == user);
  561. if success {
  562. Ok(())
  563. } else {
  564. Err(AssignmentError::InvalidAssignee)
  565. }
  566. }
  567. pub async fn set_assignee(
  568. &self,
  569. client: &GithubClient,
  570. user: &str,
  571. ) -> Result<(), AssignmentError> {
  572. log::info!("set_assignee for {} to {}", self.global_id(), user);
  573. self.add_assignee(client, user).await?;
  574. self.remove_assignees(client, Selection::Except(user))
  575. .await?;
  576. Ok(())
  577. }
  578. pub async fn set_milestone(&self, client: &GithubClient, title: &str) -> anyhow::Result<()> {
  579. log::trace!(
  580. "Setting milestone for rust-lang/rust#{} to {}",
  581. self.number,
  582. title
  583. );
  584. let create_url = format!("{}/milestones", self.repository().url());
  585. let resp = client
  586. .send_req(
  587. client
  588. .post(&create_url)
  589. .body(serde_json::to_vec(&MilestoneCreateBody { title }).unwrap()),
  590. )
  591. .await;
  592. // Explicitly do *not* try to return Err(...) if this fails -- that's
  593. // fine, it just means the milestone was already created.
  594. log::trace!("Created milestone: {:?}", resp);
  595. let list_url = format!("{}/milestones", self.repository().url());
  596. let milestone_list: Vec<Milestone> = client.json(client.get(&list_url)).await?;
  597. let milestone_no = if let Some(milestone) = milestone_list.iter().find(|v| v.title == title)
  598. {
  599. milestone.number
  600. } else {
  601. anyhow::bail!(
  602. "Despite just creating milestone {} on {}, it does not exist?",
  603. title,
  604. self.repository()
  605. )
  606. };
  607. #[derive(serde::Serialize)]
  608. struct SetMilestone {
  609. milestone: u64,
  610. }
  611. let url = format!("{}/issues/{}", self.repository().url(), self.number);
  612. client
  613. ._send_req(client.patch(&url).json(&SetMilestone {
  614. milestone: milestone_no,
  615. }))
  616. .await
  617. .context("failed to set milestone")?;
  618. Ok(())
  619. }
  620. pub async fn close(&self, client: &GithubClient) -> anyhow::Result<()> {
  621. let edit_url = format!("{}/issues/{}", self.repository().url(), self.number);
  622. #[derive(serde::Serialize)]
  623. struct CloseIssue<'a> {
  624. state: &'a str,
  625. }
  626. client
  627. ._send_req(
  628. client
  629. .patch(&edit_url)
  630. .json(&CloseIssue { state: "closed" }),
  631. )
  632. .await
  633. .context("failed to close issue")?;
  634. Ok(())
  635. }
  636. /// Returns the diff in this event, for Open and Synchronize events for now.
  637. pub async fn diff(&self, client: &GithubClient) -> anyhow::Result<Option<String>> {
  638. let (before, after) = if let (Some(base), Some(head)) = (&self.base, &self.head) {
  639. (base.sha.clone(), head.sha.clone())
  640. } else {
  641. return Ok(None);
  642. };
  643. let mut req = client.get(&format!(
  644. "{}/compare/{}...{}",
  645. self.repository().url(),
  646. before,
  647. after
  648. ));
  649. req = req.header("Accept", "application/vnd.github.v3.diff");
  650. let diff = client.send_req(req).await?;
  651. Ok(Some(String::from(String::from_utf8_lossy(&diff))))
  652. }
  653. }
  654. #[derive(serde::Serialize)]
  655. struct MilestoneCreateBody<'a> {
  656. title: &'a str,
  657. }
  658. #[derive(Debug, serde::Deserialize)]
  659. pub struct Milestone {
  660. number: u64,
  661. title: String,
  662. }
  663. #[derive(Debug, serde::Deserialize)]
  664. pub struct ChangeInner {
  665. pub from: String,
  666. }
  667. #[derive(Debug, serde::Deserialize)]
  668. pub struct Changes {
  669. pub title: Option<ChangeInner>,
  670. pub body: Option<ChangeInner>,
  671. }
  672. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  673. #[serde(rename_all = "lowercase")]
  674. pub enum PullRequestReviewAction {
  675. Submitted,
  676. Edited,
  677. Dismissed,
  678. }
  679. #[derive(Debug, serde::Deserialize)]
  680. pub struct PullRequestReviewEvent {
  681. pub action: PullRequestReviewAction,
  682. pub pull_request: Issue,
  683. pub review: Comment,
  684. pub changes: Option<Changes>,
  685. pub repository: Repository,
  686. }
  687. #[derive(Debug, serde::Deserialize)]
  688. pub struct PullRequestReviewComment {
  689. pub action: IssueCommentAction,
  690. pub changes: Option<Changes>,
  691. #[serde(rename = "pull_request")]
  692. pub issue: Issue,
  693. pub comment: Comment,
  694. pub repository: Repository,
  695. }
  696. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  697. #[serde(rename_all = "lowercase")]
  698. pub enum IssueCommentAction {
  699. Created,
  700. Edited,
  701. Deleted,
  702. }
  703. #[derive(Debug, serde::Deserialize)]
  704. pub struct IssueCommentEvent {
  705. pub action: IssueCommentAction,
  706. pub changes: Option<Changes>,
  707. pub issue: Issue,
  708. pub comment: Comment,
  709. pub repository: Repository,
  710. }
  711. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  712. #[serde(rename_all = "snake_case")]
  713. pub enum IssuesAction {
  714. Opened,
  715. Edited,
  716. Deleted,
  717. Transferred,
  718. Pinned,
  719. Unpinned,
  720. Closed,
  721. Reopened,
  722. Assigned,
  723. Unassigned,
  724. Labeled,
  725. Unlabeled,
  726. Locked,
  727. Unlocked,
  728. Milestoned,
  729. Demilestoned,
  730. ReviewRequested,
  731. ReviewRequestRemoved,
  732. ReadyForReview,
  733. Synchronize,
  734. ConvertedToDraft,
  735. }
  736. #[derive(Debug, serde::Deserialize)]
  737. pub struct IssuesEvent {
  738. pub action: IssuesAction,
  739. #[serde(alias = "pull_request")]
  740. pub issue: Issue,
  741. pub changes: Option<Changes>,
  742. pub repository: Repository,
  743. /// Some if action is IssuesAction::Labeled, for example
  744. pub label: Option<Label>,
  745. }
  746. #[derive(Debug, serde::Deserialize)]
  747. struct PullRequestEventFields {}
  748. #[derive(Default, Clone, Debug, serde::Deserialize)]
  749. pub struct CommitBase {
  750. sha: String,
  751. }
  752. pub fn files_changed(diff: &str) -> Vec<&str> {
  753. let mut files = Vec::new();
  754. for line in diff.lines() {
  755. // mostly copied from highfive
  756. if line.starts_with("diff --git ") {
  757. files.push(
  758. line[line.find(" b/").unwrap()..]
  759. .strip_prefix(" b/")
  760. .unwrap(),
  761. );
  762. }
  763. }
  764. files
  765. }
  766. #[derive(Debug, serde::Deserialize)]
  767. pub struct IssueSearchResult {
  768. pub total_count: usize,
  769. pub incomplete_results: bool,
  770. pub items: Vec<Issue>,
  771. }
  772. #[derive(Debug, serde::Deserialize)]
  773. pub struct Repository {
  774. pub full_name: String,
  775. }
  776. #[derive(Copy, Clone)]
  777. struct Ordering<'a> {
  778. pub sort: &'a str,
  779. pub direction: &'a str,
  780. pub per_page: &'a str,
  781. pub page: usize,
  782. }
  783. impl Repository {
  784. const GITHUB_API_URL: &'static str = "https://api.github.com";
  785. const GITHUB_GRAPHQL_API_URL: &'static str = "https://api.github.com/graphql";
  786. pub fn owner(&self) -> &str {
  787. self.full_name.split_once('/').unwrap().0
  788. }
  789. pub fn name(&self) -> &str {
  790. self.full_name.split_once('/').unwrap().1
  791. }
  792. pub async fn get_issues<'a>(
  793. &self,
  794. client: &GithubClient,
  795. query: &Query<'a>,
  796. ) -> anyhow::Result<Vec<Issue>> {
  797. let Query {
  798. filters,
  799. include_labels,
  800. exclude_labels,
  801. } = query;
  802. let mut ordering = Ordering {
  803. sort: "created",
  804. direction: "asc",
  805. per_page: "100",
  806. page: 1,
  807. };
  808. let filters: Vec<_> = filters
  809. .clone()
  810. .into_iter()
  811. .filter(|(key, val)| {
  812. match *key {
  813. "sort" => ordering.sort = val,
  814. "direction" => ordering.direction = val,
  815. "per_page" => ordering.per_page = val,
  816. _ => return true,
  817. };
  818. false
  819. })
  820. .collect();
  821. // `is: pull-request` indicates the query to retrieve PRs only
  822. let is_pr = filters
  823. .iter()
  824. .any(|&(key, value)| key == "is" && value == "pull-request");
  825. // There are some cases that can only be handled by the search API:
  826. // 1. When using negating label filters (exclude_labels)
  827. // 2. When there's a key parameter key=no
  828. // 3. When the query is to retrieve PRs only and there are label filters
  829. //
  830. // Check https://docs.github.com/en/rest/reference/search#search-issues-and-pull-requests
  831. // for more information
  832. let use_search_api = !exclude_labels.is_empty()
  833. || filters.iter().any(|&(key, _)| key == "no")
  834. || is_pr && !include_labels.is_empty();
  835. // If there are more than `per_page` of issues, we need to paginate
  836. let mut issues = vec![];
  837. loop {
  838. let url = if use_search_api {
  839. self.build_search_issues_url(&filters, include_labels, exclude_labels, ordering)
  840. } else if is_pr {
  841. self.build_pulls_url(&filters, include_labels, ordering)
  842. } else {
  843. self.build_issues_url(&filters, include_labels, ordering)
  844. };
  845. let result = client.get(&url);
  846. if use_search_api {
  847. let result = client
  848. .json::<IssueSearchResult>(result)
  849. .await
  850. .with_context(|| format!("failed to list issues from {}", url))?;
  851. issues.extend(result.items);
  852. if issues.len() < result.total_count {
  853. ordering.page += 1;
  854. continue;
  855. }
  856. } else {
  857. // FIXME: paginate with non-search
  858. issues = client
  859. .json(result)
  860. .await
  861. .with_context(|| format!("failed to list issues from {}", url))?
  862. }
  863. break;
  864. }
  865. Ok(issues)
  866. }
  867. fn build_issues_url(
  868. &self,
  869. filters: &Vec<(&str, &str)>,
  870. include_labels: &Vec<&str>,
  871. ordering: Ordering<'_>,
  872. ) -> String {
  873. self.build_endpoint_url("issues", filters, include_labels, ordering)
  874. }
  875. fn build_pulls_url(
  876. &self,
  877. filters: &Vec<(&str, &str)>,
  878. include_labels: &Vec<&str>,
  879. ordering: Ordering<'_>,
  880. ) -> String {
  881. self.build_endpoint_url("pulls", filters, include_labels, ordering)
  882. }
  883. fn build_endpoint_url(
  884. &self,
  885. endpoint: &str,
  886. filters: &Vec<(&str, &str)>,
  887. include_labels: &Vec<&str>,
  888. ordering: Ordering<'_>,
  889. ) -> String {
  890. let filters = filters
  891. .iter()
  892. .map(|(key, val)| format!("{}={}", key, val))
  893. .chain(std::iter::once(format!(
  894. "labels={}",
  895. include_labels.join(",")
  896. )))
  897. .chain(std::iter::once("filter=all".to_owned()))
  898. .chain(std::iter::once(format!("sort={}", ordering.sort,)))
  899. .chain(std::iter::once(
  900. format!("direction={}", ordering.direction,),
  901. ))
  902. .chain(std::iter::once(format!("per_page={}", ordering.per_page,)))
  903. .collect::<Vec<_>>()
  904. .join("&");
  905. format!(
  906. "{}/repos/{}/{}?{}",
  907. Repository::GITHUB_API_URL,
  908. self.full_name,
  909. endpoint,
  910. filters
  911. )
  912. }
  913. fn build_search_issues_url(
  914. &self,
  915. filters: &Vec<(&str, &str)>,
  916. include_labels: &Vec<&str>,
  917. exclude_labels: &Vec<&str>,
  918. ordering: Ordering<'_>,
  919. ) -> String {
  920. let filters = filters
  921. .iter()
  922. .filter(|&&(key, val)| !(key == "state" && val == "all"))
  923. .map(|(key, val)| format!("{}:{}", key, val))
  924. .chain(
  925. include_labels
  926. .iter()
  927. .map(|label| format!("label:{}", label)),
  928. )
  929. .chain(
  930. exclude_labels
  931. .iter()
  932. .map(|label| format!("-label:{}", label)),
  933. )
  934. .chain(std::iter::once(format!("repo:{}", self.full_name)))
  935. .collect::<Vec<_>>()
  936. .join("+");
  937. format!(
  938. "{}/search/issues?q={}&sort={}&order={}&per_page={}&page={}",
  939. Repository::GITHUB_API_URL,
  940. filters,
  941. ordering.sort,
  942. ordering.direction,
  943. ordering.per_page,
  944. ordering.page,
  945. )
  946. }
  947. }
  948. pub struct Query<'a> {
  949. // key/value filter
  950. pub filters: Vec<(&'a str, &'a str)>,
  951. pub include_labels: Vec<&'a str>,
  952. pub exclude_labels: Vec<&'a str>,
  953. }
  954. fn quote_reply(markdown: &str) -> String {
  955. if markdown.is_empty() {
  956. String::from("*No content*")
  957. } else {
  958. format!("\n\t> {}", markdown.replace("\n", "\n\t> "))
  959. }
  960. }
  961. #[async_trait]
  962. impl<'q> IssuesQuery for Query<'q> {
  963. async fn query<'a>(
  964. &'a self,
  965. repo: &'a Repository,
  966. include_fcp_details: bool,
  967. client: &'a GithubClient,
  968. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>> {
  969. let issues = repo
  970. .get_issues(&client, self)
  971. .await
  972. .with_context(|| "Unable to get issues.")?;
  973. let fcp_map = crate::rfcbot::get_all_fcps().await?;
  974. let mut issues_decorator = Vec::new();
  975. for issue in issues {
  976. let fcp_details = if include_fcp_details {
  977. let repository_name = if let Some(repo) = issue.repository.get() {
  978. repo.repository.clone()
  979. } else {
  980. let re = regex::Regex::new("https://github.com/rust-lang/|/").unwrap();
  981. let split = re.split(&issue.html_url).collect::<Vec<&str>>();
  982. split[1].to_string()
  983. };
  984. let key = format!(
  985. "rust-lang/{}:{}:{}",
  986. repository_name, issue.number, issue.title,
  987. );
  988. if let Some(fcp) = fcp_map.get(&key) {
  989. let bot_tracking_comment_html_url = format!(
  990. "{}#issuecomment-{}",
  991. issue.html_url, fcp.fcp.fk_bot_tracking_comment
  992. );
  993. let bot_tracking_comment_content = quote_reply(&fcp.status_comment.body);
  994. let fk_initiating_comment = fcp.fcp.fk_initiating_comment;
  995. let init_comment = issue
  996. .get_comment(&client, fk_initiating_comment.try_into()?)
  997. .await?;
  998. Some(crate::actions::FCPDetails {
  999. bot_tracking_comment_html_url,
  1000. bot_tracking_comment_content,
  1001. initiating_comment_html_url: init_comment.html_url.clone(),
  1002. initiating_comment_content: quote_reply(&init_comment.body),
  1003. })
  1004. } else {
  1005. None
  1006. }
  1007. } else {
  1008. None
  1009. };
  1010. issues_decorator.push(crate::actions::IssueDecorator {
  1011. title: issue.title.clone(),
  1012. number: issue.number,
  1013. html_url: issue.html_url.clone(),
  1014. repo_name: repo.name().to_owned(),
  1015. labels: issue
  1016. .labels
  1017. .iter()
  1018. .map(|l| l.name.as_ref())
  1019. .collect::<Vec<_>>()
  1020. .join(", "),
  1021. assignees: issue
  1022. .assignees
  1023. .iter()
  1024. .map(|u| u.login.as_ref())
  1025. .collect::<Vec<_>>()
  1026. .join(", "),
  1027. updated_at: crate::actions::to_human(issue.updated_at),
  1028. fcp_details,
  1029. });
  1030. }
  1031. Ok(issues_decorator)
  1032. }
  1033. }
  1034. #[derive(Debug, serde::Deserialize)]
  1035. #[serde(rename_all = "snake_case")]
  1036. pub enum CreateKind {
  1037. Branch,
  1038. Tag,
  1039. }
  1040. #[derive(Debug, serde::Deserialize)]
  1041. pub struct CreateEvent {
  1042. pub ref_type: CreateKind,
  1043. repository: Repository,
  1044. sender: User,
  1045. }
  1046. #[derive(Debug, serde::Deserialize)]
  1047. pub struct PushEvent {
  1048. #[serde(rename = "ref")]
  1049. pub git_ref: String,
  1050. repository: Repository,
  1051. sender: User,
  1052. }
  1053. #[derive(Debug)]
  1054. pub enum Event {
  1055. Create(CreateEvent),
  1056. IssueComment(IssueCommentEvent),
  1057. Issue(IssuesEvent),
  1058. Push(PushEvent),
  1059. }
  1060. impl Event {
  1061. pub fn repo_name(&self) -> String {
  1062. match self {
  1063. Event::Create(event) => event.repository.full_name.clone(),
  1064. Event::IssueComment(event) => event.repository.full_name.clone(),
  1065. Event::Issue(event) => event.repository.full_name.clone(),
  1066. Event::Push(event) => event.repository.full_name.clone(),
  1067. }
  1068. }
  1069. pub fn issue(&self) -> Option<&Issue> {
  1070. match self {
  1071. Event::Create(_) => None,
  1072. Event::IssueComment(event) => Some(&event.issue),
  1073. Event::Issue(event) => Some(&event.issue),
  1074. Event::Push(_) => None,
  1075. }
  1076. }
  1077. /// This will both extract from IssueComment events but also Issue events
  1078. pub fn comment_body(&self) -> Option<&str> {
  1079. match self {
  1080. Event::Create(_) => None,
  1081. Event::Issue(e) => Some(&e.issue.body),
  1082. Event::IssueComment(e) => Some(&e.comment.body),
  1083. Event::Push(_) => None,
  1084. }
  1085. }
  1086. /// This will both extract from IssueComment events but also Issue events
  1087. pub fn comment_from(&self) -> Option<&str> {
  1088. match self {
  1089. Event::Create(_) => None,
  1090. Event::Issue(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  1091. Event::IssueComment(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  1092. Event::Push(_) => None,
  1093. }
  1094. }
  1095. pub fn html_url(&self) -> Option<&str> {
  1096. match self {
  1097. Event::Create(_) => None,
  1098. Event::Issue(e) => Some(&e.issue.html_url),
  1099. Event::IssueComment(e) => Some(&e.comment.html_url),
  1100. Event::Push(_) => None,
  1101. }
  1102. }
  1103. pub fn user(&self) -> &User {
  1104. match self {
  1105. Event::Create(e) => &e.sender,
  1106. Event::Issue(e) => &e.issue.user,
  1107. Event::IssueComment(e) => &e.comment.user,
  1108. Event::Push(e) => &e.sender,
  1109. }
  1110. }
  1111. pub fn time(&self) -> Option<chrono::DateTime<FixedOffset>> {
  1112. match self {
  1113. Event::Create(_) => None,
  1114. Event::Issue(e) => Some(e.issue.created_at.into()),
  1115. Event::IssueComment(e) => Some(e.comment.updated_at.into()),
  1116. Event::Push(_) => None,
  1117. }
  1118. }
  1119. }
  1120. trait RequestSend: Sized {
  1121. fn configure(self, g: &GithubClient) -> Self;
  1122. }
  1123. impl RequestSend for RequestBuilder {
  1124. fn configure(self, g: &GithubClient) -> RequestBuilder {
  1125. let mut auth = HeaderValue::from_maybe_shared(format!("token {}", g.token)).unwrap();
  1126. auth.set_sensitive(true);
  1127. self.header(USER_AGENT, "rust-lang-triagebot")
  1128. .header(AUTHORIZATION, &auth)
  1129. }
  1130. }
  1131. /// Finds the token in the user's environment, panicking if no suitable token
  1132. /// can be found.
  1133. pub fn default_token_from_env() -> String {
  1134. match std::env::var("GITHUB_API_TOKEN") {
  1135. Ok(v) => return v,
  1136. Err(_) => (),
  1137. }
  1138. match get_token_from_git_config() {
  1139. Ok(v) => return v,
  1140. Err(_) => (),
  1141. }
  1142. panic!("could not find token in GITHUB_API_TOKEN or .gitconfig/github.oath-token")
  1143. }
  1144. fn get_token_from_git_config() -> anyhow::Result<String> {
  1145. let output = std::process::Command::new("git")
  1146. .arg("config")
  1147. .arg("--get")
  1148. .arg("github.oauth-token")
  1149. .output()?;
  1150. if !output.status.success() {
  1151. anyhow::bail!("error received executing `git`: {:?}", output.status);
  1152. }
  1153. let git_token = String::from_utf8(output.stdout)?.trim().to_string();
  1154. Ok(git_token)
  1155. }
  1156. #[derive(Clone)]
  1157. pub struct GithubClient {
  1158. token: String,
  1159. client: Client,
  1160. }
  1161. impl GithubClient {
  1162. pub fn new(client: Client, token: String) -> Self {
  1163. GithubClient { client, token }
  1164. }
  1165. pub fn new_with_default_token(client: Client) -> Self {
  1166. Self::new(client, default_token_from_env())
  1167. }
  1168. pub fn raw(&self) -> &Client {
  1169. &self.client
  1170. }
  1171. pub async fn raw_file(
  1172. &self,
  1173. repo: &str,
  1174. branch: &str,
  1175. path: &str,
  1176. ) -> anyhow::Result<Option<Vec<u8>>> {
  1177. let url = format!(
  1178. "https://raw.githubusercontent.com/{}/{}/{}",
  1179. repo, branch, path
  1180. );
  1181. let req = self.get(&url);
  1182. let req_dbg = format!("{:?}", req);
  1183. let req = req
  1184. .build()
  1185. .with_context(|| format!("failed to build request {:?}", req_dbg))?;
  1186. let mut resp = self.client.execute(req).await.context(req_dbg.clone())?;
  1187. let status = resp.status();
  1188. match status {
  1189. StatusCode::OK => {
  1190. let mut buf = Vec::with_capacity(resp.content_length().unwrap_or(4) as usize);
  1191. while let Some(chunk) = resp.chunk().await.transpose() {
  1192. let chunk = chunk
  1193. .context("reading stream failed")
  1194. .map_err(anyhow::Error::from)
  1195. .context(req_dbg.clone())?;
  1196. buf.extend_from_slice(&chunk);
  1197. }
  1198. Ok(Some(buf))
  1199. }
  1200. StatusCode::NOT_FOUND => Ok(None),
  1201. status => anyhow::bail!("failed to GET {}: {}", url, status),
  1202. }
  1203. }
  1204. /// Get the raw gist content from the URL of the HTML version of the gist:
  1205. ///
  1206. /// `html_url` looks like `https://gist.github.com/rust-play/7e80ca3b1ec7abe08f60c41aff91f060`.
  1207. ///
  1208. /// `filename` is the name of the file you want the content of.
  1209. pub async fn raw_gist_from_url(
  1210. &self,
  1211. html_url: &str,
  1212. filename: &str,
  1213. ) -> anyhow::Result<String> {
  1214. let url = html_url.replace("github.com", "githubusercontent.com") + "/raw/" + filename;
  1215. let response = self.raw().get(&url).send().await?;
  1216. response.text().await.context("raw gist from url")
  1217. }
  1218. fn get(&self, url: &str) -> RequestBuilder {
  1219. log::trace!("get {:?}", url);
  1220. self.client.get(url).configure(self)
  1221. }
  1222. fn patch(&self, url: &str) -> RequestBuilder {
  1223. log::trace!("patch {:?}", url);
  1224. self.client.patch(url).configure(self)
  1225. }
  1226. fn delete(&self, url: &str) -> RequestBuilder {
  1227. log::trace!("delete {:?}", url);
  1228. self.client.delete(url).configure(self)
  1229. }
  1230. fn post(&self, url: &str) -> RequestBuilder {
  1231. log::trace!("post {:?}", url);
  1232. self.client.post(url).configure(self)
  1233. }
  1234. #[allow(unused)]
  1235. fn put(&self, url: &str) -> RequestBuilder {
  1236. log::trace!("put {:?}", url);
  1237. self.client.put(url).configure(self)
  1238. }
  1239. pub async fn rust_commit(&self, sha: &str) -> Option<GithubCommit> {
  1240. let req = self.get(&format!(
  1241. "https://api.github.com/repos/rust-lang/rust/commits/{}",
  1242. sha
  1243. ));
  1244. match self.json(req).await {
  1245. Ok(r) => Some(r),
  1246. Err(e) => {
  1247. log::error!("Failed to query commit {:?}: {:?}", sha, e);
  1248. None
  1249. }
  1250. }
  1251. }
  1252. /// This does not retrieve all of them, only the last several.
  1253. pub async fn bors_commits(&self) -> Vec<GithubCommit> {
  1254. let req = self.get("https://api.github.com/repos/rust-lang/rust/commits?author=bors");
  1255. match self.json(req).await {
  1256. Ok(r) => r,
  1257. Err(e) => {
  1258. log::error!("Failed to query commit list: {:?}", e);
  1259. Vec::new()
  1260. }
  1261. }
  1262. }
  1263. }
  1264. #[derive(Debug, serde::Deserialize)]
  1265. pub struct GithubCommit {
  1266. pub sha: String,
  1267. #[serde(default)]
  1268. pub message: String,
  1269. pub commit: GitCommit,
  1270. pub parents: Vec<Parent>,
  1271. }
  1272. #[derive(Debug, serde::Deserialize)]
  1273. pub struct GitCommit {
  1274. pub author: GitUser,
  1275. }
  1276. #[derive(Debug, serde::Deserialize)]
  1277. pub struct GitUser {
  1278. pub date: DateTime<FixedOffset>,
  1279. }
  1280. #[derive(Debug, serde::Deserialize)]
  1281. pub struct Parent {
  1282. pub sha: String,
  1283. }
  1284. #[async_trait]
  1285. pub trait IssuesQuery {
  1286. async fn query<'a>(
  1287. &'a self,
  1288. repo: &'a Repository,
  1289. include_fcp_details: bool,
  1290. client: &'a GithubClient,
  1291. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>>;
  1292. }
  1293. #[cfg(test)]
  1294. mod tests {
  1295. use super::*;
  1296. #[test]
  1297. fn display_labels() {
  1298. let x = UnknownLabels { labels: vec!["A-bootstrap".into(), "xxx".into()] };
  1299. assert_eq!(x.to_string(), "Unknown labels: A-bootstrap, xxx");
  1300. }
  1301. #[test]
  1302. fn extract_one_file() {
  1303. let input = r##"\
  1304. diff --git a/triagebot.toml b/triagebot.toml
  1305. index fb9cee43b2d..b484c25ea51 100644
  1306. --- a/triagebot.toml
  1307. +++ b/triagebot.toml
  1308. @@ -114,6 +114,15 @@ trigger_files = [
  1309. "src/tools/rustdoc-themes",
  1310. ]
  1311. +[autolabel."T-compiler"]
  1312. +trigger_files = [
  1313. + # Source code
  1314. + "compiler",
  1315. +
  1316. + # Tests
  1317. + "src/test/ui",
  1318. +]
  1319. +
  1320. [notify-zulip."I-prioritize"]
  1321. zulip_stream = 245100 # #t-compiler/wg-prioritization/alerts
  1322. topic = "#{number} {title}"
  1323. "##;
  1324. assert_eq!(files_changed(input), vec!["triagebot.toml".to_string()]);
  1325. }
  1326. #[test]
  1327. fn extract_several_files() {
  1328. let input = r##"\
  1329. diff --git a/library/stdarch b/library/stdarch
  1330. index b70ae88ef2a..cfba59fccd9 160000
  1331. --- a/library/stdarch
  1332. +++ b/library/stdarch
  1333. @@ -1 +1 @@
  1334. -Subproject commit b70ae88ef2a6c83acad0a1e83d5bd78f9655fd05
  1335. +Subproject commit cfba59fccd90b3b52a614120834320f764ab08d1
  1336. diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs
  1337. index 1fe4aa9023e..f0330f1e424 100644
  1338. --- a/src/librustdoc/clean/types.rs
  1339. +++ b/src/librustdoc/clean/types.rs
  1340. @@ -2322,3 +2322,4 @@ impl SubstParam {
  1341. if let Self::Lifetime(lt) = self { Some(lt) } else { None }
  1342. }
  1343. }
  1344. +
  1345. diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
  1346. index c58310947d2..3b0854d4a9b 100644
  1347. --- a/src/librustdoc/core.rs
  1348. +++ b/src/librustdoc/core.rs
  1349. @@ -591,3 +591,4 @@ fn from(idx: u32) -> Self {
  1350. ImplTraitParam::ParamIndex(idx)
  1351. }
  1352. }
  1353. +
  1354. "##;
  1355. assert_eq!(
  1356. files_changed(input),
  1357. vec![
  1358. "library/stdarch".to_string(),
  1359. "src/librustdoc/clean/types.rs".to_string(),
  1360. "src/librustdoc/core.rs".to_string(),
  1361. ]
  1362. )
  1363. }
  1364. }