github.rs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. use anyhow::Context;
  2. use chrono::{DateTime, FixedOffset, Utc};
  3. use futures::stream::{FuturesUnordered, StreamExt};
  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::{
  10. fmt,
  11. time::{Duration, SystemTime},
  12. };
  13. #[derive(Debug, PartialEq, Eq, serde::Deserialize)]
  14. pub struct User {
  15. pub login: String,
  16. pub id: Option<i64>,
  17. }
  18. impl GithubClient {
  19. async fn _send_req(&self, req: RequestBuilder) -> anyhow::Result<(Response, String)> {
  20. const MAX_ATTEMPTS: usize = 2;
  21. log::debug!("_send_req with {:?}", req);
  22. let req_dbg = format!("{:?}", req);
  23. let req = req
  24. .build()
  25. .with_context(|| format!("building reqwest {}", req_dbg))?;
  26. let mut resp = self.client.execute(req.try_clone().unwrap()).await?;
  27. if let Some(sleep) = Self::needs_retry(&resp).await {
  28. resp = self.retry(req, sleep, MAX_ATTEMPTS).await?;
  29. }
  30. resp.error_for_status_ref()?;
  31. Ok((resp, req_dbg))
  32. }
  33. async fn needs_retry(resp: &Response) -> Option<Duration> {
  34. const REMAINING: &str = "X-RateLimit-Remaining";
  35. const RESET: &str = "X-RateLimit-Reset";
  36. if resp.status().is_success() {
  37. return None;
  38. }
  39. let headers = resp.headers();
  40. if !(headers.contains_key(REMAINING) && headers.contains_key(RESET)) {
  41. return None;
  42. }
  43. // Weird github api behavior. It asks us to retry but also has a remaining count above 1
  44. // Try again immediately and hope for the best...
  45. if headers[REMAINING] != "0" {
  46. return Some(Duration::from_secs(0));
  47. }
  48. let reset_time = headers[RESET].to_str().unwrap().parse::<u64>().unwrap();
  49. Some(Duration::from_secs(Self::calc_sleep(reset_time) + 10))
  50. }
  51. fn calc_sleep(reset_time: u64) -> u64 {
  52. let epoch_time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs();
  53. reset_time.saturating_sub(epoch_time)
  54. }
  55. fn retry(
  56. &self,
  57. req: Request,
  58. sleep: Duration,
  59. remaining_attempts: usize,
  60. ) -> BoxFuture<Result<Response, reqwest::Error>> {
  61. #[derive(Debug, serde::Deserialize)]
  62. struct RateLimit {
  63. pub limit: u64,
  64. pub remaining: u64,
  65. pub reset: u64,
  66. }
  67. #[derive(Debug, serde::Deserialize)]
  68. struct RateLimitResponse {
  69. pub resources: Resources,
  70. }
  71. #[derive(Debug, serde::Deserialize)]
  72. struct Resources {
  73. pub core: RateLimit,
  74. pub search: RateLimit,
  75. pub graphql: RateLimit,
  76. pub source_import: RateLimit,
  77. }
  78. log::warn!(
  79. "Retrying after {} seconds, remaining attepts {}",
  80. sleep.as_secs(),
  81. remaining_attempts,
  82. );
  83. async move {
  84. tokio::time::delay_for(sleep).await;
  85. // check rate limit
  86. let rate_resp = self
  87. .client
  88. .execute(
  89. self.client
  90. .get("https://api.github.com/rate_limit")
  91. .configure(self)
  92. .build()
  93. .unwrap(),
  94. )
  95. .await?;
  96. let rate_limit_response = rate_resp.json::<RateLimitResponse>().await?;
  97. // Check url for search path because github has different rate limits for the search api
  98. let rate_limit = if req
  99. .url()
  100. .path_segments()
  101. .map(|mut segments| matches!(segments.next(), Some("search")))
  102. .unwrap_or(false)
  103. {
  104. rate_limit_response.resources.search
  105. } else {
  106. rate_limit_response.resources.core
  107. };
  108. // If we still don't have any more remaining attempts, try sleeping for the remaining
  109. // period of time
  110. if rate_limit.remaining == 0 {
  111. let sleep = Self::calc_sleep(rate_limit.reset);
  112. if sleep > 0 {
  113. tokio::time::delay_for(Duration::from_secs(sleep)).await;
  114. }
  115. }
  116. let resp = self.client.execute(req.try_clone().unwrap()).await?;
  117. if let Some(sleep) = Self::needs_retry(&resp).await {
  118. if remaining_attempts > 0 {
  119. return self.retry(req, sleep, remaining_attempts - 1).await;
  120. }
  121. }
  122. Ok(resp)
  123. }
  124. .boxed()
  125. }
  126. async fn send_req(&self, req: RequestBuilder) -> anyhow::Result<Vec<u8>> {
  127. let (mut resp, req_dbg) = self._send_req(req).await?;
  128. let mut body = Vec::new();
  129. while let Some(chunk) = resp.chunk().await.transpose() {
  130. let chunk = chunk
  131. .context("reading stream failed")
  132. .map_err(anyhow::Error::from)
  133. .context(req_dbg.clone())?;
  134. body.extend_from_slice(&chunk);
  135. }
  136. Ok(body)
  137. }
  138. pub async fn json<T>(&self, req: RequestBuilder) -> anyhow::Result<T>
  139. where
  140. T: serde::de::DeserializeOwned,
  141. {
  142. let (resp, req_dbg) = self._send_req(req).await?;
  143. Ok(resp.json().await.context(req_dbg)?)
  144. }
  145. }
  146. impl User {
  147. pub async fn current(client: &GithubClient) -> anyhow::Result<Self> {
  148. client.json(client.get("https://api.github.com/user")).await
  149. }
  150. pub async fn is_team_member<'a>(&'a self, client: &'a GithubClient) -> anyhow::Result<bool> {
  151. log::trace!("Getting team membership for {:?}", self.login);
  152. let permission = crate::team_data::teams(client).await?;
  153. let map = permission.teams;
  154. let is_triager = map
  155. .get("wg-triage")
  156. .map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
  157. let is_pri_member = map
  158. .get("wg-prioritization")
  159. .map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
  160. let in_all = map["all"].members.iter().any(|g| g.github == self.login);
  161. log::trace!(
  162. "{:?} is all?={:?}, triager?={:?}, prioritizer?={:?}",
  163. self.login,
  164. in_all,
  165. is_triager,
  166. is_pri_member
  167. );
  168. Ok(in_all || is_triager || is_pri_member)
  169. }
  170. // Returns the ID of the given user, if the user is in the `all` team.
  171. pub async fn get_id<'a>(&'a self, client: &'a GithubClient) -> anyhow::Result<Option<usize>> {
  172. let permission = crate::team_data::teams(client).await?;
  173. let map = permission.teams;
  174. Ok(map["all"]
  175. .members
  176. .iter()
  177. .find(|g| g.github == self.login)
  178. .map(|u| u.github_id))
  179. }
  180. }
  181. pub async fn get_team(
  182. client: &GithubClient,
  183. team: &str,
  184. ) -> anyhow::Result<Option<rust_team_data::v1::Team>> {
  185. let permission = crate::team_data::teams(client).await?;
  186. let mut map = permission.teams;
  187. Ok(map.swap_remove(team))
  188. }
  189. #[derive(PartialEq, Eq, Debug, Clone, serde::Deserialize)]
  190. pub struct Label {
  191. pub name: String,
  192. }
  193. impl Label {
  194. async fn exists<'a>(&'a self, repo_api_prefix: &'a str, client: &'a GithubClient) -> bool {
  195. #[allow(clippy::redundant_pattern_matching)]
  196. let url = format!("{}/labels/{}", repo_api_prefix, self.name);
  197. match client.send_req(client.get(&url)).await {
  198. Ok(_) => true,
  199. // XXX: Error handling if the request failed for reasons beyond 'label didn't exist'
  200. Err(_) => false,
  201. }
  202. }
  203. }
  204. #[derive(Debug, serde::Deserialize)]
  205. pub struct PullRequestDetails {
  206. // none for now
  207. }
  208. #[derive(Debug, serde::Deserialize)]
  209. pub struct Issue {
  210. pub number: u64,
  211. pub body: String,
  212. created_at: chrono::DateTime<Utc>,
  213. #[serde(default)]
  214. pub merge_commit_sha: Option<String>,
  215. pub title: String,
  216. pub html_url: String,
  217. pub user: User,
  218. pub labels: Vec<Label>,
  219. pub assignees: Vec<User>,
  220. pub pull_request: Option<PullRequestDetails>,
  221. #[serde(default)]
  222. pub merged: bool,
  223. // API URL
  224. comments_url: String,
  225. #[serde(skip)]
  226. repository: OnceCell<IssueRepository>,
  227. }
  228. /// Contains only the parts of `Issue` that are needed for turning the issue title into a Zulip
  229. /// topic.
  230. #[derive(Clone, Debug, PartialEq, Eq)]
  231. pub struct ZulipGitHubReference {
  232. pub number: u64,
  233. pub title: String,
  234. pub repository: IssueRepository,
  235. }
  236. impl ZulipGitHubReference {
  237. pub fn zulip_topic_reference(&self) -> String {
  238. let repo = &self.repository;
  239. if repo.organization == "rust-lang" {
  240. if repo.repository == "rust" {
  241. format!("#{}", self.number)
  242. } else {
  243. format!("{}#{}", repo.repository, self.number)
  244. }
  245. } else {
  246. format!("{}/{}#{}", repo.organization, repo.repository, self.number)
  247. }
  248. }
  249. }
  250. #[derive(Debug, serde::Deserialize)]
  251. pub struct Comment {
  252. #[serde(deserialize_with = "opt_string")]
  253. pub body: String,
  254. pub html_url: String,
  255. pub user: User,
  256. #[serde(alias = "submitted_at")] // for pull request reviews
  257. pub updated_at: chrono::DateTime<Utc>,
  258. #[serde(rename = "state")]
  259. pub pr_review_state: PullRequestReviewState,
  260. }
  261. #[derive(Debug, serde::Deserialize, Eq, PartialEq)]
  262. #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
  263. pub enum PullRequestReviewState {
  264. Approved,
  265. ChangesRequested,
  266. Commented,
  267. Dismissed,
  268. Pending,
  269. }
  270. fn opt_string<'de, D>(deserializer: D) -> Result<String, D::Error>
  271. where
  272. D: serde::de::Deserializer<'de>,
  273. {
  274. use serde::de::Deserialize;
  275. match <Option<String>>::deserialize(deserializer) {
  276. Ok(v) => Ok(v.unwrap_or_default()),
  277. Err(e) => Err(e),
  278. }
  279. }
  280. #[derive(Debug)]
  281. pub enum AssignmentError {
  282. InvalidAssignee,
  283. Http(anyhow::Error),
  284. }
  285. #[derive(Debug)]
  286. pub enum Selection<'a, T: ?Sized> {
  287. All,
  288. One(&'a T),
  289. Except(&'a T),
  290. }
  291. impl fmt::Display for AssignmentError {
  292. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  293. match self {
  294. AssignmentError::InvalidAssignee => write!(f, "invalid assignee"),
  295. AssignmentError::Http(e) => write!(f, "cannot assign: {}", e),
  296. }
  297. }
  298. }
  299. impl std::error::Error for AssignmentError {}
  300. #[derive(Debug, Clone, PartialEq, Eq)]
  301. pub struct IssueRepository {
  302. pub organization: String,
  303. pub repository: String,
  304. }
  305. impl fmt::Display for IssueRepository {
  306. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  307. write!(f, "{}/{}", self.organization, self.repository)
  308. }
  309. }
  310. impl IssueRepository {
  311. fn url(&self) -> String {
  312. format!(
  313. "https://api.github.com/repos/{}/{}",
  314. self.organization, self.repository
  315. )
  316. }
  317. }
  318. impl Issue {
  319. pub fn to_zulip_github_reference(&self) -> ZulipGitHubReference {
  320. ZulipGitHubReference {
  321. number: self.number,
  322. title: self.title.clone(),
  323. repository: self.repository().clone(),
  324. }
  325. }
  326. pub fn repository(&self) -> &IssueRepository {
  327. self.repository.get_or_init(|| {
  328. // https://api.github.com/repos/rust-lang/rust/issues/69257/comments
  329. log::trace!("get repository for {}", self.comments_url);
  330. let url = url::Url::parse(&self.comments_url).unwrap();
  331. let mut segments = url.path_segments().unwrap();
  332. let _comments = segments.next_back().unwrap();
  333. let _number = segments.next_back().unwrap();
  334. let _issues_or_prs = segments.next_back().unwrap();
  335. let repository = segments.next_back().unwrap();
  336. let organization = segments.next_back().unwrap();
  337. IssueRepository {
  338. organization: organization.into(),
  339. repository: repository.into(),
  340. }
  341. })
  342. }
  343. pub fn global_id(&self) -> String {
  344. format!("{}#{}", self.repository(), self.number)
  345. }
  346. pub fn is_pr(&self) -> bool {
  347. self.pull_request.is_some()
  348. }
  349. pub async fn get_comment(&self, client: &GithubClient, id: usize) -> anyhow::Result<Comment> {
  350. let comment_url = format!("{}/issues/comments/{}", self.repository().url(), id);
  351. let comment = client.json(client.get(&comment_url)).await?;
  352. Ok(comment)
  353. }
  354. pub async fn edit_body(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  355. let edit_url = format!("{}/issues/{}", self.repository().url(), self.number);
  356. #[derive(serde::Serialize)]
  357. struct ChangedIssue<'a> {
  358. body: &'a str,
  359. }
  360. client
  361. ._send_req(client.patch(&edit_url).json(&ChangedIssue { body }))
  362. .await
  363. .context("failed to edit issue body")?;
  364. Ok(())
  365. }
  366. pub async fn edit_comment(
  367. &self,
  368. client: &GithubClient,
  369. id: usize,
  370. new_body: &str,
  371. ) -> anyhow::Result<()> {
  372. let comment_url = format!("{}/issues/comments/{}", self.repository().url(), id);
  373. #[derive(serde::Serialize)]
  374. struct NewComment<'a> {
  375. body: &'a str,
  376. }
  377. client
  378. ._send_req(
  379. client
  380. .patch(&comment_url)
  381. .json(&NewComment { body: new_body }),
  382. )
  383. .await
  384. .context("failed to edit comment")?;
  385. Ok(())
  386. }
  387. pub async fn post_comment(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  388. #[derive(serde::Serialize)]
  389. struct PostComment<'a> {
  390. body: &'a str,
  391. }
  392. client
  393. ._send_req(client.post(&self.comments_url).json(&PostComment { body }))
  394. .await
  395. .context("failed to post comment")?;
  396. Ok(())
  397. }
  398. pub async fn set_labels(
  399. &self,
  400. client: &GithubClient,
  401. labels: Vec<Label>,
  402. ) -> anyhow::Result<()> {
  403. log::info!("set_labels {} to {:?}", self.global_id(), labels);
  404. // PUT /repos/:owner/:repo/issues/:number/labels
  405. // repo_url = https://api.github.com/repos/Codertocat/Hello-World
  406. let url = format!(
  407. "{repo_url}/issues/{number}/labels",
  408. repo_url = self.repository().url(),
  409. number = self.number
  410. );
  411. let mut stream = labels
  412. .into_iter()
  413. .map(|label| async { (label.exists(&self.repository().url(), &client).await, label) })
  414. .collect::<FuturesUnordered<_>>();
  415. let mut labels = Vec::new();
  416. while let Some((true, label)) = stream.next().await {
  417. labels.push(label);
  418. }
  419. #[derive(serde::Serialize)]
  420. struct LabelsReq {
  421. labels: Vec<String>,
  422. }
  423. client
  424. ._send_req(client.put(&url).json(&LabelsReq {
  425. labels: labels.iter().map(|l| l.name.clone()).collect(),
  426. }))
  427. .await
  428. .context("failed to set labels")?;
  429. Ok(())
  430. }
  431. pub fn labels(&self) -> &[Label] {
  432. &self.labels
  433. }
  434. pub fn contain_assignee(&self, user: &str) -> bool {
  435. self.assignees.iter().any(|a| a.login == user)
  436. }
  437. pub async fn remove_assignees(
  438. &self,
  439. client: &GithubClient,
  440. selection: Selection<'_, str>,
  441. ) -> Result<(), AssignmentError> {
  442. log::info!("remove {:?} assignees for {}", selection, self.global_id());
  443. let url = format!(
  444. "{repo_url}/issues/{number}/assignees",
  445. repo_url = self.repository().url(),
  446. number = self.number
  447. );
  448. let assignees = match selection {
  449. Selection::All => self
  450. .assignees
  451. .iter()
  452. .map(|u| u.login.as_str())
  453. .collect::<Vec<_>>(),
  454. Selection::One(user) => vec![user],
  455. Selection::Except(user) => self
  456. .assignees
  457. .iter()
  458. .map(|u| u.login.as_str())
  459. .filter(|&u| u != user)
  460. .collect::<Vec<_>>(),
  461. };
  462. #[derive(serde::Serialize)]
  463. struct AssigneeReq<'a> {
  464. assignees: &'a [&'a str],
  465. }
  466. client
  467. ._send_req(client.delete(&url).json(&AssigneeReq {
  468. assignees: &assignees[..],
  469. }))
  470. .await
  471. .map_err(AssignmentError::Http)?;
  472. Ok(())
  473. }
  474. pub async fn add_assignee(
  475. &self,
  476. client: &GithubClient,
  477. user: &str,
  478. ) -> Result<(), AssignmentError> {
  479. log::info!("add_assignee {} for {}", user, self.global_id());
  480. let url = format!(
  481. "{repo_url}/issues/{number}/assignees",
  482. repo_url = self.repository().url(),
  483. number = self.number
  484. );
  485. #[derive(serde::Serialize)]
  486. struct AssigneeReq<'a> {
  487. assignees: &'a [&'a str],
  488. }
  489. let result: Issue = client
  490. .json(client.post(&url).json(&AssigneeReq { assignees: &[user] }))
  491. .await
  492. .map_err(AssignmentError::Http)?;
  493. // Invalid assignees are silently ignored. We can just check if the user is now
  494. // contained in the assignees list.
  495. let success = result.assignees.iter().any(|u| u.login.as_str() == user);
  496. if success {
  497. Ok(())
  498. } else {
  499. Err(AssignmentError::InvalidAssignee)
  500. }
  501. }
  502. pub async fn set_assignee(
  503. &self,
  504. client: &GithubClient,
  505. user: &str,
  506. ) -> Result<(), AssignmentError> {
  507. log::info!("set_assignee for {} to {}", self.global_id(), user);
  508. self.add_assignee(client, user).await?;
  509. self.remove_assignees(client, Selection::Except(user))
  510. .await?;
  511. Ok(())
  512. }
  513. pub async fn set_milestone(&self, client: &GithubClient, title: &str) -> anyhow::Result<()> {
  514. log::trace!(
  515. "Setting milestone for rust-lang/rust#{} to {}",
  516. self.number,
  517. title
  518. );
  519. let create_url = format!("{}/milestones", self.repository().url());
  520. let resp = client
  521. .send_req(
  522. client
  523. .post(&create_url)
  524. .body(serde_json::to_vec(&MilestoneCreateBody { title }).unwrap()),
  525. )
  526. .await;
  527. // Explicitly do *not* try to return Err(...) if this fails -- that's
  528. // fine, it just means the milestone was already created.
  529. log::trace!("Created milestone: {:?}", resp);
  530. let list_url = format!("{}/milestones", self.repository().url());
  531. let milestone_list: Vec<Milestone> = client.json(client.get(&list_url)).await?;
  532. let milestone_no = if let Some(milestone) = milestone_list.iter().find(|v| v.title == title)
  533. {
  534. milestone.number
  535. } else {
  536. anyhow::bail!(
  537. "Despite just creating milestone {} on {}, it does not exist?",
  538. title,
  539. self.repository()
  540. )
  541. };
  542. #[derive(serde::Serialize)]
  543. struct SetMilestone {
  544. milestone: u64,
  545. }
  546. let url = format!("{}/issues/{}", self.repository().url(), self.number);
  547. client
  548. ._send_req(client.patch(&url).json(&SetMilestone {
  549. milestone: milestone_no,
  550. }))
  551. .await
  552. .context("failed to set milestone")?;
  553. Ok(())
  554. }
  555. pub async fn close(&self, client: &GithubClient) -> anyhow::Result<()> {
  556. let edit_url = format!("{}/issues/{}", self.repository().url(), self.number);
  557. #[derive(serde::Serialize)]
  558. struct CloseIssue<'a> {
  559. state: &'a str,
  560. }
  561. client
  562. ._send_req(
  563. client
  564. .patch(&edit_url)
  565. .json(&CloseIssue { state: "closed" }),
  566. )
  567. .await
  568. .context("failed to close issue")?;
  569. Ok(())
  570. }
  571. }
  572. #[derive(serde::Serialize)]
  573. struct MilestoneCreateBody<'a> {
  574. title: &'a str,
  575. }
  576. #[derive(Debug, serde::Deserialize)]
  577. pub struct Milestone {
  578. number: u64,
  579. title: String,
  580. }
  581. #[derive(Debug, serde::Deserialize)]
  582. pub struct ChangeInner {
  583. pub from: String,
  584. }
  585. #[derive(Debug, serde::Deserialize)]
  586. pub struct Changes {
  587. pub title: Option<ChangeInner>,
  588. pub body: Option<ChangeInner>,
  589. }
  590. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  591. #[serde(rename_all = "lowercase")]
  592. pub enum PullRequestReviewAction {
  593. Submitted,
  594. Edited,
  595. Dismissed,
  596. }
  597. #[derive(Debug, serde::Deserialize)]
  598. pub struct PullRequestReviewEvent {
  599. pub action: PullRequestReviewAction,
  600. pub pull_request: Issue,
  601. pub review: Comment,
  602. pub changes: Option<Changes>,
  603. pub repository: Repository,
  604. }
  605. #[derive(Debug, serde::Deserialize)]
  606. pub struct PullRequestReviewComment {
  607. pub action: IssueCommentAction,
  608. pub changes: Option<Changes>,
  609. #[serde(rename = "pull_request")]
  610. pub issue: Issue,
  611. pub comment: Comment,
  612. pub repository: Repository,
  613. }
  614. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  615. #[serde(rename_all = "lowercase")]
  616. pub enum IssueCommentAction {
  617. Created,
  618. Edited,
  619. Deleted,
  620. }
  621. #[derive(Debug, serde::Deserialize)]
  622. pub struct IssueCommentEvent {
  623. pub action: IssueCommentAction,
  624. pub changes: Option<Changes>,
  625. pub issue: Issue,
  626. pub comment: Comment,
  627. pub repository: Repository,
  628. }
  629. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  630. #[serde(rename_all = "snake_case")]
  631. pub enum IssuesAction {
  632. Opened,
  633. Edited,
  634. Deleted,
  635. Transferred,
  636. Pinned,
  637. Unpinned,
  638. Closed,
  639. Reopened,
  640. Assigned,
  641. Unassigned,
  642. Labeled,
  643. Unlabeled,
  644. Locked,
  645. Unlocked,
  646. Milestoned,
  647. Demilestoned,
  648. ReviewRequested,
  649. ReviewRequestRemoved,
  650. ReadyForReview,
  651. Synchronize,
  652. ConvertedToDraft,
  653. }
  654. #[derive(Debug, serde::Deserialize)]
  655. pub struct IssuesEvent {
  656. pub action: IssuesAction,
  657. #[serde(alias = "pull_request")]
  658. pub issue: Issue,
  659. pub changes: Option<Changes>,
  660. pub repository: Repository,
  661. /// Some if action is IssuesAction::Labeled, for example
  662. pub label: Option<Label>,
  663. }
  664. #[derive(Debug, serde::Deserialize)]
  665. pub struct IssueSearchResult {
  666. pub total_count: usize,
  667. pub incomplete_results: bool,
  668. pub items: Vec<Issue>,
  669. }
  670. #[derive(Debug, serde::Deserialize)]
  671. pub struct Repository {
  672. pub full_name: String,
  673. }
  674. impl Repository {
  675. const GITHUB_API_URL: &'static str = "https://api.github.com";
  676. pub async fn get_issues<'a>(
  677. &self,
  678. client: &GithubClient,
  679. query: &Query<'a>,
  680. ) -> anyhow::Result<Vec<Issue>> {
  681. let Query {
  682. filters,
  683. include_labels,
  684. exclude_labels,
  685. ..
  686. } = query;
  687. let use_issues = exclude_labels.is_empty() && filters.iter().all(|&(key, _)| key != "no");
  688. let is_pr = filters
  689. .iter()
  690. .any(|&(key, value)| key == "is" && value == "pr");
  691. // negating filters can only be handled by the search api
  692. let url = if is_pr {
  693. self.build_pulls_url(filters, include_labels)
  694. } else if use_issues {
  695. self.build_issues_url(filters, include_labels)
  696. } else {
  697. self.build_search_issues_url(filters, include_labels, exclude_labels)
  698. };
  699. let result = client.get(&url);
  700. if use_issues {
  701. client
  702. .json(result)
  703. .await
  704. .with_context(|| format!("failed to list issues from {}", url))
  705. } else {
  706. let result = client
  707. .json::<IssueSearchResult>(result)
  708. .await
  709. .with_context(|| format!("failed to list issues from {}", url))?;
  710. Ok(result.items)
  711. }
  712. }
  713. pub async fn get_issues_count<'a>(
  714. &self,
  715. client: &GithubClient,
  716. query: &Query<'a>,
  717. ) -> anyhow::Result<usize> {
  718. Ok(self.get_issues(client, query).await?.len())
  719. }
  720. fn build_issues_url(&self, filters: &Vec<(&str, &str)>, include_labels: &Vec<&str>) -> String {
  721. let filters = filters
  722. .iter()
  723. .map(|(key, val)| format!("{}={}", key, val))
  724. .chain(std::iter::once(format!(
  725. "labels={}",
  726. include_labels.join(",")
  727. )))
  728. .chain(std::iter::once("filter=all".to_owned()))
  729. .chain(std::iter::once(format!("sort=created")))
  730. .chain(std::iter::once(format!("direction=asc")))
  731. .chain(std::iter::once(format!("per_page=100")))
  732. .collect::<Vec<_>>()
  733. .join("&");
  734. format!(
  735. "{}/repos/{}/issues?{}",
  736. Repository::GITHUB_API_URL,
  737. self.full_name,
  738. filters
  739. )
  740. }
  741. fn build_pulls_url(&self, filters: &Vec<(&str, &str)>, include_labels: &Vec<&str>) -> String {
  742. let filters = filters
  743. .iter()
  744. .map(|(key, val)| format!("{}={}", key, val))
  745. .chain(std::iter::once(format!(
  746. "labels={}",
  747. include_labels.join(",")
  748. )))
  749. .chain(std::iter::once("filter=all".to_owned()))
  750. .chain(std::iter::once(format!("sort=created")))
  751. .chain(std::iter::once(format!("direction=asc")))
  752. .chain(std::iter::once(format!("per_page=100")))
  753. .collect::<Vec<_>>()
  754. .join("&");
  755. format!(
  756. "{}/repos/{}/pulls?{}",
  757. Repository::GITHUB_API_URL,
  758. self.full_name,
  759. filters
  760. )
  761. }
  762. fn build_search_issues_url(
  763. &self,
  764. filters: &Vec<(&str, &str)>,
  765. include_labels: &Vec<&str>,
  766. exclude_labels: &Vec<&str>,
  767. ) -> String {
  768. let filters = filters
  769. .iter()
  770. .map(|(key, val)| format!("{}:{}", key, val))
  771. .chain(
  772. include_labels
  773. .iter()
  774. .map(|label| format!("label:{}", label)),
  775. )
  776. .chain(
  777. exclude_labels
  778. .iter()
  779. .map(|label| format!("-label:{}", label)),
  780. )
  781. .chain(std::iter::once(format!("repo:{}", self.full_name)))
  782. .collect::<Vec<_>>()
  783. .join("+");
  784. format!(
  785. "{}/search/issues?q={}&sort=created&order=asc&per_page=100",
  786. Repository::GITHUB_API_URL,
  787. filters
  788. )
  789. }
  790. }
  791. pub struct Query<'a> {
  792. pub kind: QueryKind,
  793. // key/value filter
  794. pub filters: Vec<(&'a str, &'a str)>,
  795. pub include_labels: Vec<&'a str>,
  796. pub exclude_labels: Vec<&'a str>,
  797. }
  798. pub enum QueryKind {
  799. List,
  800. Count,
  801. }
  802. #[derive(Debug, serde::Deserialize)]
  803. #[serde(rename_all = "snake_case")]
  804. pub enum CreateKind {
  805. Branch,
  806. Tag,
  807. }
  808. #[derive(Debug, serde::Deserialize)]
  809. pub struct CreateEvent {
  810. pub ref_type: CreateKind,
  811. repository: Repository,
  812. sender: User,
  813. }
  814. #[derive(Debug, serde::Deserialize)]
  815. pub struct PushEvent {
  816. #[serde(rename = "ref")]
  817. pub git_ref: String,
  818. repository: Repository,
  819. sender: User,
  820. }
  821. #[derive(Debug)]
  822. pub enum Event {
  823. Create(CreateEvent),
  824. IssueComment(IssueCommentEvent),
  825. Issue(IssuesEvent),
  826. Push(PushEvent),
  827. }
  828. impl Event {
  829. pub fn repo_name(&self) -> &str {
  830. match self {
  831. Event::Create(event) => &event.repository.full_name,
  832. Event::IssueComment(event) => &event.repository.full_name,
  833. Event::Issue(event) => &event.repository.full_name,
  834. Event::Push(event) => &event.repository.full_name,
  835. }
  836. }
  837. pub fn issue(&self) -> Option<&Issue> {
  838. match self {
  839. Event::Create(_) => None,
  840. Event::IssueComment(event) => Some(&event.issue),
  841. Event::Issue(event) => Some(&event.issue),
  842. Event::Push(_) => None,
  843. }
  844. }
  845. /// This will both extract from IssueComment events but also Issue events
  846. pub fn comment_body(&self) -> Option<&str> {
  847. match self {
  848. Event::Create(_) => None,
  849. Event::Issue(e) => Some(&e.issue.body),
  850. Event::IssueComment(e) => Some(&e.comment.body),
  851. Event::Push(_) => None,
  852. }
  853. }
  854. /// This will both extract from IssueComment events but also Issue events
  855. pub fn comment_from(&self) -> Option<&str> {
  856. match self {
  857. Event::Create(_) => None,
  858. Event::Issue(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  859. Event::IssueComment(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  860. Event::Push(_) => None,
  861. }
  862. }
  863. pub fn html_url(&self) -> Option<&str> {
  864. match self {
  865. Event::Create(_) => None,
  866. Event::Issue(e) => Some(&e.issue.html_url),
  867. Event::IssueComment(e) => Some(&e.comment.html_url),
  868. Event::Push(_) => None,
  869. }
  870. }
  871. pub fn user(&self) -> &User {
  872. match self {
  873. Event::Create(e) => &e.sender,
  874. Event::Issue(e) => &e.issue.user,
  875. Event::IssueComment(e) => &e.comment.user,
  876. Event::Push(e) => &e.sender,
  877. }
  878. }
  879. pub fn time(&self) -> Option<chrono::DateTime<FixedOffset>> {
  880. match self {
  881. Event::Create(_) => None,
  882. Event::Issue(e) => Some(e.issue.created_at.into()),
  883. Event::IssueComment(e) => Some(e.comment.updated_at.into()),
  884. Event::Push(_) => None,
  885. }
  886. }
  887. }
  888. trait RequestSend: Sized {
  889. fn configure(self, g: &GithubClient) -> Self;
  890. }
  891. impl RequestSend for RequestBuilder {
  892. fn configure(self, g: &GithubClient) -> RequestBuilder {
  893. let mut auth = HeaderValue::from_maybe_shared(format!("token {}", g.token)).unwrap();
  894. auth.set_sensitive(true);
  895. self.header(USER_AGENT, "rust-lang-triagebot")
  896. .header(AUTHORIZATION, &auth)
  897. }
  898. }
  899. /// Finds the token in the user's environment, panicking if no suitable token
  900. /// can be found.
  901. pub fn default_token_from_env() -> String {
  902. match std::env::var("GITHUB_API_TOKEN") {
  903. Ok(v) => return v,
  904. Err(_) => (),
  905. }
  906. match get_token_from_git_config() {
  907. Ok(v) => return v,
  908. Err(_) => (),
  909. }
  910. panic!("could not find token in GITHUB_API_TOKEN or .gitconfig/github.oath-token")
  911. }
  912. fn get_token_from_git_config() -> anyhow::Result<String> {
  913. let output = std::process::Command::new("git")
  914. .arg("config")
  915. .arg("--get")
  916. .arg("github.oauth-token")
  917. .output()?;
  918. if !output.status.success() {
  919. anyhow::bail!("error received executing `git`: {:?}", output.status);
  920. }
  921. let git_token = String::from_utf8(output.stdout)?.trim().to_string();
  922. Ok(git_token)
  923. }
  924. #[derive(Clone)]
  925. pub struct GithubClient {
  926. token: String,
  927. client: Client,
  928. }
  929. impl GithubClient {
  930. pub fn new(client: Client, token: String) -> Self {
  931. GithubClient { client, token }
  932. }
  933. pub fn new_with_default_token(client: Client) -> Self {
  934. Self::new(client, default_token_from_env())
  935. }
  936. pub fn raw(&self) -> &Client {
  937. &self.client
  938. }
  939. pub async fn raw_file(
  940. &self,
  941. repo: &str,
  942. branch: &str,
  943. path: &str,
  944. ) -> anyhow::Result<Option<Vec<u8>>> {
  945. let url = format!(
  946. "https://raw.githubusercontent.com/{}/{}/{}",
  947. repo, branch, path
  948. );
  949. let req = self.get(&url);
  950. let req_dbg = format!("{:?}", req);
  951. let req = req
  952. .build()
  953. .with_context(|| format!("failed to build request {:?}", req_dbg))?;
  954. let mut resp = self.client.execute(req).await.context(req_dbg.clone())?;
  955. let status = resp.status();
  956. match status {
  957. StatusCode::OK => {
  958. let mut buf = Vec::with_capacity(resp.content_length().unwrap_or(4) as usize);
  959. while let Some(chunk) = resp.chunk().await.transpose() {
  960. let chunk = chunk
  961. .context("reading stream failed")
  962. .map_err(anyhow::Error::from)
  963. .context(req_dbg.clone())?;
  964. buf.extend_from_slice(&chunk);
  965. }
  966. Ok(Some(buf))
  967. }
  968. StatusCode::NOT_FOUND => Ok(None),
  969. status => anyhow::bail!("failed to GET {}: {}", url, status),
  970. }
  971. }
  972. /// Get the raw gist content from the URL of the HTML version of the gist:
  973. ///
  974. /// `html_url` looks like `https://gist.github.com/rust-play/7e80ca3b1ec7abe08f60c41aff91f060`.
  975. ///
  976. /// `filename` is the name of the file you want the content of.
  977. pub async fn raw_gist_from_url(
  978. &self,
  979. html_url: &str,
  980. filename: &str,
  981. ) -> anyhow::Result<String> {
  982. let url = html_url.replace("github.com", "githubusercontent.com") + "/raw/" + filename;
  983. let response = self.raw().get(&url).send().await?;
  984. response.text().await.context("raw gist from url")
  985. }
  986. fn get(&self, url: &str) -> RequestBuilder {
  987. log::trace!("get {:?}", url);
  988. self.client.get(url).configure(self)
  989. }
  990. fn patch(&self, url: &str) -> RequestBuilder {
  991. log::trace!("patch {:?}", url);
  992. self.client.patch(url).configure(self)
  993. }
  994. fn delete(&self, url: &str) -> RequestBuilder {
  995. log::trace!("delete {:?}", url);
  996. self.client.delete(url).configure(self)
  997. }
  998. fn post(&self, url: &str) -> RequestBuilder {
  999. log::trace!("post {:?}", url);
  1000. self.client.post(url).configure(self)
  1001. }
  1002. fn put(&self, url: &str) -> RequestBuilder {
  1003. log::trace!("put {:?}", url);
  1004. self.client.put(url).configure(self)
  1005. }
  1006. pub async fn rust_commit(&self, sha: &str) -> Option<GithubCommit> {
  1007. let req = self.get(&format!(
  1008. "https://api.github.com/repos/rust-lang/rust/commits/{}",
  1009. sha
  1010. ));
  1011. match self.json(req).await {
  1012. Ok(r) => Some(r),
  1013. Err(e) => {
  1014. log::error!("Failed to query commit {:?}: {:?}", sha, e);
  1015. None
  1016. }
  1017. }
  1018. }
  1019. /// This does not retrieve all of them, only the last several.
  1020. pub async fn bors_commits(&self) -> Vec<GithubCommit> {
  1021. let req = self.get("https://api.github.com/repos/rust-lang/rust/commits?author=bors");
  1022. match self.json(req).await {
  1023. Ok(r) => r,
  1024. Err(e) => {
  1025. log::error!("Failed to query commit list: {:?}", e);
  1026. Vec::new()
  1027. }
  1028. }
  1029. }
  1030. }
  1031. #[derive(Debug, serde::Deserialize)]
  1032. pub struct GithubCommit {
  1033. pub sha: String,
  1034. pub commit: GitCommit,
  1035. pub parents: Vec<Parent>,
  1036. }
  1037. #[derive(Debug, serde::Deserialize)]
  1038. pub struct GitCommit {
  1039. pub author: GitUser,
  1040. }
  1041. #[derive(Debug, serde::Deserialize)]
  1042. pub struct GitUser {
  1043. pub date: DateTime<FixedOffset>,
  1044. }
  1045. #[derive(Debug, serde::Deserialize)]
  1046. pub struct Parent {
  1047. pub sha: String,
  1048. }