-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathgithub.rs
3314 lines (3045 loc) · 106 KB
/
github.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, FixedOffset, Utc};
use futures::{future::BoxFuture, FutureExt};
use hyper::header::HeaderValue;
use once_cell::sync::OnceCell;
use regex::Regex;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use reqwest::{Client, Request, RequestBuilder, Response, StatusCode};
use std::collections::{HashMap, HashSet};
use std::{
fmt,
time::{Duration, SystemTime},
};
use tracing as log;
#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
pub struct User {
pub login: String,
pub id: u64,
}
impl GithubClient {
async fn send_req(&self, req: RequestBuilder) -> anyhow::Result<(Bytes, String)> {
const MAX_ATTEMPTS: u32 = 2;
log::debug!("send_req with {:?}", req);
let req_dbg = format!("{:?}", req);
let req = req
.build()
.with_context(|| format!("building reqwest {}", req_dbg))?;
let mut resp = self.client.execute(req.try_clone().unwrap()).await?;
if self.retry_rate_limit {
if let Some(sleep) = Self::needs_retry(&resp).await {
resp = self.retry(req, sleep, MAX_ATTEMPTS).await?;
}
}
let maybe_err = resp.error_for_status_ref().err();
let body = resp
.bytes()
.await
.with_context(|| format!("failed to read response body {req_dbg}"))?;
if let Some(e) = maybe_err {
return Err(anyhow::Error::new(e))
.with_context(|| format!("response: {}", String::from_utf8_lossy(&body)));
}
Ok((body, req_dbg))
}
async fn needs_retry(resp: &Response) -> Option<Duration> {
const REMAINING: &str = "X-RateLimit-Remaining";
const RESET: &str = "X-RateLimit-Reset";
if !matches!(
resp.status(),
StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
) {
return None;
}
let headers = resp.headers();
if !(headers.contains_key(REMAINING) && headers.contains_key(RESET)) {
return None;
}
let reset_time = headers[RESET].to_str().unwrap().parse::<u64>().unwrap();
Some(Duration::from_secs(Self::calc_sleep(reset_time) + 10))
}
fn calc_sleep(reset_time: u64) -> u64 {
let epoch_time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs();
reset_time.saturating_sub(epoch_time)
}
fn retry(
&self,
req: Request,
sleep: Duration,
remaining_attempts: u32,
) -> BoxFuture<Result<Response, reqwest::Error>> {
#[derive(Debug, serde::Deserialize)]
struct RateLimit {
#[allow(unused)]
pub limit: u64,
pub remaining: u64,
pub reset: u64,
}
#[derive(Debug, serde::Deserialize)]
struct RateLimitResponse {
pub resources: Resources,
}
#[derive(Debug, serde::Deserialize)]
struct Resources {
pub core: RateLimit,
pub search: RateLimit,
#[allow(unused)]
pub graphql: RateLimit,
#[allow(unused)]
pub source_import: RateLimit,
}
log::warn!(
"Retrying after {} seconds, remaining attepts {}",
sleep.as_secs(),
remaining_attempts,
);
async move {
tokio::time::sleep(sleep).await;
// check rate limit
let rate_resp = self
.client
.execute(
self.client
.get(&format!("{}/rate_limit", self.api_url))
.configure(self)
.build()
.unwrap(),
)
.await?;
rate_resp.error_for_status_ref()?;
let rate_limit_response = rate_resp.json::<RateLimitResponse>().await?;
// Check url for search path because github has different rate limits for the search api
let rate_limit = if req
.url()
.path_segments()
.map(|mut segments| matches!(segments.next(), Some("search")))
.unwrap_or(false)
{
rate_limit_response.resources.search
} else {
rate_limit_response.resources.core
};
// If we still don't have any more remaining attempts, try sleeping for the remaining
// period of time
if rate_limit.remaining == 0 {
let sleep = Self::calc_sleep(rate_limit.reset);
if sleep > 0 {
tokio::time::sleep(Duration::from_secs(sleep)).await;
}
}
let resp = self.client.execute(req.try_clone().unwrap()).await?;
if let Some(sleep) = Self::needs_retry(&resp).await {
if remaining_attempts > 0 {
return self.retry(req, sleep, remaining_attempts - 1).await;
}
}
Ok(resp)
}
.boxed()
}
pub async fn json<T>(&self, req: RequestBuilder) -> anyhow::Result<T>
where
T: serde::de::DeserializeOwned,
{
let (body, _req_dbg) = self.send_req(req).await?;
Ok(serde_json::from_slice(&body)?)
}
pub(crate) async fn new_issue(
&self,
repo: &IssueRepository,
title: &str,
body: &str,
labels: Vec<String>,
) -> anyhow::Result<NewIssueResponse> {
#[derive(serde::Serialize)]
struct NewIssue<'a> {
title: &'a str,
body: &'a str,
labels: Vec<String>,
}
let url = format!("{}/issues", repo.url(&self));
self.json(self.post(&url).json(&NewIssue {
title,
body,
labels,
}))
.await
.context("failed to create issue")
}
pub(crate) async fn set_pr_state(
&self,
repo: &IssueRepository,
number: u64,
state: PrState,
) -> anyhow::Result<()> {
#[derive(serde::Serialize)]
struct Update {
state: PrState,
}
let url = format!("{}/pulls/{number}", repo.url(&self));
self.send_req(self.patch(&url).json(&Update { state }))
.await
.context("failed to update pr state")?;
Ok(())
}
}
#[derive(Debug, serde::Serialize)]
pub(crate) enum PrState {
#[serde(rename = "open")]
Open,
#[serde(rename = "closed")]
Closed,
}
#[derive(Debug, serde::Deserialize)]
pub struct NewIssueResponse {
pub number: u64,
}
impl User {
pub async fn current(client: &GithubClient) -> anyhow::Result<Self> {
client
.json(client.get(&format!("{}/user", client.api_url)))
.await
}
pub async fn is_team_member<'a>(&'a self, client: &'a GithubClient) -> anyhow::Result<bool> {
log::trace!("Getting team membership for {:?}", self.login);
let permission = crate::team_data::teams(client).await?;
let map = permission.teams;
let is_triager = map
.get("wg-triage")
.map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
let is_pri_member = map
.get("wg-prioritization")
.map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
let is_async_member = map
.get("wg-async")
.map_or(false, |w| w.members.iter().any(|g| g.github == self.login));
let in_all = map["all"].members.iter().any(|g| g.github == self.login);
log::trace!(
"{:?} is all?={:?}, triager?={:?}, prioritizer?={:?}, async?={:?}",
self.login,
in_all,
is_triager,
is_pri_member,
is_async_member,
);
Ok(in_all || is_triager || is_pri_member || is_async_member)
}
}
// Returns the ID of the given user, if the user is in the `all` team.
pub async fn get_id_for_username<'a>(
client: &'a GithubClient,
login: &str,
) -> anyhow::Result<Option<u64>> {
let permission = crate::team_data::teams(client).await?;
let map = permission.teams;
Ok(map["all"]
.members
.iter()
.find(|g| g.github == login)
.map(|u| u.github_id))
}
pub async fn get_team(
client: &GithubClient,
team: &str,
) -> anyhow::Result<Option<rust_team_data::v1::Team>> {
let permission = crate::team_data::teams(client).await?;
let mut map = permission.teams;
Ok(map.swap_remove(team))
}
#[derive(PartialEq, Eq, Debug, Clone, serde::Deserialize)]
pub struct Label {
pub name: String,
}
/// An indicator used to differentiate between an issue and a pull request.
///
/// Some webhook events include a `pull_request` field in the Issue object,
/// and some don't. GitHub does include a few fields here, but they aren't
/// needed at this time (merged_at, diff_url, html_url, patch_url, url).
#[derive(Debug, serde::Deserialize)]
pub struct PullRequestDetails {
/// This is a slot to hold the diff for a PR.
///
/// This will be filled in only once as an optimization since multiple
/// handlers want to see PR changes, and getting the diff can be
/// expensive.
#[serde(skip)]
files_changed: tokio::sync::OnceCell<Vec<FileDiff>>,
}
/// Representation of a diff to a single file.
#[derive(Debug)]
pub struct FileDiff {
/// The full path of the file.
pub path: String,
/// The diff for the file.
pub diff: String,
}
impl PullRequestDetails {
pub fn new() -> PullRequestDetails {
PullRequestDetails {
files_changed: tokio::sync::OnceCell::new(),
}
}
}
/// An issue or pull request.
///
/// For convenience, since issues and pull requests share most of their
/// fields, this struct is used for both. The `pull_request` field can be used
/// to determine which it is. Some fields are only available on pull requests
/// (but not always, check the GitHub API for details).
#[derive(Debug, serde::Deserialize)]
pub struct Issue {
pub number: u64,
#[serde(deserialize_with = "opt_string")]
pub body: String,
pub created_at: chrono::DateTime<Utc>,
pub updated_at: chrono::DateTime<Utc>,
/// The SHA for a merge commit.
///
/// This field is complicated, see the [Pull Request
/// docs](https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request)
/// for details.
#[serde(default)]
pub merge_commit_sha: Option<String>,
pub title: String,
/// The common URL for viewing this issue or PR.
///
/// Example: `https://github.com/octocat/Hello-World/pull/1347`
pub html_url: String,
// User performing an `action` (or PR/issue author)
pub user: User,
pub labels: Vec<Label>,
// Users assigned to the issue/pr after `action` has been performed
// These are NOT the same as `IssueEvent.assignee`
pub assignees: Vec<User>,
/// Indicator if this is a pull request.
///
/// This is `Some` if this is a PR (as opposed to an issue). Note that
/// this does not always get filled in by GitHub, and must be manually
/// populated (because some webhook events do not set it).
pub pull_request: Option<PullRequestDetails>,
/// Whether or not the pull request was merged.
#[serde(default)]
pub merged: bool,
#[serde(default)]
pub draft: bool,
/// Number of comments
pub comments: Option<i32>,
/// The API URL for discussion comments.
///
/// Example: `https://api.github.com/repos/octocat/Hello-World/issues/1347/comments`
comments_url: String,
/// The repository for this issue.
///
/// Note that this is constructed via the [`Issue::repository`] method.
/// It is not deserialized from the GitHub API.
#[serde(skip)]
repository: OnceCell<IssueRepository>,
/// The base commit for a PR (the branch of the destination repo).
#[serde(default)]
pub base: Option<CommitBase>,
/// The head commit for a PR (the branch from the source repo).
#[serde(default)]
pub head: Option<CommitBase>,
/// Whether it is open or closed.
pub state: IssueState,
pub milestone: Option<Milestone>,
/// Whether a PR has merge conflicts.
pub mergeable: Option<bool>,
}
#[derive(Debug, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum IssueState {
Open,
Closed,
}
/// Contains only the parts of `Issue` that are needed for turning the issue title into a Zulip
/// topic.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ZulipGitHubReference {
pub number: u64,
pub title: String,
pub repository: IssueRepository,
}
impl ZulipGitHubReference {
pub fn zulip_topic_reference(&self) -> String {
let repo = &self.repository;
if repo.organization == "rust-lang" {
if repo.repository == "rust" {
format!("#{}", self.number)
} else {
format!("{}#{}", repo.repository, self.number)
}
} else {
format!("{}/{}#{}", repo.organization, repo.repository, self.number)
}
}
}
#[derive(Debug, serde::Deserialize)]
pub struct Comment {
pub id: u64,
pub node_id: String,
#[serde(deserialize_with = "opt_string")]
pub body: String,
pub html_url: String,
pub user: User,
#[serde(default, alias = "submitted_at")] // for pull request reviews
pub created_at: chrono::DateTime<Utc>,
#[serde(default, alias = "submitted_at")] // for pull request reviews
pub updated_at: chrono::DateTime<Utc>,
#[serde(default, rename = "state")]
pub pr_review_state: Option<PullRequestReviewState>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportedContentClassifiers {
Abuse,
Duplicate,
OffTopic,
Outdated,
Resolved,
Spam,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq)]
pub enum LockReason {
#[serde(rename = "off-topic")]
OffTopic,
#[serde(rename = "too heated")]
TooHeated,
#[serde(rename = "resolved")]
Resolved,
#[serde(rename = "spam")]
Spam,
}
#[derive(Debug, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PullRequestReviewState {
Approved,
ChangesRequested,
Commented,
Dismissed,
Pending,
}
fn opt_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: serde::de::Deserializer<'de>,
{
use serde::de::Deserialize;
match <Option<String>>::deserialize(deserializer) {
Ok(v) => Ok(v.unwrap_or_default()),
Err(e) => Err(e),
}
}
#[derive(Debug)]
pub enum AssignmentError {
InvalidAssignee,
Http(anyhow::Error),
}
#[derive(Debug)]
pub enum Selection<'a, T: ?Sized> {
All,
One(&'a T),
Except(&'a T),
}
impl fmt::Display for AssignmentError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AssignmentError::InvalidAssignee => write!(f, "invalid assignee"),
AssignmentError::Http(e) => write!(f, "cannot assign: {}", e),
}
}
}
impl std::error::Error for AssignmentError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueRepository {
pub organization: String,
pub repository: String,
}
impl fmt::Display for IssueRepository {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}/{}", self.organization, self.repository)
}
}
impl IssueRepository {
fn url(&self, client: &GithubClient) -> String {
format!(
"{}/repos/{}/{}",
client.api_url, self.organization, self.repository
)
}
fn full_repo_name(&self) -> String {
format!("{}/{}", self.organization, self.repository)
}
async fn has_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<bool> {
#[allow(clippy::redundant_pattern_matching)]
let url = format!("{}/labels/{}", self.url(client), label);
match client.send_req(client.get(&url)).await {
Ok(_) => Ok(true),
Err(e) => {
if e.downcast_ref::<reqwest::Error>()
.map_or(false, |e| e.status() == Some(StatusCode::NOT_FOUND))
{
Ok(false)
} else {
Err(e)
}
}
}
}
}
#[derive(Debug)]
pub(crate) struct UnknownLabels {
labels: Vec<String>,
}
// NOTE: This is used to post the Github comment; make sure it's valid markdown.
impl fmt::Display for UnknownLabels {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Unknown labels: {}", &self.labels.join(", "))
}
}
impl std::error::Error for UnknownLabels {}
impl Issue {
pub fn to_zulip_github_reference(&self) -> ZulipGitHubReference {
ZulipGitHubReference {
number: self.number,
title: self.title.clone(),
repository: self.repository().clone(),
}
}
pub fn repository(&self) -> &IssueRepository {
self.repository.get_or_init(|| {
// https://api.github.com/repos/rust-lang/rust/issues/69257/comments
log::trace!("get repository for {}", self.comments_url);
let url = url::Url::parse(&self.comments_url).unwrap();
let mut segments = url.path_segments().unwrap();
let _comments = segments.next_back().unwrap();
let _number = segments.next_back().unwrap();
let _issues_or_prs = segments.next_back().unwrap();
let repository = segments.next_back().unwrap();
let organization = segments.next_back().unwrap();
IssueRepository {
organization: organization.into(),
repository: repository.into(),
}
})
}
pub fn global_id(&self) -> String {
format!("{}#{}", self.repository(), self.number)
}
pub fn is_pr(&self) -> bool {
self.pull_request.is_some()
}
pub fn is_open(&self) -> bool {
self.state == IssueState::Open
}
pub async fn get_comment(&self, client: &GithubClient, id: i32) -> anyhow::Result<Comment> {
let comment_url = format!("{}/issues/comments/{}", self.repository().url(client), id);
let comment = client.json(client.get(&comment_url)).await?;
Ok(comment)
}
pub async fn get_first100_comments(
&self,
client: &GithubClient,
) -> anyhow::Result<Vec<Comment>> {
let comment_url = format!(
"{}/issues/{}/comments?page=1&per_page=100",
self.repository().url(client),
self.number,
);
Ok(client
.json::<Vec<Comment>>(client.get(&comment_url))
.await?)
}
pub async fn edit_body(&self, client: &GithubClient, body: &str) -> anyhow::Result<()> {
let edit_url = format!("{}/issues/{}", self.repository().url(client), self.number);
#[derive(serde::Serialize)]
struct ChangedIssue<'a> {
body: &'a str,
}
client
.send_req(client.patch(&edit_url).json(&ChangedIssue { body }))
.await
.context("failed to edit issue body")?;
Ok(())
}
pub async fn edit_comment(
&self,
client: &GithubClient,
id: u64,
new_body: &str,
) -> anyhow::Result<Comment> {
let comment_url = format!("{}/issues/comments/{}", self.repository().url(client), id);
#[derive(serde::Serialize)]
struct NewComment<'a> {
body: &'a str,
}
let comment = client
.json(
client
.patch(&comment_url)
.json(&NewComment { body: new_body }),
)
.await
.context("failed to edit comment")?;
Ok(comment)
}
pub async fn post_comment(&self, client: &GithubClient, body: &str) -> anyhow::Result<Comment> {
#[derive(serde::Serialize)]
struct PostComment<'a> {
body: &'a str,
}
let comments_path = self
.comments_url
.strip_prefix("https://api.github.com")
.expect("expected api host");
let comments_url = format!("{}{comments_path}", client.api_url);
let comment = client
.json(client.post(&comments_url).json(&PostComment { body }))
.await
.context("failed to post comment")?;
Ok(comment)
}
pub async fn hide_comment(
&self,
client: &GithubClient,
node_id: &str,
reason: ReportedContentClassifiers,
) -> anyhow::Result<()> {
client
.graphql_query(
"mutation($node_id: ID!, $reason: ReportedContentClassifiers!) {
minimizeComment(input: {subjectId: $node_id, classifier: $reason}) {
__typename
}
}",
serde_json::json!({
"node_id": node_id,
"reason": reason,
}),
)
.await?;
Ok(())
}
pub async fn remove_label(&self, client: &GithubClient, label: &str) -> anyhow::Result<()> {
log::info!("remove_label from {}: {:?}", self.global_id(), label);
// DELETE /repos/:owner/:repo/issues/:number/labels/{name}
let url = format!(
"{repo_url}/issues/{number}/labels/{name}",
repo_url = self.repository().url(client),
number = self.number,
name = label,
);
if !self.labels().iter().any(|l| l.name == label) {
log::info!(
"remove_label from {}: {:?} already not present, skipping",
self.global_id(),
label
);
return Ok(());
}
client
.send_req(client.delete(&url))
.await
.context("failed to delete label")?;
Ok(())
}
pub async fn add_labels(
&self,
client: &GithubClient,
labels: Vec<Label>,
) -> anyhow::Result<()> {
log::info!("add_labels: {} +{:?}", self.global_id(), labels);
// POST /repos/:owner/:repo/issues/:number/labels
// repo_url = https://api.github.com/repos/Codertocat/Hello-World
let url = format!(
"{repo_url}/issues/{number}/labels",
repo_url = self.repository().url(client),
number = self.number
);
// Don't try to add labels already present on this issue.
let labels = labels
.into_iter()
.filter(|l| !self.labels().contains(&l))
.map(|l| l.name)
.collect::<Vec<_>>();
log::info!("add_labels: {} filtered to {:?}", self.global_id(), labels);
if labels.is_empty() {
return Ok(());
}
let mut unknown_labels = vec![];
let mut known_labels = vec![];
for label in labels {
if !self.repository().has_label(client, &label).await? {
unknown_labels.push(label);
} else {
known_labels.push(label);
}
}
if !unknown_labels.is_empty() {
return Err(UnknownLabels {
labels: unknown_labels,
}
.into());
}
#[derive(serde::Serialize)]
struct LabelsReq {
labels: Vec<String>,
}
client
.send_req(client.post(&url).json(&LabelsReq {
labels: known_labels,
}))
.await
.context("failed to add labels")?;
Ok(())
}
pub fn labels(&self) -> &[Label] {
&self.labels
}
pub fn contain_assignee(&self, user: &str) -> bool {
self.assignees
.iter()
.any(|a| a.login.to_lowercase() == user.to_lowercase())
}
pub async fn remove_assignees(
&self,
client: &GithubClient,
selection: Selection<'_, str>,
) -> Result<(), AssignmentError> {
log::info!("remove {:?} assignees for {}", selection, self.global_id());
let url = format!(
"{repo_url}/issues/{number}/assignees",
repo_url = self.repository().url(client),
number = self.number
);
let assignees = match selection {
Selection::All => self
.assignees
.iter()
.map(|u| u.login.as_str())
.collect::<Vec<_>>(),
Selection::One(user) => vec![user],
Selection::Except(user) => self
.assignees
.iter()
.map(|u| u.login.as_str())
.filter(|&u| u.to_lowercase() != user.to_lowercase())
.collect::<Vec<_>>(),
};
#[derive(serde::Serialize)]
struct AssigneeReq<'a> {
assignees: &'a [&'a str],
}
client
.send_req(client.delete(&url).json(&AssigneeReq {
assignees: &assignees[..],
}))
.await
.map_err(AssignmentError::Http)?;
Ok(())
}
pub async fn add_assignee(
&self,
client: &GithubClient,
user: &str,
) -> Result<(), AssignmentError> {
log::info!("add_assignee {} for {}", user, self.global_id());
let url = format!(
"{repo_url}/issues/{number}/assignees",
repo_url = self.repository().url(client),
number = self.number
);
#[derive(serde::Serialize)]
struct AssigneeReq<'a> {
assignees: &'a [&'a str],
}
let result: Issue = client
.json(client.post(&url).json(&AssigneeReq { assignees: &[user] }))
.await
.map_err(AssignmentError::Http)?;
// Invalid assignees are silently ignored. We can just check if the user is now
// contained in the assignees list.
let success = result
.assignees
.iter()
.any(|u| u.login.as_str().to_lowercase() == user.to_lowercase());
if success {
Ok(())
} else {
Err(AssignmentError::InvalidAssignee)
}
}
pub async fn set_assignee(
&self,
client: &GithubClient,
user: &str,
) -> Result<(), AssignmentError> {
log::info!("set_assignee for {} to {}", self.global_id(), user);
self.add_assignee(client, user).await?;
self.remove_assignees(client, Selection::Except(user))
.await?;
Ok(())
}
/// Sets the milestone of the issue or PR.
///
/// This will create the milestone if it does not exist. The new milestone
/// will start in the "open" state.
pub async fn set_milestone(&self, client: &GithubClient, title: &str) -> anyhow::Result<()> {
log::trace!(
"Setting milestone for rust-lang/rust#{} to {}",
self.number,
title
);
let full_repo_name = self.repository().full_repo_name();
let milestone = client
.get_or_create_milestone(&full_repo_name, title, "open")
.await?;
client
.set_milestone(&full_repo_name, &milestone, self.number)
.await?;
Ok(())
}
/// Lock an issue with an optional reason.
pub async fn lock(
&self,
client: &GithubClient,
reason: Option<LockReason>,
) -> anyhow::Result<()> {
let lock_url = format!(
"{}/issues/{}/lock",
self.repository().url(client),
self.number
);
#[derive(serde::Serialize)]
struct LockReasonIssue {
lock_reason: LockReason,
}
client
.send_req({
let req = client.put(&lock_url);
if let Some(lock_reason) = reason {
req.json(&LockReasonIssue { lock_reason })
} else {
req
}
})
.await
.context("failed to lock issue")?;
Ok(())
}
pub async fn close(&self, client: &GithubClient) -> anyhow::Result<()> {
let edit_url = format!("{}/issues/{}", self.repository().url(client), self.number);
#[derive(serde::Serialize)]
struct CloseIssue<'a> {
state: &'a str,
}
client
.send_req(
client
.patch(&edit_url)
.json(&CloseIssue { state: "closed" }),
)
.await
.context("failed to close issue")?;
Ok(())
}
/// Returns the diff in this event, for Open and Synchronize events for now.
///
/// Returns `None` if the issue is not a PR.
pub async fn diff(&self, client: &GithubClient) -> anyhow::Result<Option<&[FileDiff]>> {
let Some(pr) = &self.pull_request else {
return Ok(None);
};
let (before, after) = if let (Some(base), Some(head)) = (&self.base, &self.head) {
(&base.sha, &head.sha)
} else {
return Ok(None);
};
let diff = pr
.files_changed
.get_or_try_init::<anyhow::Error, _, _>(|| async move {
let url = format!(
"{}/compare/{before}...{after}",
self.repository().url(client)
);
let mut req = client.get(&url);
req = req.header("Accept", "application/vnd.github.v3.diff");
let (diff, _) = client
.send_req(req)
.await
.with_context(|| format!("failed to fetch diff comparison for {url}"))?;
let body = String::from_utf8_lossy(&diff);
Ok(parse_diff(&body))
})
.await?;
Ok(Some(diff))
}
/// Returns the commits from this pull request (no commits are returned if this `Issue` is not
/// a pull request).
pub async fn commits(&self, client: &GithubClient) -> anyhow::Result<Vec<GithubCommit>> {
if !self.is_pr() {
return Ok(vec![]);
}
let mut commits = Vec::new();
let mut page = 1;
loop {
let req = client.get(&format!(
"{}/pulls/{}/commits?page={page}&per_page=100",
self.repository().url(client),
self.number
));
let new: Vec<_> = client.json(req).await?;
if new.is_empty() {
break;
}
commits.extend(new);
page += 1;
}