github.rs 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726
  1. use anyhow::{anyhow, Context};
  2. use async_trait::async_trait;
  3. use bytes::Bytes;
  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::collections::{HashMap, HashSet};
  11. use std::convert::TryInto;
  12. use std::{
  13. fmt,
  14. time::{Duration, SystemTime},
  15. };
  16. use tracing as log;
  17. #[derive(Debug, PartialEq, Eq, serde::Deserialize)]
  18. pub struct User {
  19. pub login: String,
  20. pub id: Option<i64>,
  21. }
  22. impl GithubClient {
  23. async fn send_req(&self, req: RequestBuilder) -> anyhow::Result<(Bytes, String)> {
  24. const MAX_ATTEMPTS: usize = 2;
  25. log::debug!("send_req with {:?}", req);
  26. let req_dbg = format!("{:?}", req);
  27. let req = req
  28. .build()
  29. .with_context(|| format!("building reqwest {}", req_dbg))?;
  30. let mut resp = self.client.execute(req.try_clone().unwrap()).await?;
  31. if let Some(sleep) = Self::needs_retry(&resp).await {
  32. resp = self.retry(req, sleep, MAX_ATTEMPTS).await?;
  33. }
  34. let maybe_err = resp.error_for_status_ref().err();
  35. let body = resp
  36. .bytes()
  37. .await
  38. .with_context(|| format!("failed to read response body {req_dbg}"))?;
  39. if let Some(e) = maybe_err {
  40. return Err(anyhow::Error::new(e))
  41. .with_context(|| format!("response: {}", String::from_utf8_lossy(&body)));
  42. }
  43. Ok((body, req_dbg))
  44. }
  45. async fn needs_retry(resp: &Response) -> Option<Duration> {
  46. const REMAINING: &str = "X-RateLimit-Remaining";
  47. const RESET: &str = "X-RateLimit-Reset";
  48. if resp.status().is_success() {
  49. return None;
  50. }
  51. let headers = resp.headers();
  52. if !(headers.contains_key(REMAINING) && headers.contains_key(RESET)) {
  53. return None;
  54. }
  55. // Weird github api behavior. It asks us to retry but also has a remaining count above 1
  56. // Try again immediately and hope for the best...
  57. if headers[REMAINING] != "0" {
  58. return Some(Duration::from_secs(0));
  59. }
  60. let reset_time = headers[RESET].to_str().unwrap().parse::<u64>().unwrap();
  61. Some(Duration::from_secs(Self::calc_sleep(reset_time) + 10))
  62. }
  63. fn calc_sleep(reset_time: u64) -> u64 {
  64. let epoch_time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs();
  65. reset_time.saturating_sub(epoch_time)
  66. }
  67. fn retry(
  68. &self,
  69. req: Request,
  70. sleep: Duration,
  71. remaining_attempts: usize,
  72. ) -> BoxFuture<Result<Response, reqwest::Error>> {
  73. #[derive(Debug, serde::Deserialize)]
  74. struct RateLimit {
  75. #[allow(unused)]
  76. pub limit: u64,
  77. pub remaining: u64,
  78. pub reset: u64,
  79. }
  80. #[derive(Debug, serde::Deserialize)]
  81. struct RateLimitResponse {
  82. pub resources: Resources,
  83. }
  84. #[derive(Debug, serde::Deserialize)]
  85. struct Resources {
  86. pub core: RateLimit,
  87. pub search: RateLimit,
  88. #[allow(unused)]
  89. pub graphql: RateLimit,
  90. #[allow(unused)]
  91. pub source_import: RateLimit,
  92. }
  93. log::warn!(
  94. "Retrying after {} seconds, remaining attepts {}",
  95. sleep.as_secs(),
  96. remaining_attempts,
  97. );
  98. async move {
  99. tokio::time::sleep(sleep).await;
  100. // check rate limit
  101. let rate_resp = self
  102. .client
  103. .execute(
  104. self.client
  105. .get(&format!("{}/rate_limit", self.api_url))
  106. .configure(self)
  107. .build()
  108. .unwrap(),
  109. )
  110. .await?;
  111. rate_resp.error_for_status_ref()?;
  112. let rate_limit_response = rate_resp.json::<RateLimitResponse>().await?;
  113. // Check url for search path because github has different rate limits for the search api
  114. let rate_limit = if req
  115. .url()
  116. .path_segments()
  117. .map(|mut segments| matches!(segments.next(), Some("search")))
  118. .unwrap_or(false)
  119. {
  120. rate_limit_response.resources.search
  121. } else {
  122. rate_limit_response.resources.core
  123. };
  124. // If we still don't have any more remaining attempts, try sleeping for the remaining
  125. // period of time
  126. if rate_limit.remaining == 0 {
  127. let sleep = Self::calc_sleep(rate_limit.reset);
  128. if sleep > 0 {
  129. tokio::time::sleep(Duration::from_secs(sleep)).await;
  130. }
  131. }
  132. let resp = self.client.execute(req.try_clone().unwrap()).await?;
  133. if let Some(sleep) = Self::needs_retry(&resp).await {
  134. if remaining_attempts > 0 {
  135. return self.retry(req, sleep, remaining_attempts - 1).await;
  136. }
  137. }
  138. Ok(resp)
  139. }
  140. .boxed()
  141. }
  142. pub async fn json<T>(&self, req: RequestBuilder) -> anyhow::Result<T>
  143. where
  144. T: serde::de::DeserializeOwned,
  145. {
  146. let (body, _req_dbg) = self.send_req(req).await?;
  147. Ok(serde_json::from_slice(&body)?)
  148. }
  149. }
  150. impl User {
  151. pub async fn current(client: &GithubClient) -> anyhow::Result<Self> {
  152. client
  153. .json(client.get(&format!("{}/user", client.api_url)))
  154. .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. /// An indicator used to differentiate between an issue and a pull request.
  204. ///
  205. /// Some webhook events include a `pull_request` field in the Issue object,
  206. /// and some don't. GitHub does include a few fields here, but they aren't
  207. /// needed at this time (merged_at, diff_url, html_url, patch_url, url).
  208. #[derive(Debug, serde::Deserialize)]
  209. pub struct PullRequestDetails {
  210. /// This is a slot to hold the diff for a PR.
  211. ///
  212. /// This will be filled in only once as an optimization since multiple
  213. /// handlers want to see PR changes, and getting the diff can be
  214. /// expensive.
  215. #[serde(skip)]
  216. files_changed: tokio::sync::OnceCell<Vec<FileDiff>>,
  217. }
  218. /// Representation of a diff to a single file.
  219. #[derive(Debug)]
  220. pub struct FileDiff {
  221. /// The full path of the file.
  222. pub path: String,
  223. /// The diff for the file.
  224. pub diff: String,
  225. }
  226. impl PullRequestDetails {
  227. pub fn new() -> PullRequestDetails {
  228. PullRequestDetails {
  229. files_changed: tokio::sync::OnceCell::new(),
  230. }
  231. }
  232. }
  233. /// An issue or pull request.
  234. ///
  235. /// For convenience, since issues and pull requests share most of their
  236. /// fields, this struct is used for both. The `pull_request` field can be used
  237. /// to determine which it is. Some fields are only available on pull requests
  238. /// (but not always, check the GitHub API for details).
  239. #[derive(Debug, serde::Deserialize)]
  240. pub struct Issue {
  241. pub number: u64,
  242. #[serde(deserialize_with = "opt_string")]
  243. pub body: String,
  244. created_at: chrono::DateTime<Utc>,
  245. pub updated_at: chrono::DateTime<Utc>,
  246. /// The SHA for a merge commit.
  247. ///
  248. /// This field is complicated, see the [Pull Request
  249. /// docs](https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request)
  250. /// for details.
  251. #[serde(default)]
  252. pub merge_commit_sha: Option<String>,
  253. pub title: String,
  254. /// The common URL for viewing this issue or PR.
  255. ///
  256. /// Example: `https://github.com/octocat/Hello-World/pull/1347`
  257. pub html_url: String,
  258. pub user: User,
  259. pub labels: Vec<Label>,
  260. pub assignees: Vec<User>,
  261. /// Indicator if this is a pull request.
  262. ///
  263. /// This is `Some` if this is a PR (as opposed to an issue). Note that
  264. /// this does not always get filled in by GitHub, and must be manually
  265. /// populated (because some webhook events do not set it).
  266. pub pull_request: Option<PullRequestDetails>,
  267. /// Whether or not the pull request was merged.
  268. #[serde(default)]
  269. pub merged: bool,
  270. #[serde(default)]
  271. pub draft: bool,
  272. /// The API URL for discussion comments.
  273. ///
  274. /// Example: `https://api.github.com/repos/octocat/Hello-World/issues/1347/comments`
  275. comments_url: String,
  276. /// The repository for this issue.
  277. ///
  278. /// Note that this is constructed via the [`Issue::repository`] method.
  279. /// It is not deserialized from the GitHub API.
  280. #[serde(skip)]
  281. repository: OnceCell<IssueRepository>,
  282. /// The base commit for a PR (the branch of the destination repo).
  283. #[serde(default)]
  284. pub base: Option<CommitBase>,
  285. /// The head commit for a PR (the branch from the source repo).
  286. #[serde(default)]
  287. pub head: Option<CommitBase>,
  288. /// Whether it is open or closed.
  289. pub state: IssueState,
  290. }
  291. #[derive(Debug, serde::Deserialize, Eq, PartialEq)]
  292. #[serde(rename_all = "snake_case")]
  293. pub enum IssueState {
  294. Open,
  295. Closed,
  296. }
  297. /// Contains only the parts of `Issue` that are needed for turning the issue title into a Zulip
  298. /// topic.
  299. #[derive(Clone, Debug, PartialEq, Eq)]
  300. pub struct ZulipGitHubReference {
  301. pub number: u64,
  302. pub title: String,
  303. pub repository: IssueRepository,
  304. }
  305. impl ZulipGitHubReference {
  306. pub fn zulip_topic_reference(&self) -> String {
  307. let repo = &self.repository;
  308. if repo.organization == "rust-lang" {
  309. if repo.repository == "rust" {
  310. format!("#{}", self.number)
  311. } else {
  312. format!("{}#{}", repo.repository, self.number)
  313. }
  314. } else {
  315. format!("{}/{}#{}", repo.organization, repo.repository, self.number)
  316. }
  317. }
  318. }
  319. #[derive(Debug, serde::Deserialize)]
  320. pub struct Comment {
  321. #[serde(deserialize_with = "opt_string")]
  322. pub body: String,
  323. pub html_url: String,
  324. pub user: User,
  325. #[serde(alias = "submitted_at")] // for pull request reviews
  326. pub updated_at: chrono::DateTime<Utc>,
  327. #[serde(default, rename = "state")]
  328. pub pr_review_state: Option<PullRequestReviewState>,
  329. }
  330. #[derive(Debug, serde::Deserialize, Eq, PartialEq)]
  331. #[serde(rename_all = "snake_case")]
  332. pub enum PullRequestReviewState {
  333. Approved,
  334. ChangesRequested,
  335. Commented,
  336. Dismissed,
  337. Pending,
  338. }
  339. fn opt_string<'de, D>(deserializer: D) -> Result<String, D::Error>
  340. where
  341. D: serde::de::Deserializer<'de>,
  342. {
  343. use serde::de::Deserialize;
  344. match <Option<String>>::deserialize(deserializer) {
  345. Ok(v) => Ok(v.unwrap_or_default()),
  346. Err(e) => Err(e),
  347. }
  348. }
  349. #[derive(Debug)]
  350. pub enum AssignmentError {
  351. InvalidAssignee,
  352. Http(anyhow::Error),
  353. }
  354. #[derive(Debug)]
  355. pub enum Selection<'a, T: ?Sized> {
  356. All,
  357. One(&'a T),
  358. Except(&'a T),
  359. }
  360. impl fmt::Display for AssignmentError {
  361. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  362. match self {
  363. AssignmentError::InvalidAssignee => write!(f, "invalid assignee"),
  364. AssignmentError::Http(e) => write!(f, "cannot assign: {}", e),
  365. }
  366. }
  367. }
  368. impl std::error::Error for AssignmentError {}
  369. #[derive(Debug, Clone, PartialEq, Eq)]
  370. pub struct IssueRepository {
  371. pub organization: String,
  372. pub repository: String,
  373. }
  374. impl fmt::Display for IssueRepository {
  375. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  376. write!(f, "{}/{}", self.organization, self.repository)
  377. }
  378. }
  379. impl IssueRepository {
  380. fn url(&self, client: &GithubClient) -> String {
  381. format!(
  382. "{}/repos/{}/{}",
  383. client.api_url, self.organization, self.repository
  384. )
  385. }
  386. fn full_repo_name(&self) -> String {
  387. format!("{}/{}", self.organization, self.repository)
  388. }
  389. async fn has_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<bool> {
  390. #[allow(clippy::redundant_pattern_matching)]
  391. let url = format!("{}/labels/{}", self.url(client), label);
  392. match client.send_req(client.get(&url)).await {
  393. Ok(_) => Ok(true),
  394. Err(e) => {
  395. if e.downcast_ref::<reqwest::Error>()
  396. .map_or(false, |e| e.status() == Some(StatusCode::NOT_FOUND))
  397. {
  398. Ok(false)
  399. } else {
  400. Err(e)
  401. }
  402. }
  403. }
  404. }
  405. }
  406. #[derive(Debug)]
  407. pub(crate) struct UnknownLabels {
  408. labels: Vec<String>,
  409. }
  410. // NOTE: This is used to post the Github comment; make sure it's valid markdown.
  411. impl fmt::Display for UnknownLabels {
  412. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  413. write!(f, "Unknown labels: {}", &self.labels.join(", "))
  414. }
  415. }
  416. impl std::error::Error for UnknownLabels {}
  417. impl Issue {
  418. pub fn to_zulip_github_reference(&self) -> ZulipGitHubReference {
  419. ZulipGitHubReference {
  420. number: self.number,
  421. title: self.title.clone(),
  422. repository: self.repository().clone(),
  423. }
  424. }
  425. pub fn repository(&self) -> &IssueRepository {
  426. self.repository.get_or_init(|| {
  427. // https://api.github.com/repos/rust-lang/rust/issues/69257/comments
  428. log::trace!("get repository for {}", self.comments_url);
  429. let url = url::Url::parse(&self.comments_url).unwrap();
  430. let mut segments = url.path_segments().unwrap();
  431. let _comments = segments.next_back().unwrap();
  432. let _number = segments.next_back().unwrap();
  433. let _issues_or_prs = segments.next_back().unwrap();
  434. let repository = segments.next_back().unwrap();
  435. let organization = segments.next_back().unwrap();
  436. IssueRepository {
  437. organization: organization.into(),
  438. repository: repository.into(),
  439. }
  440. })
  441. }
  442. pub fn global_id(&self) -> String {
  443. format!("{}#{}", self.repository(), self.number)
  444. }
  445. pub fn is_pr(&self) -> bool {
  446. self.pull_request.is_some()
  447. }
  448. pub fn is_open(&self) -> bool {
  449. self.state == IssueState::Open
  450. }
  451. pub async fn get_comment(&self, client: &GithubClient, id: usize) -> anyhow::Result<Comment> {
  452. let comment_url = format!("{}/issues/comments/{}", self.repository().url(client), id);
  453. let comment = client.json(client.get(&comment_url)).await?;
  454. Ok(comment)
  455. }
  456. // returns an array of one element
  457. pub async fn get_first_comment(&self, client: &GithubClient) -> anyhow::Result<Vec<Comment>> {
  458. let comment_url = format!(
  459. "{}/issues/{}/comments?page=1&per_page=1",
  460. self.repository().url(client),
  461. self.number,
  462. );
  463. Ok(client
  464. .json::<Vec<Comment>>(client.get(&comment_url))
  465. .await?)
  466. }
  467. // returns an array of one element
  468. pub async fn get_first100_comments(
  469. &self,
  470. client: &GithubClient,
  471. ) -> anyhow::Result<Vec<Comment>> {
  472. let comment_url = format!(
  473. "{}/issues/{}/comments?page=1&per_page=100",
  474. self.repository().url(client),
  475. self.number,
  476. );
  477. Ok(client
  478. .json::<Vec<Comment>>(client.get(&comment_url))
  479. .await?)
  480. }
  481. pub async fn edit_body(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  482. let edit_url = format!("{}/issues/{}", self.repository().url(client), self.number);
  483. #[derive(serde::Serialize)]
  484. struct ChangedIssue<'a> {
  485. body: &'a str,
  486. }
  487. client
  488. .send_req(client.patch(&edit_url).json(&ChangedIssue { body }))
  489. .await
  490. .context("failed to edit issue body")?;
  491. Ok(())
  492. }
  493. pub async fn edit_comment(
  494. &self,
  495. client: &GithubClient,
  496. id: usize,
  497. new_body: &str,
  498. ) -> anyhow::Result<()> {
  499. let comment_url = format!("{}/issues/comments/{}", self.repository().url(client), id);
  500. #[derive(serde::Serialize)]
  501. struct NewComment<'a> {
  502. body: &'a str,
  503. }
  504. client
  505. .send_req(
  506. client
  507. .patch(&comment_url)
  508. .json(&NewComment { body: new_body }),
  509. )
  510. .await
  511. .context("failed to edit comment")?;
  512. Ok(())
  513. }
  514. pub async fn post_comment(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
  515. #[derive(serde::Serialize)]
  516. struct PostComment<'a> {
  517. body: &'a str,
  518. }
  519. let comments_path = self
  520. .comments_url
  521. .strip_prefix("https://api.github.com")
  522. .expect("expected api host");
  523. let comments_url = format!("{}{comments_path}", client.api_url);
  524. client
  525. .send_req(client.post(&comments_url).json(&PostComment { body }))
  526. .await
  527. .context("failed to post comment")?;
  528. Ok(())
  529. }
  530. pub async fn remove_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<()> {
  531. log::info!("remove_label from {}: {:?}", self.global_id(), label);
  532. // DELETE /repos/:owner/:repo/issues/:number/labels/{name}
  533. let url = format!(
  534. "{repo_url}/issues/{number}/labels/{name}",
  535. repo_url = self.repository().url(client),
  536. number = self.number,
  537. name = label,
  538. );
  539. if !self.labels().iter().any(|l| l.name == label) {
  540. log::info!(
  541. "remove_label from {}: {:?} already not present, skipping",
  542. self.global_id(),
  543. label
  544. );
  545. return Ok(());
  546. }
  547. client
  548. .send_req(client.delete(&url))
  549. .await
  550. .context("failed to delete label")?;
  551. Ok(())
  552. }
  553. pub async fn add_labels(
  554. &self,
  555. client: &GithubClient,
  556. labels: Vec<Label>,
  557. ) -> anyhow::Result<()> {
  558. log::info!("add_labels: {} +{:?}", self.global_id(), labels);
  559. // POST /repos/:owner/:repo/issues/:number/labels
  560. // repo_url = https://api.github.com/repos/Codertocat/Hello-World
  561. let url = format!(
  562. "{repo_url}/issues/{number}/labels",
  563. repo_url = self.repository().url(client),
  564. number = self.number
  565. );
  566. // Don't try to add labels already present on this issue.
  567. let labels = labels
  568. .into_iter()
  569. .filter(|l| !self.labels().contains(&l))
  570. .map(|l| l.name)
  571. .collect::<Vec<_>>();
  572. log::info!("add_labels: {} filtered to {:?}", self.global_id(), labels);
  573. if labels.is_empty() {
  574. return Ok(());
  575. }
  576. let mut unknown_labels = vec![];
  577. let mut known_labels = vec![];
  578. for label in labels {
  579. if !self.repository().has_label(client, &label).await? {
  580. unknown_labels.push(label);
  581. } else {
  582. known_labels.push(label);
  583. }
  584. }
  585. if !unknown_labels.is_empty() {
  586. return Err(UnknownLabels {
  587. labels: unknown_labels,
  588. }
  589. .into());
  590. }
  591. #[derive(serde::Serialize)]
  592. struct LabelsReq {
  593. labels: Vec<String>,
  594. }
  595. client
  596. .send_req(client.post(&url).json(&LabelsReq {
  597. labels: known_labels,
  598. }))
  599. .await
  600. .context("failed to add labels")?;
  601. Ok(())
  602. }
  603. pub fn labels(&self) -> &[Label] {
  604. &self.labels
  605. }
  606. pub fn contain_assignee(&self, user: &str) -> bool {
  607. self.assignees
  608. .iter()
  609. .any(|a| a.login.to_lowercase() == user.to_lowercase())
  610. }
  611. pub async fn remove_assignees(
  612. &self,
  613. client: &GithubClient,
  614. selection: Selection<'_, str>,
  615. ) -> Result<(), AssignmentError> {
  616. log::info!("remove {:?} assignees for {}", selection, self.global_id());
  617. let url = format!(
  618. "{repo_url}/issues/{number}/assignees",
  619. repo_url = self.repository().url(client),
  620. number = self.number
  621. );
  622. let assignees = match selection {
  623. Selection::All => self
  624. .assignees
  625. .iter()
  626. .map(|u| u.login.as_str())
  627. .collect::<Vec<_>>(),
  628. Selection::One(user) => vec![user],
  629. Selection::Except(user) => self
  630. .assignees
  631. .iter()
  632. .map(|u| u.login.as_str())
  633. .filter(|&u| u.to_lowercase() != user.to_lowercase())
  634. .collect::<Vec<_>>(),
  635. };
  636. #[derive(serde::Serialize)]
  637. struct AssigneeReq<'a> {
  638. assignees: &'a [&'a str],
  639. }
  640. client
  641. .send_req(client.delete(&url).json(&AssigneeReq {
  642. assignees: &assignees[..],
  643. }))
  644. .await
  645. .map_err(AssignmentError::Http)?;
  646. Ok(())
  647. }
  648. pub async fn add_assignee(
  649. &self,
  650. client: &GithubClient,
  651. user: &str,
  652. ) -> Result<(), AssignmentError> {
  653. log::info!("add_assignee {} for {}", user, self.global_id());
  654. let url = format!(
  655. "{repo_url}/issues/{number}/assignees",
  656. repo_url = self.repository().url(client),
  657. number = self.number
  658. );
  659. #[derive(serde::Serialize)]
  660. struct AssigneeReq<'a> {
  661. assignees: &'a [&'a str],
  662. }
  663. let result: Issue = client
  664. .json(client.post(&url).json(&AssigneeReq { assignees: &[user] }))
  665. .await
  666. .map_err(AssignmentError::Http)?;
  667. // Invalid assignees are silently ignored. We can just check if the user is now
  668. // contained in the assignees list.
  669. let success = result
  670. .assignees
  671. .iter()
  672. .any(|u| u.login.as_str().to_lowercase() == user.to_lowercase());
  673. if success {
  674. Ok(())
  675. } else {
  676. Err(AssignmentError::InvalidAssignee)
  677. }
  678. }
  679. pub async fn set_assignee(
  680. &self,
  681. client: &GithubClient,
  682. user: &str,
  683. ) -> Result<(), AssignmentError> {
  684. log::info!("set_assignee for {} to {}", self.global_id(), user);
  685. self.add_assignee(client, user).await?;
  686. self.remove_assignees(client, Selection::Except(user))
  687. .await?;
  688. Ok(())
  689. }
  690. /// Sets the milestone of the issue or PR.
  691. ///
  692. /// This will create the milestone if it does not exist. The new milestone
  693. /// will start in the "open" state.
  694. pub async fn set_milestone(&self, client: &GithubClient, title: &str) -> anyhow::Result<()> {
  695. log::trace!(
  696. "Setting milestone for rust-lang/rust#{} to {}",
  697. self.number,
  698. title
  699. );
  700. let full_repo_name = self.repository().full_repo_name();
  701. let milestone = client
  702. .get_or_create_milestone(&full_repo_name, title, "open")
  703. .await?;
  704. client
  705. .set_milestone(&full_repo_name, &milestone, self.number)
  706. .await?;
  707. Ok(())
  708. }
  709. pub async fn close(&self, client: &GithubClient) -> anyhow::Result<()> {
  710. let edit_url = format!("{}/issues/{}", self.repository().url(client), self.number);
  711. #[derive(serde::Serialize)]
  712. struct CloseIssue<'a> {
  713. state: &'a str,
  714. }
  715. client
  716. .send_req(
  717. client
  718. .patch(&edit_url)
  719. .json(&CloseIssue { state: "closed" }),
  720. )
  721. .await
  722. .context("failed to close issue")?;
  723. Ok(())
  724. }
  725. /// Returns the diff in this event, for Open and Synchronize events for now.
  726. ///
  727. /// Returns `None` if the issue is not a PR.
  728. pub async fn diff(&self, client: &GithubClient) -> anyhow::Result<Option<&[FileDiff]>> {
  729. let Some(pr) = &self.pull_request else {
  730. return Ok(None);
  731. };
  732. let (before, after) = if let (Some(base), Some(head)) = (&self.base, &self.head) {
  733. (&base.sha, &head.sha)
  734. } else {
  735. return Ok(None);
  736. };
  737. let diff = pr
  738. .files_changed
  739. .get_or_try_init::<anyhow::Error, _, _>(|| async move {
  740. let url = format!(
  741. "{}/compare/{before}...{after}",
  742. self.repository().url(client)
  743. );
  744. let mut req = client.get(&url);
  745. req = req.header("Accept", "application/vnd.github.v3.diff");
  746. let (diff, _) = client
  747. .send_req(req)
  748. .await
  749. .with_context(|| format!("failed to fetch diff comparison for {url}"))?;
  750. let body = String::from_utf8_lossy(&diff);
  751. Ok(parse_diff(&body))
  752. })
  753. .await?;
  754. Ok(Some(diff))
  755. }
  756. /// Returns the commits from this pull request (no commits are returned if this `Issue` is not
  757. /// a pull request).
  758. pub async fn commits(&self, client: &GithubClient) -> anyhow::Result<Vec<GithubCommit>> {
  759. if !self.is_pr() {
  760. return Ok(vec![]);
  761. }
  762. let mut commits = Vec::new();
  763. let mut page = 1;
  764. loop {
  765. let req = client.get(&format!(
  766. "{}/pulls/{}/commits?page={page}&per_page=100",
  767. self.repository().url(client),
  768. self.number
  769. ));
  770. let new: Vec<_> = client.json(req).await?;
  771. if new.is_empty() {
  772. break;
  773. }
  774. commits.extend(new);
  775. page += 1;
  776. }
  777. Ok(commits)
  778. }
  779. pub async fn files(&self, client: &GithubClient) -> anyhow::Result<Vec<PullRequestFile>> {
  780. if !self.is_pr() {
  781. return Ok(vec![]);
  782. }
  783. let req = client.get(&format!(
  784. "{}/pulls/{}/files",
  785. self.repository().url(client),
  786. self.number
  787. ));
  788. Ok(client.json(req).await?)
  789. }
  790. }
  791. #[derive(Debug, serde::Deserialize)]
  792. pub struct PullRequestFile {
  793. pub sha: String,
  794. pub filename: String,
  795. pub blob_url: String,
  796. }
  797. #[derive(Debug, serde::Deserialize)]
  798. pub struct Milestone {
  799. number: u64,
  800. title: String,
  801. }
  802. #[derive(Debug, serde::Deserialize)]
  803. pub struct ChangeInner {
  804. pub from: String,
  805. }
  806. #[derive(Debug, serde::Deserialize)]
  807. pub struct Changes {
  808. pub title: Option<ChangeInner>,
  809. pub body: Option<ChangeInner>,
  810. }
  811. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  812. #[serde(rename_all = "lowercase")]
  813. pub enum PullRequestReviewAction {
  814. Submitted,
  815. Edited,
  816. Dismissed,
  817. }
  818. /// A pull request review event.
  819. ///
  820. /// <https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#pull_request_review>
  821. #[derive(Debug, serde::Deserialize)]
  822. pub struct PullRequestReviewEvent {
  823. pub action: PullRequestReviewAction,
  824. pub pull_request: Issue,
  825. pub review: Comment,
  826. pub changes: Option<Changes>,
  827. pub repository: Repository,
  828. }
  829. #[derive(Debug, serde::Deserialize)]
  830. pub struct PullRequestReviewComment {
  831. pub action: IssueCommentAction,
  832. pub changes: Option<Changes>,
  833. #[serde(rename = "pull_request")]
  834. pub issue: Issue,
  835. pub comment: Comment,
  836. pub repository: Repository,
  837. }
  838. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  839. #[serde(rename_all = "lowercase")]
  840. pub enum IssueCommentAction {
  841. Created,
  842. Edited,
  843. Deleted,
  844. }
  845. #[derive(Debug, serde::Deserialize)]
  846. pub struct IssueCommentEvent {
  847. pub action: IssueCommentAction,
  848. pub changes: Option<Changes>,
  849. pub issue: Issue,
  850. pub comment: Comment,
  851. pub repository: Repository,
  852. }
  853. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  854. #[serde(rename_all = "snake_case", tag = "action")]
  855. pub enum IssuesAction {
  856. Opened,
  857. Edited,
  858. Deleted,
  859. Transferred,
  860. Pinned,
  861. Unpinned,
  862. Closed,
  863. Reopened,
  864. Assigned,
  865. Unassigned,
  866. Labeled {
  867. /// The label added from the issue
  868. label: Label,
  869. },
  870. Unlabeled {
  871. /// The label removed from the issue
  872. label: Label,
  873. },
  874. Locked,
  875. Unlocked,
  876. Milestoned,
  877. Demilestoned,
  878. ReviewRequested {
  879. /// The person requested to review the pull request
  880. requested_reviewer: User,
  881. },
  882. ReviewRequestRemoved,
  883. ReadyForReview,
  884. Synchronize,
  885. ConvertedToDraft,
  886. AutoMergeEnabled,
  887. AutoMergeDisabled,
  888. }
  889. #[derive(Debug, serde::Deserialize)]
  890. pub struct IssuesEvent {
  891. #[serde(flatten)]
  892. pub action: IssuesAction,
  893. #[serde(alias = "pull_request")]
  894. pub issue: Issue,
  895. pub changes: Option<Changes>,
  896. pub repository: Repository,
  897. /// The GitHub user that triggered the event.
  898. pub sender: User,
  899. }
  900. #[derive(Debug, serde::Deserialize)]
  901. struct PullRequestEventFields {}
  902. #[derive(Clone, Debug, serde::Deserialize)]
  903. pub struct CommitBase {
  904. pub sha: String,
  905. #[serde(rename = "ref")]
  906. pub git_ref: String,
  907. pub repo: Repository,
  908. }
  909. pub fn parse_diff(diff: &str) -> Vec<FileDiff> {
  910. // This does not properly handle filenames with spaces.
  911. let re = regex::Regex::new("(?m)^diff --git .* b/(.*)").unwrap();
  912. let mut files: Vec<_> = re
  913. .captures_iter(diff)
  914. .map(|cap| {
  915. let start = cap.get(0).unwrap().start();
  916. let path = cap.get(1).unwrap().as_str().to_string();
  917. (start, path)
  918. })
  919. .collect();
  920. // Break the list up into (start, end) pairs starting from the "diff --git" line.
  921. files.push((diff.len(), String::new()));
  922. files
  923. .windows(2)
  924. .map(|w| {
  925. let (start, end) = (&w[0], &w[1]);
  926. FileDiff {
  927. path: start.1.clone(),
  928. diff: diff[start.0..end.0].to_string(),
  929. }
  930. })
  931. .collect()
  932. }
  933. #[derive(Debug, serde::Deserialize)]
  934. pub struct IssueSearchResult {
  935. pub total_count: usize,
  936. pub incomplete_results: bool,
  937. pub items: Vec<Issue>,
  938. }
  939. #[derive(Clone, Debug, serde::Deserialize)]
  940. pub struct Repository {
  941. pub full_name: String,
  942. pub default_branch: String,
  943. #[serde(default)]
  944. pub fork: bool,
  945. pub parent: Option<Box<Repository>>,
  946. }
  947. #[derive(Copy, Clone)]
  948. struct Ordering<'a> {
  949. pub sort: &'a str,
  950. pub direction: &'a str,
  951. pub per_page: &'a str,
  952. pub page: usize,
  953. }
  954. impl Repository {
  955. fn url(&self, client: &GithubClient) -> String {
  956. format!("{}/repos/{}", client.api_url, self.full_name)
  957. }
  958. pub fn owner(&self) -> &str {
  959. self.full_name.split_once('/').unwrap().0
  960. }
  961. pub fn name(&self) -> &str {
  962. self.full_name.split_once('/').unwrap().1
  963. }
  964. pub async fn get_issues<'a>(
  965. &self,
  966. client: &GithubClient,
  967. query: &Query<'a>,
  968. ) -> anyhow::Result<Vec<Issue>> {
  969. let Query {
  970. filters,
  971. include_labels,
  972. exclude_labels,
  973. } = query;
  974. let mut ordering = Ordering {
  975. sort: "created",
  976. direction: "asc",
  977. per_page: "100",
  978. page: 1,
  979. };
  980. let filters: Vec<_> = filters
  981. .clone()
  982. .into_iter()
  983. .filter(|(key, val)| {
  984. match *key {
  985. "sort" => ordering.sort = val,
  986. "direction" => ordering.direction = val,
  987. "per_page" => ordering.per_page = val,
  988. _ => return true,
  989. };
  990. false
  991. })
  992. .collect();
  993. // `is: pull-request` indicates the query to retrieve PRs only
  994. let is_pr = filters
  995. .iter()
  996. .any(|&(key, value)| key == "is" && value == "pull-request");
  997. // There are some cases that can only be handled by the search API:
  998. // 1. When using negating label filters (exclude_labels)
  999. // 2. When there's a key parameter key=no
  1000. // 3. When the query is to retrieve PRs only and there are label filters
  1001. //
  1002. // Check https://docs.github.com/en/rest/reference/search#search-issues-and-pull-requests
  1003. // for more information
  1004. let use_search_api = !exclude_labels.is_empty()
  1005. || filters.iter().any(|&(key, _)| key == "no")
  1006. || is_pr && !include_labels.is_empty();
  1007. // If there are more than `per_page` of issues, we need to paginate
  1008. let mut issues = vec![];
  1009. loop {
  1010. let url = if use_search_api {
  1011. self.build_search_issues_url(
  1012. client,
  1013. &filters,
  1014. include_labels,
  1015. exclude_labels,
  1016. ordering,
  1017. )
  1018. } else if is_pr {
  1019. self.build_pulls_url(client, &filters, include_labels, ordering)
  1020. } else {
  1021. self.build_issues_url(client, &filters, include_labels, ordering)
  1022. };
  1023. let result = client.get(&url);
  1024. if use_search_api {
  1025. let result = client
  1026. .json::<IssueSearchResult>(result)
  1027. .await
  1028. .with_context(|| format!("failed to list issues from {}", url))?;
  1029. issues.extend(result.items);
  1030. if issues.len() < result.total_count {
  1031. ordering.page += 1;
  1032. continue;
  1033. }
  1034. } else {
  1035. // FIXME: paginate with non-search
  1036. issues = client
  1037. .json(result)
  1038. .await
  1039. .with_context(|| format!("failed to list issues from {}", url))?
  1040. }
  1041. break;
  1042. }
  1043. Ok(issues)
  1044. }
  1045. fn build_issues_url(
  1046. &self,
  1047. client: &GithubClient,
  1048. filters: &Vec<(&str, &str)>,
  1049. include_labels: &Vec<&str>,
  1050. ordering: Ordering<'_>,
  1051. ) -> String {
  1052. self.build_endpoint_url(client, "issues", filters, include_labels, ordering)
  1053. }
  1054. fn build_pulls_url(
  1055. &self,
  1056. client: &GithubClient,
  1057. filters: &Vec<(&str, &str)>,
  1058. include_labels: &Vec<&str>,
  1059. ordering: Ordering<'_>,
  1060. ) -> String {
  1061. self.build_endpoint_url(client, "pulls", filters, include_labels, ordering)
  1062. }
  1063. fn build_endpoint_url(
  1064. &self,
  1065. client: &GithubClient,
  1066. endpoint: &str,
  1067. filters: &Vec<(&str, &str)>,
  1068. include_labels: &Vec<&str>,
  1069. ordering: Ordering<'_>,
  1070. ) -> String {
  1071. let filters = filters
  1072. .iter()
  1073. .map(|(key, val)| format!("{}={}", key, val))
  1074. .chain(std::iter::once(format!(
  1075. "labels={}",
  1076. include_labels.join(",")
  1077. )))
  1078. .chain(std::iter::once("filter=all".to_owned()))
  1079. .chain(std::iter::once(format!("sort={}", ordering.sort,)))
  1080. .chain(std::iter::once(
  1081. format!("direction={}", ordering.direction,),
  1082. ))
  1083. .chain(std::iter::once(format!("per_page={}", ordering.per_page,)))
  1084. .collect::<Vec<_>>()
  1085. .join("&");
  1086. format!(
  1087. "{}/repos/{}/{}?{}",
  1088. client.api_url, self.full_name, endpoint, filters
  1089. )
  1090. }
  1091. fn build_search_issues_url(
  1092. &self,
  1093. client: &GithubClient,
  1094. filters: &Vec<(&str, &str)>,
  1095. include_labels: &Vec<&str>,
  1096. exclude_labels: &Vec<&str>,
  1097. ordering: Ordering<'_>,
  1098. ) -> String {
  1099. let filters = filters
  1100. .iter()
  1101. .filter(|&&(key, val)| !(key == "state" && val == "all"))
  1102. .map(|(key, val)| format!("{}:{}", key, val))
  1103. .chain(
  1104. include_labels
  1105. .iter()
  1106. .map(|label| format!("label:{}", label)),
  1107. )
  1108. .chain(
  1109. exclude_labels
  1110. .iter()
  1111. .map(|label| format!("-label:{}", label)),
  1112. )
  1113. .chain(std::iter::once(format!("repo:{}", self.full_name)))
  1114. .collect::<Vec<_>>()
  1115. .join("+");
  1116. format!(
  1117. "{}/search/issues?q={}&sort={}&order={}&per_page={}&page={}",
  1118. client.api_url,
  1119. filters,
  1120. ordering.sort,
  1121. ordering.direction,
  1122. ordering.per_page,
  1123. ordering.page,
  1124. )
  1125. }
  1126. /// Returns a list of commits between the SHA ranges of start (exclusive)
  1127. /// and end (inclusive).
  1128. pub async fn commits_in_range(
  1129. &self,
  1130. client: &GithubClient,
  1131. start: &str,
  1132. end: &str,
  1133. ) -> anyhow::Result<Vec<GithubCommit>> {
  1134. let mut commits = Vec::new();
  1135. let mut page = 1;
  1136. loop {
  1137. let url = format!(
  1138. "{}/commits?sha={end}&per_page=100&page={page}",
  1139. self.url(client)
  1140. );
  1141. let mut this_page: Vec<GithubCommit> = client
  1142. .json(client.get(&url))
  1143. .await
  1144. .with_context(|| format!("failed to fetch commits for {url}"))?;
  1145. if let Some(idx) = this_page.iter().position(|commit| commit.sha == start) {
  1146. this_page.truncate(idx);
  1147. commits.extend(this_page);
  1148. return Ok(commits);
  1149. } else {
  1150. commits.extend(this_page);
  1151. }
  1152. page += 1;
  1153. }
  1154. }
  1155. /// Retrieves a git commit for the given SHA.
  1156. pub async fn git_commit(&self, client: &GithubClient, sha: &str) -> anyhow::Result<GitCommit> {
  1157. let url = format!("{}/git/commits/{sha}", self.url(client));
  1158. client
  1159. .json(client.get(&url))
  1160. .await
  1161. .with_context(|| format!("{} failed to get git commit {sha}", self.full_name))
  1162. }
  1163. /// Creates a new commit.
  1164. pub async fn create_commit(
  1165. &self,
  1166. client: &GithubClient,
  1167. message: &str,
  1168. parents: &[&str],
  1169. tree: &str,
  1170. ) -> anyhow::Result<GitCommit> {
  1171. let url = format!("{}/git/commits", self.url(client));
  1172. client
  1173. .json(client.post(&url).json(&serde_json::json!({
  1174. "message": message,
  1175. "parents": parents,
  1176. "tree": tree,
  1177. })))
  1178. .await
  1179. .with_context(|| format!("{} failed to create commit for tree {tree}", self.full_name))
  1180. }
  1181. /// Retrieves a git reference for the given refname.
  1182. pub async fn get_reference(
  1183. &self,
  1184. client: &GithubClient,
  1185. refname: &str,
  1186. ) -> anyhow::Result<GitReference> {
  1187. let url = format!("{}/git/ref/{}", self.url(client), refname);
  1188. client
  1189. .json(client.get(&url))
  1190. .await
  1191. .with_context(|| format!("{} failed to get git reference {refname}", self.full_name))
  1192. }
  1193. /// Updates an existing git reference to a new SHA.
  1194. pub async fn update_reference(
  1195. &self,
  1196. client: &GithubClient,
  1197. refname: &str,
  1198. sha: &str,
  1199. ) -> anyhow::Result<GitReference> {
  1200. let url = format!("{}/git/refs/{}", self.url(client), refname);
  1201. client
  1202. .json(client.patch(&url).json(&serde_json::json!({
  1203. "sha": sha,
  1204. "force": true,
  1205. })))
  1206. .await
  1207. .with_context(|| {
  1208. format!(
  1209. "{} failed to update reference {refname} to {sha}",
  1210. self.full_name
  1211. )
  1212. })
  1213. }
  1214. /// Returns a list of recent commits on the given branch.
  1215. ///
  1216. /// Returns results in the OID range `oldest` (exclusive) to `newest`
  1217. /// (inclusive).
  1218. pub async fn recent_commits(
  1219. &self,
  1220. client: &GithubClient,
  1221. branch: &str,
  1222. oldest: &str,
  1223. newest: &str,
  1224. ) -> anyhow::Result<Vec<RecentCommit>> {
  1225. // This is used to deduplicate the results (so that a PR with multiple
  1226. // commits will only show up once).
  1227. let mut prs_seen = HashSet::new();
  1228. let mut recent_commits = Vec::new(); // This is the final result.
  1229. use cynic::QueryBuilder;
  1230. use github_graphql::docs_update_queries::{
  1231. GitObject, RecentCommits, RecentCommitsArguments,
  1232. };
  1233. let mut args = RecentCommitsArguments {
  1234. branch,
  1235. name: self.name(),
  1236. owner: self.owner(),
  1237. after: None,
  1238. };
  1239. let mut found_newest = false;
  1240. let mut found_oldest = false;
  1241. // This simulates --first-parent. We only care about top-level commits.
  1242. // Unfortunately the GitHub API doesn't provide anything like that.
  1243. let mut next_first_parent = None;
  1244. // Search for `oldest` within 3 pages (300 commits).
  1245. for _ in 0..3 {
  1246. let query = RecentCommits::build(args.clone());
  1247. let data = client
  1248. .json::<cynic::GraphQlResponse<RecentCommits>>(
  1249. client.post(&client.graphql_url).json(&query),
  1250. )
  1251. .await
  1252. .with_context(|| {
  1253. format!(
  1254. "{} failed to get recent commits branch={branch}",
  1255. self.full_name
  1256. )
  1257. })?;
  1258. if let Some(errors) = data.errors {
  1259. anyhow::bail!("There were graphql errors. {:?}", errors);
  1260. }
  1261. let target = data
  1262. .data
  1263. .ok_or_else(|| anyhow::anyhow!("No data returned."))?
  1264. .repository
  1265. .ok_or_else(|| anyhow::anyhow!("No repository."))?
  1266. .ref_
  1267. .ok_or_else(|| anyhow::anyhow!("No ref."))?
  1268. .target
  1269. .ok_or_else(|| anyhow::anyhow!("No target."))?;
  1270. let commit = match target {
  1271. GitObject::Commit(commit) => commit,
  1272. _ => anyhow::bail!("unexpected target type {target:?}"),
  1273. };
  1274. let commits = commit
  1275. .history
  1276. .nodes
  1277. .into_iter()
  1278. // Don't include anything newer than `newest`
  1279. .skip_while(|node| {
  1280. if found_newest || node.oid.0 == newest {
  1281. found_newest = true;
  1282. false
  1283. } else {
  1284. // This should only happen if there is a commit that arrives
  1285. // between the time that `update_submodules` fetches the latest
  1286. // ref, and this runs. This window should be a few seconds, so it
  1287. // should be unlikely. This warning is here in case my assumptions
  1288. // about how things work is not correct.
  1289. tracing::warn!(
  1290. "unexpected race with submodule history, newest oid={newest} skipping oid={}",
  1291. node.oid.0
  1292. );
  1293. true
  1294. }
  1295. })
  1296. // Skip nodes that aren't the first parent
  1297. .filter(|node| {
  1298. let this_first_parent = node.parents.nodes
  1299. .first()
  1300. .map(|parent| parent.oid.0.clone());
  1301. match &next_first_parent {
  1302. Some(first_parent) => {
  1303. if first_parent == &node.oid.0 {
  1304. // Found the next first parent, include it and
  1305. // set next_first_parent to look for this
  1306. // commit's first parent.
  1307. next_first_parent = this_first_parent;
  1308. true
  1309. } else {
  1310. // Still looking for the next first parent.
  1311. false
  1312. }
  1313. }
  1314. None => {
  1315. // First commit.
  1316. next_first_parent = this_first_parent;
  1317. true
  1318. }
  1319. }
  1320. })
  1321. // Stop once reached the `oldest` commit
  1322. .take_while(|node| {
  1323. if node.oid.0 == oldest {
  1324. found_oldest = true;
  1325. false
  1326. } else {
  1327. true
  1328. }
  1329. })
  1330. .filter_map(|node| {
  1331. // Determine if this is associated with a PR or not.
  1332. match node.associated_pull_requests
  1333. // Get the first PR (we only care about one)
  1334. .and_then(|mut pr| pr.nodes.pop()) {
  1335. Some(pr) => {
  1336. // Only include a PR once
  1337. if prs_seen.insert(pr.number) {
  1338. Some(RecentCommit {
  1339. pr_num: Some(pr.number),
  1340. title: pr.title,
  1341. oid: node.oid.0.clone(),
  1342. committed_date: node.committed_date,
  1343. })
  1344. } else {
  1345. None
  1346. }
  1347. }
  1348. None => {
  1349. // This is an unassociated commit, possibly
  1350. // created without a PR.
  1351. Some(RecentCommit {
  1352. pr_num: None,
  1353. title: node.message_headline,
  1354. oid: node.oid.0,
  1355. committed_date: node.committed_date,
  1356. })
  1357. }
  1358. }
  1359. });
  1360. recent_commits.extend(commits);
  1361. let page_info = commit.history.page_info;
  1362. if found_oldest || !page_info.has_next_page || page_info.end_cursor.is_none() {
  1363. break;
  1364. }
  1365. args.after = page_info.end_cursor;
  1366. }
  1367. if !found_oldest {
  1368. // This should probably do something more than log a warning, but
  1369. // I don't think it is too important at this time (the log message
  1370. // is only informational, and this should be unlikely to happen).
  1371. tracing::warn!(
  1372. "{} failed to find oldest commit sha={oldest} branch={branch}",
  1373. self.full_name
  1374. );
  1375. }
  1376. Ok(recent_commits)
  1377. }
  1378. /// Creates a new git tree based on another tree.
  1379. pub async fn update_tree(
  1380. &self,
  1381. client: &GithubClient,
  1382. base_tree: &str,
  1383. tree: &[GitTreeEntry],
  1384. ) -> anyhow::Result<GitTreeObject> {
  1385. let url = format!("{}/git/trees", self.url(client));
  1386. client
  1387. .json(client.post(&url).json(&serde_json::json!({
  1388. "base_tree": base_tree,
  1389. "tree": tree,
  1390. })))
  1391. .await
  1392. .with_context(|| {
  1393. format!(
  1394. "{} failed to update tree with base {base_tree}",
  1395. self.full_name
  1396. )
  1397. })
  1398. }
  1399. /// Returns information about the git submodule at the given path.
  1400. ///
  1401. /// `refname` is the ref to use for fetching information. If `None`, will
  1402. /// use the latest version on the default branch.
  1403. pub async fn submodule(
  1404. &self,
  1405. client: &GithubClient,
  1406. path: &str,
  1407. refname: Option<&str>,
  1408. ) -> anyhow::Result<Submodule> {
  1409. let mut url = format!("{}/contents/{}", self.url(client), path);
  1410. if let Some(refname) = refname {
  1411. url.push_str("?ref=");
  1412. url.push_str(refname);
  1413. }
  1414. client.json(client.get(&url)).await.with_context(|| {
  1415. format!(
  1416. "{} failed to get submodule path={path} refname={refname:?}",
  1417. self.full_name
  1418. )
  1419. })
  1420. }
  1421. /// Creates a new PR.
  1422. pub async fn new_pr(
  1423. &self,
  1424. client: &GithubClient,
  1425. title: &str,
  1426. head: &str,
  1427. base: &str,
  1428. body: &str,
  1429. ) -> anyhow::Result<Issue> {
  1430. let url = format!("{}/pulls", self.url(client));
  1431. let mut issue: Issue = client
  1432. .json(client.post(&url).json(&serde_json::json!({
  1433. "title": title,
  1434. "head": head,
  1435. "base": base,
  1436. "body": body,
  1437. })))
  1438. .await
  1439. .with_context(|| {
  1440. format!(
  1441. "{} failed to create a new PR head={head} base={base} title={title}",
  1442. self.full_name
  1443. )
  1444. })?;
  1445. issue.pull_request = Some(PullRequestDetails::new());
  1446. Ok(issue)
  1447. }
  1448. /// Synchronize a branch (in a forked repository) by pulling in its upstream contents.
  1449. ///
  1450. /// **Warning**: This will to a force update if there are conflicts.
  1451. pub async fn merge_upstream(&self, client: &GithubClient, branch: &str) -> anyhow::Result<()> {
  1452. let url = format!("{}/merge-upstream", self.url(client));
  1453. let merge_error = match client
  1454. .send_req(client.post(&url).json(&serde_json::json!({
  1455. "branch": branch,
  1456. })))
  1457. .await
  1458. {
  1459. Ok(_) => return Ok(()),
  1460. Err(e) => {
  1461. if e.downcast_ref::<reqwest::Error>().map_or(false, |e| {
  1462. matches!(
  1463. e.status(),
  1464. Some(StatusCode::UNPROCESSABLE_ENTITY | StatusCode::CONFLICT)
  1465. )
  1466. }) {
  1467. e
  1468. } else {
  1469. return Err(e);
  1470. }
  1471. }
  1472. };
  1473. // 409 is a clear error that there is a merge conflict.
  1474. // However, I don't understand how/why 422 might happen. The docs don't really say.
  1475. // The gh cli falls back to trying to force a sync, so let's try that.
  1476. log::info!(
  1477. "{} failed to merge upstream branch {branch}, trying force sync: {merge_error:?}",
  1478. self.full_name
  1479. );
  1480. let parent = self.parent.as_ref().ok_or_else(|| {
  1481. anyhow::anyhow!(
  1482. "{} failed to merge upstream branch {branch}, \
  1483. force sync could not determine parent",
  1484. self.full_name
  1485. )
  1486. })?;
  1487. // Note: I'm not sure how to handle the case where the branch name
  1488. // differs to the upstream. For example, if I create a branch off
  1489. // master in my fork, somehow GitHub knows that my branch should push
  1490. // to upstream/master (not upstream/my-branch-name). I can't find a
  1491. // way to find that branch name. Perhaps GitHub assumes it is the
  1492. // default branch if there is no matching branch name?
  1493. let branch_ref = format!("heads/{branch}");
  1494. let latest_parent_commit = parent
  1495. .get_reference(client, &branch_ref)
  1496. .await
  1497. .with_context(|| {
  1498. format!(
  1499. "failed to get head branch {branch} when merging upstream to {}",
  1500. self.full_name
  1501. )
  1502. })?;
  1503. let sha = latest_parent_commit.object.sha;
  1504. self.update_reference(client, &branch_ref, &sha)
  1505. .await
  1506. .with_context(|| {
  1507. format!(
  1508. "failed to force update {branch} to {sha} for {}",
  1509. self.full_name
  1510. )
  1511. })?;
  1512. Ok(())
  1513. }
  1514. /// Get or create a [`Milestone`].
  1515. ///
  1516. /// This will not change the state if it already exists.
  1517. pub async fn get_or_create_milestone(
  1518. &self,
  1519. client: &GithubClient,
  1520. title: &str,
  1521. state: &str,
  1522. ) -> anyhow::Result<Milestone> {
  1523. client
  1524. .get_or_create_milestone(&self.full_name, title, state)
  1525. .await
  1526. }
  1527. /// Set the milestone of an issue or PR.
  1528. pub async fn set_milestone(
  1529. &self,
  1530. client: &GithubClient,
  1531. milestone: &Milestone,
  1532. issue_num: u64,
  1533. ) -> anyhow::Result<()> {
  1534. client
  1535. .set_milestone(&self.full_name, milestone, issue_num)
  1536. .await
  1537. }
  1538. pub async fn get_issue(&self, client: &GithubClient, issue_num: u64) -> anyhow::Result<Issue> {
  1539. let url = format!("{}/pulls/{issue_num}", self.url(client));
  1540. client
  1541. .json(client.get(&url))
  1542. .await
  1543. .with_context(|| format!("{} failed to get issue {issue_num}", self.full_name))
  1544. }
  1545. }
  1546. pub struct Query<'a> {
  1547. // key/value filter
  1548. pub filters: Vec<(&'a str, &'a str)>,
  1549. pub include_labels: Vec<&'a str>,
  1550. pub exclude_labels: Vec<&'a str>,
  1551. }
  1552. fn quote_reply(markdown: &str) -> String {
  1553. if markdown.is_empty() {
  1554. String::from("*No content*")
  1555. } else {
  1556. format!("\n\t> {}", markdown.replace("\n", "\n\t> "))
  1557. }
  1558. }
  1559. #[async_trait]
  1560. impl<'q> IssuesQuery for Query<'q> {
  1561. async fn query<'a>(
  1562. &'a self,
  1563. repo: &'a Repository,
  1564. include_fcp_details: bool,
  1565. include_mcp_details: bool,
  1566. client: &'a GithubClient,
  1567. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>> {
  1568. let issues = repo
  1569. .get_issues(&client, self)
  1570. .await
  1571. .with_context(|| "Unable to get issues.")?;
  1572. let fcp_map = if include_fcp_details {
  1573. crate::rfcbot::get_all_fcps().await?
  1574. } else {
  1575. HashMap::new()
  1576. };
  1577. let mut issues_decorator = Vec::new();
  1578. let re = regex::Regex::new("https://github.com/rust-lang/|/").unwrap();
  1579. let re_zulip_link = regex::Regex::new(r"\[stream\]:\s").unwrap();
  1580. for issue in issues {
  1581. let fcp_details = if include_fcp_details {
  1582. let repository_name = if let Some(repo) = issue.repository.get() {
  1583. repo.repository.clone()
  1584. } else {
  1585. let split = re.split(&issue.html_url).collect::<Vec<&str>>();
  1586. split[1].to_string()
  1587. };
  1588. let key = format!(
  1589. "rust-lang/{}:{}:{}",
  1590. repository_name, issue.number, issue.title,
  1591. );
  1592. if let Some(fcp) = fcp_map.get(&key) {
  1593. let bot_tracking_comment_html_url = format!(
  1594. "{}#issuecomment-{}",
  1595. issue.html_url, fcp.fcp.fk_bot_tracking_comment
  1596. );
  1597. let bot_tracking_comment_content = quote_reply(&fcp.status_comment.body);
  1598. let fk_initiating_comment = fcp.fcp.fk_initiating_comment;
  1599. let init_comment = issue
  1600. .get_comment(&client, fk_initiating_comment.try_into()?)
  1601. .await?;
  1602. Some(crate::actions::FCPDetails {
  1603. bot_tracking_comment_html_url,
  1604. bot_tracking_comment_content,
  1605. initiating_comment_html_url: init_comment.html_url.clone(),
  1606. initiating_comment_content: quote_reply(&init_comment.body),
  1607. })
  1608. } else {
  1609. None
  1610. }
  1611. } else {
  1612. None
  1613. };
  1614. let mcp_details = if include_mcp_details {
  1615. let first_comment = issue.get_first_comment(&client).await?;
  1616. let split = re_zulip_link
  1617. .split(&first_comment[0].body)
  1618. .collect::<Vec<&str>>();
  1619. let zulip_link = split.last().unwrap_or(&"#").to_string();
  1620. Some(crate::actions::MCPDetails { zulip_link })
  1621. } else {
  1622. None
  1623. };
  1624. issues_decorator.push(crate::actions::IssueDecorator {
  1625. title: issue.title.clone(),
  1626. number: issue.number,
  1627. html_url: issue.html_url.clone(),
  1628. repo_name: repo.name().to_owned(),
  1629. labels: issue
  1630. .labels
  1631. .iter()
  1632. .map(|l| l.name.as_ref())
  1633. .collect::<Vec<_>>()
  1634. .join(", "),
  1635. assignees: issue
  1636. .assignees
  1637. .iter()
  1638. .map(|u| u.login.as_ref())
  1639. .collect::<Vec<_>>()
  1640. .join(", "),
  1641. updated_at_hts: crate::actions::to_human(issue.updated_at),
  1642. fcp_details,
  1643. mcp_details,
  1644. });
  1645. }
  1646. Ok(issues_decorator)
  1647. }
  1648. }
  1649. #[derive(Debug, serde::Deserialize)]
  1650. #[serde(rename_all = "snake_case")]
  1651. pub enum CreateKind {
  1652. Branch,
  1653. Tag,
  1654. }
  1655. #[derive(Debug, serde::Deserialize)]
  1656. pub struct CreateEvent {
  1657. pub ref_type: CreateKind,
  1658. repository: Repository,
  1659. sender: User,
  1660. }
  1661. #[derive(Debug, serde::Deserialize)]
  1662. pub struct PushEvent {
  1663. #[serde(rename = "ref")]
  1664. pub git_ref: String,
  1665. repository: Repository,
  1666. sender: User,
  1667. }
  1668. /// An event triggered by a webhook.
  1669. #[derive(Debug)]
  1670. pub enum Event {
  1671. /// A Git branch or tag is created.
  1672. Create(CreateEvent),
  1673. /// A comment on an issue or PR.
  1674. ///
  1675. /// Can be:
  1676. /// - Regular comment on an issue or PR.
  1677. /// - A PR review.
  1678. /// - A comment on a PR review.
  1679. ///
  1680. /// These different scenarios are unified into the `IssueComment` variant
  1681. /// when triagebot receives the corresponding webhook event.
  1682. IssueComment(IssueCommentEvent),
  1683. /// Activity on an issue or PR.
  1684. Issue(IssuesEvent),
  1685. /// One or more commits are pushed to a repository branch or tag.
  1686. Push(PushEvent),
  1687. }
  1688. impl Event {
  1689. pub fn repo(&self) -> &Repository {
  1690. match self {
  1691. Event::Create(event) => &event.repository,
  1692. Event::IssueComment(event) => &event.repository,
  1693. Event::Issue(event) => &event.repository,
  1694. Event::Push(event) => &event.repository,
  1695. }
  1696. }
  1697. pub fn issue(&self) -> Option<&Issue> {
  1698. match self {
  1699. Event::Create(_) => None,
  1700. Event::IssueComment(event) => Some(&event.issue),
  1701. Event::Issue(event) => Some(&event.issue),
  1702. Event::Push(_) => None,
  1703. }
  1704. }
  1705. /// This will both extract from IssueComment events but also Issue events
  1706. pub fn comment_body(&self) -> Option<&str> {
  1707. match self {
  1708. Event::Create(_) => None,
  1709. Event::Issue(e) => Some(&e.issue.body),
  1710. Event::IssueComment(e) => Some(&e.comment.body),
  1711. Event::Push(_) => None,
  1712. }
  1713. }
  1714. /// This will both extract from IssueComment events but also Issue events
  1715. pub fn comment_from(&self) -> Option<&str> {
  1716. match self {
  1717. Event::Create(_) => None,
  1718. Event::Issue(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  1719. Event::IssueComment(e) => Some(&e.changes.as_ref()?.body.as_ref()?.from),
  1720. Event::Push(_) => None,
  1721. }
  1722. }
  1723. pub fn html_url(&self) -> Option<&str> {
  1724. match self {
  1725. Event::Create(_) => None,
  1726. Event::Issue(e) => Some(&e.issue.html_url),
  1727. Event::IssueComment(e) => Some(&e.comment.html_url),
  1728. Event::Push(_) => None,
  1729. }
  1730. }
  1731. pub fn user(&self) -> &User {
  1732. match self {
  1733. Event::Create(e) => &e.sender,
  1734. Event::Issue(e) => &e.issue.user,
  1735. Event::IssueComment(e) => &e.comment.user,
  1736. Event::Push(e) => &e.sender,
  1737. }
  1738. }
  1739. pub fn time(&self) -> Option<chrono::DateTime<FixedOffset>> {
  1740. match self {
  1741. Event::Create(_) => None,
  1742. Event::Issue(e) => Some(e.issue.created_at.into()),
  1743. Event::IssueComment(e) => Some(e.comment.updated_at.into()),
  1744. Event::Push(_) => None,
  1745. }
  1746. }
  1747. }
  1748. trait RequestSend: Sized {
  1749. fn configure(self, g: &GithubClient) -> Self;
  1750. }
  1751. impl RequestSend for RequestBuilder {
  1752. fn configure(self, g: &GithubClient) -> RequestBuilder {
  1753. let mut auth = HeaderValue::from_maybe_shared(format!("token {}", g.token)).unwrap();
  1754. auth.set_sensitive(true);
  1755. self.header(USER_AGENT, "rust-lang-triagebot")
  1756. .header(AUTHORIZATION, &auth)
  1757. }
  1758. }
  1759. /// Finds the token in the user's environment, panicking if no suitable token
  1760. /// can be found.
  1761. pub fn default_token_from_env() -> String {
  1762. match std::env::var("GITHUB_API_TOKEN") {
  1763. Ok(v) => return v,
  1764. Err(_) => (),
  1765. }
  1766. match get_token_from_git_config() {
  1767. Ok(v) => return v,
  1768. Err(_) => (),
  1769. }
  1770. panic!("could not find token in GITHUB_API_TOKEN or .gitconfig/github.oath-token")
  1771. }
  1772. fn get_token_from_git_config() -> anyhow::Result<String> {
  1773. let output = std::process::Command::new("git")
  1774. .arg("config")
  1775. .arg("--get")
  1776. .arg("github.oauth-token")
  1777. .output()?;
  1778. if !output.status.success() {
  1779. anyhow::bail!("error received executing `git`: {:?}", output.status);
  1780. }
  1781. let git_token = String::from_utf8(output.stdout)?.trim().to_string();
  1782. Ok(git_token)
  1783. }
  1784. #[derive(Clone)]
  1785. pub struct GithubClient {
  1786. token: String,
  1787. client: Client,
  1788. api_url: String,
  1789. graphql_url: String,
  1790. raw_url: String,
  1791. }
  1792. impl GithubClient {
  1793. pub fn new(token: String, api_url: String, graphql_url: String, raw_url: String) -> Self {
  1794. GithubClient {
  1795. client: Client::new(),
  1796. token,
  1797. api_url,
  1798. graphql_url,
  1799. raw_url,
  1800. }
  1801. }
  1802. pub fn new_from_env() -> Self {
  1803. Self::new(
  1804. default_token_from_env(),
  1805. std::env::var("GITHUB_API_URL")
  1806. .unwrap_or_else(|_| "https://api.github.com".to_string()),
  1807. std::env::var("GITHUB_GRAPHQL_API_URL")
  1808. .unwrap_or_else(|_| "https://api.github.com/graphql".to_string()),
  1809. std::env::var("GITHUB_RAW_URL")
  1810. .unwrap_or_else(|_| "https://raw.githubusercontent.com".to_string()),
  1811. )
  1812. }
  1813. pub fn raw(&self) -> &Client {
  1814. &self.client
  1815. }
  1816. pub async fn raw_file(
  1817. &self,
  1818. repo: &str,
  1819. branch: &str,
  1820. path: &str,
  1821. ) -> anyhow::Result<Option<Bytes>> {
  1822. let url = format!("{}/{repo}/{branch}/{path}", self.raw_url);
  1823. let req = self.get(&url);
  1824. let req_dbg = format!("{:?}", req);
  1825. let req = req
  1826. .build()
  1827. .with_context(|| format!("failed to build request {:?}", req_dbg))?;
  1828. let resp = self.client.execute(req).await.context(req_dbg.clone())?;
  1829. let status = resp.status();
  1830. let body = resp
  1831. .bytes()
  1832. .await
  1833. .with_context(|| format!("failed to read response body {req_dbg}"))?;
  1834. match status {
  1835. StatusCode::OK => Ok(Some(body)),
  1836. StatusCode::NOT_FOUND => Ok(None),
  1837. status => anyhow::bail!("failed to GET {}: {}", url, status),
  1838. }
  1839. }
  1840. /// Get the raw gist content from the URL of the HTML version of the gist:
  1841. ///
  1842. /// `html_url` looks like `https://gist.github.com/rust-play/7e80ca3b1ec7abe08f60c41aff91f060`.
  1843. ///
  1844. /// `filename` is the name of the file you want the content of.
  1845. pub async fn raw_gist_from_url(
  1846. &self,
  1847. html_url: &str,
  1848. filename: &str,
  1849. ) -> anyhow::Result<String> {
  1850. let url = html_url.replace("github.com", "githubusercontent.com") + "/raw/" + filename;
  1851. let response = self.raw().get(&url).send().await?;
  1852. response.text().await.context("raw gist from url")
  1853. }
  1854. fn get(&self, url: &str) -> RequestBuilder {
  1855. log::trace!("get {:?}", url);
  1856. self.client.get(url).configure(self)
  1857. }
  1858. fn patch(&self, url: &str) -> RequestBuilder {
  1859. log::trace!("patch {:?}", url);
  1860. self.client.patch(url).configure(self)
  1861. }
  1862. fn delete(&self, url: &str) -> RequestBuilder {
  1863. log::trace!("delete {:?}", url);
  1864. self.client.delete(url).configure(self)
  1865. }
  1866. fn post(&self, url: &str) -> RequestBuilder {
  1867. log::trace!("post {:?}", url);
  1868. self.client.post(url).configure(self)
  1869. }
  1870. #[allow(unused)]
  1871. fn put(&self, url: &str) -> RequestBuilder {
  1872. log::trace!("put {:?}", url);
  1873. self.client.put(url).configure(self)
  1874. }
  1875. pub async fn rust_commit(&self, sha: &str) -> Option<GithubCommit> {
  1876. let req = self.get(&format!(
  1877. "{}/repos/rust-lang/rust/commits/{sha}",
  1878. self.api_url
  1879. ));
  1880. match self.json(req).await {
  1881. Ok(r) => Some(r),
  1882. Err(e) => {
  1883. log::error!("Failed to query commit {:?}: {:?}", sha, e);
  1884. None
  1885. }
  1886. }
  1887. }
  1888. /// This does not retrieve all of them, only the last several.
  1889. pub async fn bors_commits(&self) -> Vec<GithubCommit> {
  1890. let req = self.get(&format!(
  1891. "{}/repos/rust-lang/rust/commits?author=bors",
  1892. self.api_url
  1893. ));
  1894. match self.json(req).await {
  1895. Ok(r) => r,
  1896. Err(e) => {
  1897. log::error!("Failed to query commit list: {:?}", e);
  1898. Vec::new()
  1899. }
  1900. }
  1901. }
  1902. /// Issues an ad-hoc GraphQL query.
  1903. pub async fn graphql_query<T: serde::de::DeserializeOwned>(
  1904. &self,
  1905. query: &str,
  1906. vars: serde_json::Value,
  1907. ) -> anyhow::Result<T> {
  1908. self.json(self.post(&self.graphql_url).json(&serde_json::json!({
  1909. "query": query,
  1910. "variables": vars,
  1911. })))
  1912. .await
  1913. }
  1914. /// Returns the object ID of the given user.
  1915. ///
  1916. /// Returns `None` if the user doesn't exist.
  1917. pub async fn user_object_id(&self, user: &str) -> anyhow::Result<Option<String>> {
  1918. let user_info: serde_json::Value = self
  1919. .graphql_query(
  1920. "query($user:String!) {
  1921. user(login:$user) {
  1922. id
  1923. }
  1924. }",
  1925. serde_json::json!({
  1926. "user": user,
  1927. }),
  1928. )
  1929. .await?;
  1930. if let Some(id) = user_info["data"]["user"]["id"].as_str() {
  1931. return Ok(Some(id.to_string()));
  1932. }
  1933. if let Some(errors) = user_info["errors"].as_array() {
  1934. if errors
  1935. .iter()
  1936. .any(|err| err["type"].as_str().unwrap_or_default() == "NOT_FOUND")
  1937. {
  1938. return Ok(None);
  1939. }
  1940. let messages: Vec<_> = errors
  1941. .iter()
  1942. .map(|err| err["message"].as_str().unwrap_or_default())
  1943. .collect();
  1944. anyhow::bail!("failed to query user: {}", messages.join("\n"));
  1945. }
  1946. anyhow::bail!("query for user {user} failed, no error message? {user_info:?}");
  1947. }
  1948. /// Returns whether or not the given GitHub login has made any commits to
  1949. /// the given repo.
  1950. pub async fn is_new_contributor(&self, repo: &Repository, author: &str) -> bool {
  1951. let user_id = match self.user_object_id(author).await {
  1952. Ok(None) => return true,
  1953. Ok(Some(id)) => id,
  1954. Err(e) => {
  1955. log::warn!("failed to query user: {e:?}");
  1956. return true;
  1957. }
  1958. };
  1959. // Note: This only returns results for the default branch. That should
  1960. // be fine in most cases since I think it is rare for new users to
  1961. // make their first commit to a different branch.
  1962. //
  1963. // Note: This is using GraphQL because the
  1964. // `/repos/ORG/REPO/commits?author=AUTHOR` API was having problems not
  1965. // finding users (https://github.com/rust-lang/triagebot/issues/1689).
  1966. // The other possibility is the `/search/commits?q=repo:{}+author:{}`
  1967. // API, but that endpoint has a very limited rate limit, and doesn't
  1968. // work on forks. This GraphQL query seems to work fairly reliably,
  1969. // and seems to cost only 1 point.
  1970. match self
  1971. .graphql_query::<serde_json::Value>(
  1972. "query($repository_owner:String!, $repository_name:String!, $user_id:ID!) {
  1973. repository(owner: $repository_owner, name: $repository_name) {
  1974. defaultBranchRef {
  1975. target {
  1976. ... on Commit {
  1977. history(author: {id: $user_id}) {
  1978. totalCount
  1979. }
  1980. }
  1981. }
  1982. }
  1983. }
  1984. }",
  1985. serde_json::json!({
  1986. "repository_owner": repo.owner(),
  1987. "repository_name": repo.name(),
  1988. "user_id": user_id
  1989. }),
  1990. )
  1991. .await
  1992. {
  1993. Ok(c) => {
  1994. if let Some(c) = c["data"]["repository"]["defaultBranchRef"]["target"]["history"]
  1995. ["totalCount"]
  1996. .as_i64()
  1997. {
  1998. return c == 0;
  1999. }
  2000. log::warn!("new user query failed: {c:?}");
  2001. false
  2002. }
  2003. Err(e) => {
  2004. log::warn!(
  2005. "failed to search for user commits in {} for author {author}: {e:?}",
  2006. repo.full_name
  2007. );
  2008. // Using `false` since if there is some underlying problem, we
  2009. // don't need to spam everyone with the "new user" welcome
  2010. // message.
  2011. false
  2012. }
  2013. }
  2014. }
  2015. /// Returns information about a repository.
  2016. ///
  2017. /// The `full_name` should be something like `rust-lang/rust`.
  2018. pub async fn repository(&self, full_name: &str) -> anyhow::Result<Repository> {
  2019. let req = self.get(&format!("{}/repos/{full_name}", self.api_url));
  2020. self.json(req)
  2021. .await
  2022. .with_context(|| format!("{} failed to get repo", full_name))
  2023. }
  2024. /// Get or create a [`Milestone`].
  2025. ///
  2026. /// This will not change the state if it already exists.
  2027. async fn get_or_create_milestone(
  2028. &self,
  2029. full_repo_name: &str,
  2030. title: &str,
  2031. state: &str,
  2032. ) -> anyhow::Result<Milestone> {
  2033. let url = format!("{}/repos/{full_repo_name}/milestones", self.api_url);
  2034. let resp = self
  2035. .send_req(self.post(&url).json(&serde_json::json!({
  2036. "title": title,
  2037. "state": state,
  2038. })))
  2039. .await;
  2040. match resp {
  2041. Ok((body, _dbg)) => {
  2042. let milestone = serde_json::from_slice(&body)?;
  2043. log::trace!("Created milestone: {milestone:?}");
  2044. return Ok(milestone);
  2045. }
  2046. Err(e) => {
  2047. if e.downcast_ref::<reqwest::Error>().map_or(false, |e| {
  2048. matches!(e.status(), Some(StatusCode::UNPROCESSABLE_ENTITY))
  2049. }) {
  2050. // fall-through, it already exists
  2051. } else {
  2052. return Err(e.context(format!(
  2053. "failed to create milestone {url} with title {title}"
  2054. )));
  2055. }
  2056. }
  2057. }
  2058. // In the case where it already exists, we need to search for its number.
  2059. let mut page = 1;
  2060. loop {
  2061. let url = format!(
  2062. "{}/repos/{full_repo_name}/milestones?page={page}&state=all",
  2063. self.api_url
  2064. );
  2065. let milestones: Vec<Milestone> = self
  2066. .json(self.get(&url))
  2067. .await
  2068. .with_context(|| format!("failed to get milestones {url} searching for {title}"))?;
  2069. if milestones.is_empty() {
  2070. anyhow::bail!("expected to find milestone with title {title}");
  2071. }
  2072. if let Some(milestone) = milestones.into_iter().find(|m| m.title == title) {
  2073. return Ok(milestone);
  2074. }
  2075. page += 1;
  2076. }
  2077. }
  2078. /// Set the milestone of an issue or PR.
  2079. async fn set_milestone(
  2080. &self,
  2081. full_repo_name: &str,
  2082. milestone: &Milestone,
  2083. issue_num: u64,
  2084. ) -> anyhow::Result<()> {
  2085. let url = format!("{}/repos/{full_repo_name}/issues/{issue_num}", self.api_url);
  2086. self.send_req(self.patch(&url).json(&serde_json::json!({
  2087. "milestone": milestone.number
  2088. })))
  2089. .await
  2090. .with_context(|| format!("failed to set milestone for {url} to milestone {milestone:?}"))?;
  2091. Ok(())
  2092. }
  2093. }
  2094. #[derive(Debug, serde::Deserialize)]
  2095. pub struct GithubCommit {
  2096. pub sha: String,
  2097. pub commit: GithubCommitCommitField,
  2098. pub parents: Vec<Parent>,
  2099. }
  2100. #[derive(Debug, serde::Deserialize)]
  2101. pub struct GithubCommitCommitField {
  2102. pub author: GitUser,
  2103. pub message: String,
  2104. pub tree: GitCommitTree,
  2105. }
  2106. #[derive(Debug, serde::Deserialize)]
  2107. pub struct GitCommit {
  2108. pub sha: String,
  2109. pub author: GitUser,
  2110. pub message: String,
  2111. pub tree: GitCommitTree,
  2112. }
  2113. #[derive(Debug, serde::Deserialize)]
  2114. pub struct GitCommitTree {
  2115. pub sha: String,
  2116. }
  2117. #[derive(Debug, serde::Deserialize)]
  2118. pub struct GitTreeObject {
  2119. pub sha: String,
  2120. }
  2121. #[derive(Debug, serde::Serialize, serde::Deserialize)]
  2122. pub struct GitTreeEntry {
  2123. pub path: String,
  2124. pub mode: String,
  2125. #[serde(rename = "type")]
  2126. pub object_type: String,
  2127. pub sha: String,
  2128. }
  2129. pub struct RecentCommit {
  2130. pub title: String,
  2131. pub pr_num: Option<i32>,
  2132. pub oid: String,
  2133. pub committed_date: DateTime<Utc>,
  2134. }
  2135. #[derive(Debug, serde::Deserialize)]
  2136. pub struct GitUser {
  2137. pub date: DateTime<FixedOffset>,
  2138. }
  2139. #[derive(Debug, serde::Deserialize)]
  2140. pub struct Parent {
  2141. pub sha: String,
  2142. }
  2143. #[async_trait]
  2144. pub trait IssuesQuery {
  2145. async fn query<'a>(
  2146. &'a self,
  2147. repo: &'a Repository,
  2148. include_fcp_details: bool,
  2149. include_mcp_details: bool,
  2150. client: &'a GithubClient,
  2151. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>>;
  2152. }
  2153. pub struct LeastRecentlyReviewedPullRequests;
  2154. #[async_trait]
  2155. impl IssuesQuery for LeastRecentlyReviewedPullRequests {
  2156. async fn query<'a>(
  2157. &'a self,
  2158. repo: &'a Repository,
  2159. _include_fcp_details: bool,
  2160. _include_mcp_details: bool,
  2161. client: &'a GithubClient,
  2162. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>> {
  2163. use cynic::QueryBuilder;
  2164. use github_graphql::queries;
  2165. let repository_owner = repo.owner();
  2166. let repository_name = repo.name();
  2167. let mut prs: Vec<queries::PullRequest> = vec![];
  2168. let mut args = queries::LeastRecentlyReviewedPullRequestsArguments {
  2169. repository_owner,
  2170. repository_name,
  2171. after: None,
  2172. };
  2173. loop {
  2174. let query = queries::LeastRecentlyReviewedPullRequests::build(args.clone());
  2175. let req = client.post(&client.graphql_url);
  2176. let req = req.json(&query);
  2177. let data: cynic::GraphQlResponse<queries::LeastRecentlyReviewedPullRequests> =
  2178. client.json(req).await?;
  2179. if let Some(errors) = data.errors {
  2180. anyhow::bail!("There were graphql errors. {:?}", errors);
  2181. }
  2182. let repository = data
  2183. .data
  2184. .ok_or_else(|| anyhow::anyhow!("No data returned."))?
  2185. .repository
  2186. .ok_or_else(|| anyhow::anyhow!("No repository."))?;
  2187. prs.extend(repository.pull_requests.nodes);
  2188. let page_info = repository.pull_requests.page_info;
  2189. if !page_info.has_next_page || page_info.end_cursor.is_none() {
  2190. break;
  2191. }
  2192. args.after = page_info.end_cursor;
  2193. }
  2194. let mut prs: Vec<_> = prs
  2195. .into_iter()
  2196. .filter_map(|pr| {
  2197. if pr.is_draft {
  2198. return None;
  2199. }
  2200. let labels = pr
  2201. .labels
  2202. .map(|l| l.nodes)
  2203. .unwrap_or_default()
  2204. .into_iter()
  2205. .map(|node| node.name)
  2206. .collect::<Vec<_>>();
  2207. if !labels.iter().any(|label| label == "T-compiler") {
  2208. return None;
  2209. }
  2210. let labels = labels.join(", ");
  2211. let assignees: Vec<_> = pr
  2212. .assignees
  2213. .nodes
  2214. .into_iter()
  2215. .map(|user| user.login)
  2216. .collect();
  2217. let mut reviews = pr
  2218. .latest_reviews
  2219. .map(|connection| connection.nodes)
  2220. .unwrap_or_default()
  2221. .into_iter()
  2222. .filter_map(|node| {
  2223. let created_at = node.created_at;
  2224. node.author.map(|author| (author, created_at))
  2225. })
  2226. .map(|(author, created_at)| (author.login, created_at))
  2227. .collect::<Vec<_>>();
  2228. reviews.sort_by_key(|r| r.1);
  2229. let mut comments = pr
  2230. .comments
  2231. .nodes
  2232. .into_iter()
  2233. .filter_map(|node| {
  2234. let created_at = node.created_at;
  2235. node.author.map(|author| (author, created_at))
  2236. })
  2237. .map(|(author, created_at)| (author.login, created_at))
  2238. .filter(|comment| assignees.contains(&comment.0))
  2239. .collect::<Vec<_>>();
  2240. comments.sort_by_key(|c| c.1);
  2241. let updated_at = std::cmp::max(
  2242. reviews.last().map(|t| t.1).unwrap_or(pr.created_at),
  2243. comments.last().map(|t| t.1).unwrap_or(pr.created_at),
  2244. );
  2245. let assignees = assignees.join(", ");
  2246. Some((
  2247. updated_at,
  2248. pr.number as u64,
  2249. pr.title,
  2250. pr.url.0,
  2251. repository_name,
  2252. labels,
  2253. assignees,
  2254. ))
  2255. })
  2256. .collect();
  2257. prs.sort_by_key(|pr| pr.0);
  2258. let prs: Vec<_> = prs
  2259. .into_iter()
  2260. .take(50)
  2261. .map(
  2262. |(updated_at, number, title, html_url, repo_name, labels, assignees)| {
  2263. let updated_at_hts = crate::actions::to_human(updated_at);
  2264. crate::actions::IssueDecorator {
  2265. number,
  2266. title,
  2267. html_url,
  2268. repo_name: repo_name.to_string(),
  2269. labels,
  2270. assignees,
  2271. updated_at_hts,
  2272. fcp_details: None,
  2273. mcp_details: None,
  2274. }
  2275. },
  2276. )
  2277. .collect();
  2278. Ok(prs)
  2279. }
  2280. }
  2281. async fn project_items_by_status(
  2282. client: &GithubClient,
  2283. status_filter: impl Fn(Option<&str>) -> bool,
  2284. ) -> anyhow::Result<Vec<github_graphql::project_items::ProjectV2Item>> {
  2285. use cynic::QueryBuilder;
  2286. use github_graphql::project_items;
  2287. const DESIGN_MEETING_PROJECT: i32 = 31;
  2288. let mut args = project_items::Arguments {
  2289. project_number: DESIGN_MEETING_PROJECT,
  2290. after: None,
  2291. };
  2292. let mut all_items = vec![];
  2293. loop {
  2294. let query = project_items::Query::build(args.clone());
  2295. let req = client.post(&client.graphql_url);
  2296. let req = req.json(&query);
  2297. let data: cynic::GraphQlResponse<project_items::Query> = client.json(req).await?;
  2298. if let Some(errors) = data.errors {
  2299. anyhow::bail!("There were graphql errors. {:?}", errors);
  2300. }
  2301. let items = data
  2302. .data
  2303. .ok_or_else(|| anyhow!("No data returned."))?
  2304. .organization
  2305. .ok_or_else(|| anyhow!("Organization not found."))?
  2306. .project_v2
  2307. .ok_or_else(|| anyhow!("Project not found."))?
  2308. .items;
  2309. let filtered = items
  2310. .nodes
  2311. .ok_or_else(|| anyhow!("Malformed response."))?
  2312. .into_iter()
  2313. .flatten()
  2314. .filter(|item| status_filter(item.status()));
  2315. all_items.extend(filtered);
  2316. let page_info = items.page_info;
  2317. if !page_info.has_next_page || page_info.end_cursor.is_none() {
  2318. break;
  2319. }
  2320. args.after = page_info.end_cursor;
  2321. }
  2322. all_items.sort_by_key(|item| item.date());
  2323. Ok(all_items)
  2324. }
  2325. pub enum DesignMeetingStatus {
  2326. Proposed,
  2327. Scheduled,
  2328. Done,
  2329. Empty,
  2330. }
  2331. impl DesignMeetingStatus {
  2332. fn query_str(&self) -> Option<&str> {
  2333. match self {
  2334. DesignMeetingStatus::Proposed => Some("Needs triage"),
  2335. DesignMeetingStatus::Scheduled => Some("Scheduled"),
  2336. DesignMeetingStatus::Done => Some("Done"),
  2337. DesignMeetingStatus::Empty => None,
  2338. }
  2339. }
  2340. }
  2341. pub struct DesignMeetings {
  2342. pub with_status: DesignMeetingStatus,
  2343. }
  2344. #[async_trait]
  2345. impl IssuesQuery for DesignMeetings {
  2346. async fn query<'a>(
  2347. &'a self,
  2348. _repo: &'a Repository,
  2349. _include_fcp_details: bool,
  2350. _include_mcp_details: bool,
  2351. client: &'a GithubClient,
  2352. ) -> anyhow::Result<Vec<crate::actions::IssueDecorator>> {
  2353. use github_graphql::project_items::ProjectV2ItemContent;
  2354. let items =
  2355. project_items_by_status(client, |status| status == self.with_status.query_str())
  2356. .await?;
  2357. Ok(items
  2358. .into_iter()
  2359. .flat_map(|item| match item.content {
  2360. Some(ProjectV2ItemContent::Issue(issue)) => Some(crate::actions::IssueDecorator {
  2361. assignees: String::new(),
  2362. number: issue.number.try_into().unwrap(),
  2363. fcp_details: None,
  2364. mcp_details: None,
  2365. html_url: issue.url.0,
  2366. title: issue.title,
  2367. repo_name: String::new(),
  2368. labels: String::new(),
  2369. updated_at_hts: String::new(),
  2370. }),
  2371. _ => None,
  2372. })
  2373. .collect())
  2374. }
  2375. }
  2376. #[derive(Debug, serde::Deserialize)]
  2377. pub struct GitReference {
  2378. #[serde(rename = "ref")]
  2379. pub refname: String,
  2380. pub object: GitObject,
  2381. }
  2382. #[derive(Debug, serde::Deserialize)]
  2383. pub struct GitObject {
  2384. #[serde(rename = "type")]
  2385. pub object_type: String,
  2386. pub sha: String,
  2387. pub url: String,
  2388. }
  2389. #[derive(Debug, serde::Deserialize)]
  2390. pub struct Submodule {
  2391. pub name: String,
  2392. pub path: String,
  2393. pub sha: String,
  2394. pub submodule_git_url: String,
  2395. }
  2396. impl Submodule {
  2397. /// Returns the `Repository` this submodule points to.
  2398. ///
  2399. /// This assumes that the submodule is on GitHub.
  2400. pub async fn repository(&self, client: &GithubClient) -> anyhow::Result<Repository> {
  2401. let fullname = self
  2402. .submodule_git_url
  2403. .strip_prefix("https://github.com/")
  2404. .ok_or_else(|| {
  2405. anyhow::anyhow!(
  2406. "only github submodules supported, got {}",
  2407. self.submodule_git_url
  2408. )
  2409. })?
  2410. .strip_suffix(".git")
  2411. .ok_or_else(|| {
  2412. anyhow::anyhow!("expected .git suffix, got {}", self.submodule_git_url)
  2413. })?;
  2414. client.repository(fullname).await
  2415. }
  2416. }
  2417. #[cfg(test)]
  2418. mod tests {
  2419. use super::*;
  2420. #[test]
  2421. fn display_labels() {
  2422. let x = UnknownLabels {
  2423. labels: vec!["A-bootstrap".into(), "xxx".into()],
  2424. };
  2425. assert_eq!(x.to_string(), "Unknown labels: A-bootstrap, xxx");
  2426. }
  2427. #[test]
  2428. fn extract_one_file() {
  2429. let input = r##"\
  2430. diff --git a/triagebot.toml b/triagebot.toml
  2431. index fb9cee43b2d..b484c25ea51 100644
  2432. --- a/triagebot.toml
  2433. +++ b/triagebot.toml
  2434. @@ -114,6 +114,15 @@ trigger_files = [
  2435. "src/tools/rustdoc-themes",
  2436. ]
  2437. +[autolabel."T-compiler"]
  2438. +trigger_files = [
  2439. + # Source code
  2440. + "compiler",
  2441. +
  2442. + # Tests
  2443. + "src/test/ui",
  2444. +]
  2445. +
  2446. [notify-zulip."I-prioritize"]
  2447. zulip_stream = 245100 # #t-compiler/wg-prioritization/alerts
  2448. topic = "#{number} {title}"
  2449. "##;
  2450. let files: Vec<_> = parse_diff(input).into_iter().map(|d| d.path).collect();
  2451. assert_eq!(files, vec!["triagebot.toml".to_string()]);
  2452. }
  2453. #[test]
  2454. fn extract_several_files() {
  2455. let input = r##"\
  2456. diff --git a/library/stdarch b/library/stdarch
  2457. index b70ae88ef2a..cfba59fccd9 160000
  2458. --- a/library/stdarch
  2459. +++ b/library/stdarch
  2460. @@ -1 +1 @@
  2461. -Subproject commit b70ae88ef2a6c83acad0a1e83d5bd78f9655fd05
  2462. +Subproject commit cfba59fccd90b3b52a614120834320f764ab08d1
  2463. diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs
  2464. index 1fe4aa9023e..f0330f1e424 100644
  2465. --- a/src/librustdoc/clean/types.rs
  2466. +++ b/src/librustdoc/clean/types.rs
  2467. @@ -2322,3 +2322,4 @@ impl SubstParam {
  2468. if let Self::Lifetime(lt) = self { Some(lt) } else { None }
  2469. }
  2470. }
  2471. +
  2472. diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
  2473. index c58310947d2..3b0854d4a9b 100644
  2474. --- a/src/librustdoc/core.rs
  2475. +++ b/src/librustdoc/core.rs
  2476. @@ -591,3 +591,4 @@ fn from(idx: u32) -> Self {
  2477. ImplTraitParam::ParamIndex(idx)
  2478. }
  2479. }
  2480. +
  2481. "##;
  2482. let files: Vec<_> = parse_diff(input).into_iter().map(|d| d.path).collect();
  2483. assert_eq!(
  2484. files,
  2485. vec![
  2486. "library/stdarch".to_string(),
  2487. "src/librustdoc/clean/types.rs".to_string(),
  2488. "src/librustdoc/core.rs".to_string(),
  2489. ]
  2490. )
  2491. }
  2492. }