github.rs 88 KB

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