-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathissue.rs
More file actions
1001 lines (901 loc) · 29.4 KB
/
issue.rs
File metadata and controls
1001 lines (901 loc) · 29.4 KB
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::Context;
use chrono::Utc;
use octocrab::models::AuthorAssociation;
use reqwest::StatusCode;
use std::fmt;
use std::sync::OnceLock;
use tracing as log;
use super::client::GithubClient;
use super::repos::{GitHubUser, Milestone, Repository};
use super::utils::{Selection, opt_string};
use crate::errors::{AssignmentError, UserError};
use crate::github::GithubCommit;
/// 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: GitHubUser,
pub labels: Vec<Label>,
// Users assigned to the issue/pr after `action` has been performed issue
// (PR reviewers or issue assignees)
// These are NOT the same as `IssueEvent.assignee`
pub assignees: Vec<GitHubUser>,
/// 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<u32>,
/// Number of review comments
///
/// This is only included in a reduced set of webhook events, such as
/// `opened`, `synchronize`, `closed` and maybe others.
#[serde(default)]
pub review_comments: Option<u32>,
/// The API URL for discussion comments.
///
/// Example: `https://api.github.com/repos/octocat/Hello-World/issues/1347/comments`
pub 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)]
pub repository: OnceLock<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>,
/// How the author is associated with the repository
pub author_association: AuthorAssociation,
}
#[derive(PartialEq, Eq, Debug, Clone, Ord, PartialOrd, serde::Deserialize)]
pub struct Label {
pub name: String,
}
#[derive(Debug, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum IssueState {
Open,
Closed,
}
#[derive(Clone, Debug, serde::Deserialize)]
pub struct CommitBase {
pub sha: String,
#[serde(rename = "ref")]
pub git_ref: String,
pub repo: Option<Repository>,
}
/// 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)]
#[cfg_attr(test, derive(Default))]
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)]
compare: tokio::sync::OnceCell<GithubCompare>,
}
impl PullRequestDetails {
pub fn new() -> PullRequestDetails {
PullRequestDetails {
compare: tokio::sync::OnceCell::new(),
}
}
}
/// The return from GitHub compare API
#[derive(Debug, serde::Deserialize)]
pub struct GithubCompare {
/// The base commit of the PR
pub base_commit: GithubCommit,
/// The merge base commit
///
/// See <https://git-scm.com/docs/git-merge-base> for more details
pub merge_base_commit: GithubCommit,
/// List of file differences
pub files: Vec<FileDiff>,
/// List of commits
pub commits: Vec<GithubCommit>,
}
/// Representation of a diff to a single file.
#[derive(Debug, serde::Deserialize)]
pub struct FileDiff {
/// The fullname path of the file.
pub filename: String,
/// The patch/diff for the file.
///
/// Can be empty when there isn't any changes to the content of the file
/// (like when a file is renamed without it's content being modified).
#[serde(default)]
pub patch: String,
}
impl Issue {
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 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_review(
&self,
client: &GithubClient,
id: u64,
new_body: &str,
) -> anyhow::Result<()> {
let comment_url = format!(
"{}/pulls/{}/reviews/{}",
self.repository().url(client),
self.number,
id
);
#[derive(serde::Serialize)]
struct NewComment<'a> {
body: &'a str,
}
client
.send_req(
client
.put(&comment_url)
.json(&NewComment { body: new_body }),
)
.await
.context("failed to edit review comment")?;
Ok(())
}
pub async fn edit_review_comment(
&self,
client: &GithubClient,
id: u64,
new_body: &str,
) -> anyhow::Result<Comment> {
let comment_url = format!("{}/pulls/comments/{}", self.repository().url(client), id);
#[derive(serde::Serialize)]
struct EditComment<'a> {
body: &'a str,
}
let comment = client
.json(
client
.patch(&comment_url)
.json(&EditComment { body: new_body }),
)
.await
.context("failed to edit review comment")?;
Ok(comment)
}
fn find_label_case_insensitive<'a>(labels: &'a [Label], name: &str) -> Option<&'a Label> {
labels
.iter()
.find(|l| l.name.to_lowercase() == name.to_lowercase())
}
pub async fn remove_labels(
&self,
client: &GithubClient,
labels: Vec<Label>,
) -> anyhow::Result<()> {
log::info!("remove_labels from {}: {:?}", self.global_id(), labels);
// Don't try to remove labels not already present on this issue.
// Use case-insensitive comparison to match GitHub's behavior when adding labels.
let labels = labels
.into_iter()
.filter_map(|l| Self::find_label_case_insensitive(self.labels(), &l.name).cloned())
.collect::<Vec<_>>();
log::info!(
"remove_labels: {} filtered to {:?}",
self.global_id(),
labels
);
if labels.is_empty() {
return Ok(());
}
// There is no API to remove all labels at once, so we issue as many
// API requests are required in parallel.
let requests = labels.into_iter().map(|label| async move {
// 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.name,
);
client
.send_req(client.delete(&url))
.await
.with_context(|| format!("failed to remove {label:?}"))
});
futures::future::try_join_all(requests).await?;
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? {
known_labels.push(label);
} else {
unknown_labels.push(label);
}
}
if !unknown_labels.is_empty() {
return Err(UserError::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::Other)?;
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::Other)?;
// 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(())
}
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]>> {
Ok(self.compare(client).await?.map(|c| c.files.as_ref()))
}
/// Returns the comparison of this event.
///
/// Returns `None` if the issue is not a PR.
pub async fn compare(&self, client: &GithubClient) -> anyhow::Result<Option<&GithubCompare>> {
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 compare = pr
.compare
.get_or_try_init::<anyhow::Error, _, _>(|| async move {
let req = client.get(&format!(
"{}/compare/{before}...{after}",
self.repository().url(client)
));
client.json(req).await
})
.await?;
Ok(Some(compare))
}
/// 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;
}
Ok(commits)
}
/// Returns the GraphQL ID of this issue.
async fn graphql_issue_id(&self, client: &GithubClient) -> anyhow::Result<String> {
let repo = self.repository();
let mut issue_id = client
.graphql_query(
"query($owner:String!, $repo:String!, $issueNum:Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $issueNum) {
id
}
}
}
",
serde_json::json!({
"owner": repo.organization,
"repo": repo.repository,
"issueNum": self.number,
}),
)
.await?;
let serde_json::Value::String(issue_id) =
issue_id["data"]["repository"]["issue"]["id"].take()
else {
anyhow::bail!("expected issue id, got {issue_id}");
};
Ok(issue_id)
}
/// Transfers this issue to the given repository.
pub async fn transfer(
&self,
client: &GithubClient,
owner: &str,
repo: &str,
) -> anyhow::Result<()> {
let issue_id = self.graphql_issue_id(client).await?;
let repo_id = client.graphql_repo_id(owner, repo).await?;
client
.graphql_query(
"mutation ($issueId: ID!, $repoId: ID!) {
transferIssue(
input: {createLabelsIfMissing: false, issueId: $issueId, repositoryId: $repoId}
) {
issue {
id
}
}
}",
serde_json::json!({
"issueId": issue_id,
"repoId": repo_id,
}),
)
.await?;
Ok(())
}
pub async fn get_review(
&self,
client: &GithubClient,
review_id: u64,
) -> anyhow::Result<Comment> {
let review_url = format!(
"{}/pulls/{}/reviews/{review_id}",
self.repository().url(client),
self.number,
);
let review = client
.json(client.get(&review_url))
.await
.with_context(|| format!("unable to fetch review ({review_id})"))?;
Ok(review)
}
}
// Comments
#[derive(Debug, serde::Deserialize)]
pub struct Comment {
pub id: u64,
pub node_id: String,
#[serde(default)]
pub in_reply_to_id: Option<u64>,
#[serde(default)]
pub pull_request_review_id: Option<u64>,
#[serde(deserialize_with = "opt_string")]
pub body: String,
pub html_url: String,
pub user: GitHubUser,
#[serde(default, alias = "submitted_at")] // for pull-request review comments
pub created_at: Option<chrono::DateTime<Utc>>,
#[serde(default)]
pub updated_at: Option<chrono::DateTime<Utc>>,
#[serde(default, rename = "state")]
pub pr_review_state: Option<PullRequestReviewState>,
pub author_association: AuthorAssociation,
}
#[derive(Debug, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PullRequestReviewState {
#[serde(alias = "APPROVED")]
Approved,
#[serde(alias = "CHANGES_REQUESTED")]
ChangesRequested,
#[serde(alias = "COMMENTED")]
Commented,
#[serde(alias = "DISMISSED")]
Dismissed,
#[serde(alias = "PENDING")]
Pending,
}
impl Issue {
pub async fn get_comment(&self, client: &GithubClient, id: u64) -> 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,
);
client.json::<Vec<Comment>>(client.get(&comment_url)).await
}
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)
}
}
// Hide comment
#[derive(Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportedContentClassifiers {
Abuse,
Duplicate,
OffTopic,
Outdated,
Resolved,
Spam,
}
impl Issue {
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(())
}
}
// Lock
#[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,
}
impl Issue {
/// 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(())
}
}
// Pull-request files
#[derive(Debug, serde::Deserialize)]
pub struct PullRequestFile {
pub sha: String,
pub status: PullRequestFileStatus,
pub filename: String,
pub blob_url: String,
pub additions: u64,
pub deletions: u64,
pub changes: u64,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PullRequestFileStatus {
Added,
Removed,
Modified,
Renamed,
Copied,
Changed,
Unchanged,
}
impl Issue {
pub async fn files(&self, client: &GithubClient) -> anyhow::Result<Vec<PullRequestFile>> {
if !self.is_pr() {
return Ok(vec![]);
}
let req = client.get(&format!(
"{}/pulls/{}/files",
self.repository().url(client),
self.number
));
client.json(req).await
}
}
// Zulip <-> GitHub
/// 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)
}
}
}
impl Issue {
pub fn to_zulip_github_reference(&self) -> ZulipGitHubReference {
ZulipGitHubReference {
number: self.number,
title: self.title.clone(),
repository: self.repository().clone(),
}
}
}
// Issue repository
#[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 {
pub(crate) fn url(&self, client: &GithubClient) -> String {
format!(
"{}/repos/{}/{}",
client.api_url, self.organization, self.repository
)
}
pub(crate) fn full_repo_name(&self) -> String {
format!("{}/{}", self.organization, self.repository)
}
pub(crate) 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>()
.is_some_and(|e| e.status() == Some(StatusCode::NOT_FOUND))
{
Ok(false)
} else {
Err(e)
}
}
}
}
}
// Collaborator permission
#[derive(Debug, serde::Deserialize)]
pub struct CollaboratorPermission {
pub permission: String,
}
impl IssueRepository {
pub(crate) async fn collaborator_permission(
&self,
client: &GithubClient,
username: &str,
) -> anyhow::Result<CollaboratorPermission> {
let url = format!("{}/collaborators/{username}/permission", self.url(client));
let permission = client.json(client.get(&url)).await?;
Ok(permission)
}
}
#[cfg(test)]
mod tests {
use super::{Issue, Label};
#[test]
fn test_case_insensitive_label_matching() {
let issue_labels = vec![
Label {
name: "E-needs-mcve".to_string(),
},
Label {
name: "T-compiler".to_string(),
},
];
assert_eq!(
Issue::find_label_case_insensitive(&issue_labels, "e-needs-mcve"),
Some(&Label {
name: "E-needs-mcve".to_string()
})
);
assert_eq!(
Issue::find_label_case_insensitive(&issue_labels, "E-NEEDS-MCVE"),
Some(&Label {
name: "E-needs-mcve".to_string()
})
);
assert_eq!(
Issue::find_label_case_insensitive(&issue_labels, "non-existent"),
None
);
}