github.rs 42 KB

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