release_plz_core 0.36.13

Update version and changelog based on semantic versioning and conventional commits
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
use crate::git::{gitea_client::Gitea, gitlab_client::GitLab};
use crate::{GitHub, GitReleaseInfo};
use std::collections::{HashMap, HashSet};

use crate::pr::Pr;
use crate::response_ext::ResponseExt;
use anyhow::Context;
use http::StatusCode;
use itertools::Itertools;
use reqwest::header::HeaderMap;
use reqwest::{Response, Url};
use reqwest_middleware::ClientBuilder;
use reqwest_retry::{RetryTransientMiddleware, policies::ExponentialBackoff};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing::{debug, info, instrument};

#[derive(Debug, Clone)]
pub enum GitForge {
    Github(GitHub),
    Gitea(Gitea),
    Gitlab(GitLab),
}

impl GitForge {
    fn default_headers(&self) -> anyhow::Result<HeaderMap> {
        match self {
            Self::Github(g) => g.default_headers(),
            Self::Gitea(g) => g.default_headers(),
            Self::Gitlab(g) => g.default_headers(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ForgeType {
    Github,
    Gitea,
    Gitlab,
}

#[derive(Debug)]
pub struct GitClient {
    pub forge: ForgeType,
    pub remote: Remote,
    pub client: reqwest_middleware::ClientWithMiddleware,
}

#[derive(Debug, Clone)]
pub struct Remote {
    pub owner: String,
    pub repo: String,
    pub token: SecretString,
    pub base_url: Url,
}

impl Remote {
    pub fn owner_slash_repo(&self) -> String {
        format!("{}/{}", self.owner, self.repo)
    }
}

#[derive(Deserialize, Debug)]
pub struct PrCommit {
    pub author: Option<Author>,
    pub sha: String,
}

#[derive(Deserialize, Clone, Debug)]
pub struct Author {
    pub id: i32,
    pub login: String,
}

// https://docs.gitlab.com/ee/api/merge_requests.html#get-single-merge-request-commits
#[derive(Deserialize, Clone, Debug)]
pub struct GitLabMrCommit {
    pub id: String,
}

impl From<GitLabMrCommit> for PrCommit {
    fn from(value: GitLabMrCommit) -> Self {
        Self {
            author: None,
            sha: value.id,
        }
    }
}

#[derive(Serialize)]
pub struct CreateReleaseOption<'a> {
    tag_name: &'a str,
    body: &'a str,
    name: &'a str,
    draft: &'a bool,
    prerelease: &'a bool,
    /// Only supported by GitHub.
    #[serde(skip_serializing_if = "Option::is_none")]
    make_latest: Option<String>,
}

#[derive(Deserialize, Clone, Debug)]
pub struct GitPr {
    pub user: Author,
    pub number: u64,
    pub html_url: Url,
    pub head: Commit,
    pub title: String,
    pub body: Option<String>,
    pub labels: Vec<Label>,
}

/// Pull request.
impl GitPr {
    pub fn branch(&self) -> &str {
        self.head.ref_field.as_str()
    }

    pub fn label_names(&self) -> Vec<&str> {
        self.labels.iter().map(|l| l.name.as_str()).collect()
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct Label {
    pub name: String,
    /// ID of the label.
    /// Used by Gitea and GitHub. Not present in GitLab responses.
    id: Option<u64>,
}

impl From<GitLabMr> for GitPr {
    fn from(value: GitLabMr) -> Self {
        let body = if value.description.is_empty() {
            None
        } else {
            Some(value.description)
        };

        let labels = value
            .labels
            .into_iter()
            .map(|l| Label { name: l, id: None })
            .collect();

        Self {
            number: value.iid,
            html_url: value.web_url,
            head: Commit {
                ref_field: value.source_branch,
                sha: value.sha,
            },
            title: value.title,
            body,
            user: Author {
                id: value.author.id,
                login: value.author.username,
            },
            labels,
        }
    }
}

/// Merge request.
#[derive(Deserialize, Clone, Debug)]
pub struct GitLabMr {
    pub author: GitLabAuthor,
    pub iid: u64,
    pub web_url: Url,
    pub sha: String,
    pub source_branch: String,
    pub title: String,
    pub description: String,
    pub labels: Vec<String>,
}

#[derive(Deserialize, Clone, Debug)]
pub struct GitLabAuthor {
    pub id: i32,
    pub username: String,
}

impl From<GitPr> for GitLabMr {
    fn from(value: GitPr) -> Self {
        let desc = value.body.unwrap_or_default();
        let labels: Vec<String> = value.labels.into_iter().map(|l| l.name).collect();

        Self {
            author: GitLabAuthor {
                id: value.user.id,
                username: value.user.login,
            },
            iid: value.number,
            web_url: value.html_url,
            sha: value.head.sha,
            source_branch: value.head.ref_field,
            title: value.title,
            description: desc,
            labels,
        }
    }
}

#[derive(Deserialize, Clone, Debug)]
pub struct Commit {
    #[serde(rename = "ref")]
    pub ref_field: String,
    pub sha: String,
}

/// Representation of a remote contributor.
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct RemoteCommit {
    /// Username of the author.
    pub username: Option<String>,
}

#[derive(Serialize, Default)]
pub struct GitLabMrEdit {
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    state_event: Option<String>,
}

#[derive(Serialize, Default, Debug)]
pub struct PrEdit {
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    state: Option<String>,
}

impl From<PrEdit> for GitLabMrEdit {
    fn from(value: PrEdit) -> Self {
        Self {
            title: value.title,
            description: value.body,
            state_event: value.state,
        }
    }
}

impl PrEdit {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    pub fn with_state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    pub fn contains_edit(&self) -> bool {
        self.title.is_some() || self.body.is_some() || self.state.is_some()
    }
}

impl GitClient {
    pub fn new(forge: GitForge) -> anyhow::Result<Self> {
        let client = {
            let headers = forge.default_headers()?;
            let reqwest_client = crate::http_client::http_client_builder()
                .default_headers(headers)
                .build()
                .context("can't build Git client")?;

            let retry_policy = ExponentialBackoff::builder().build_with_max_retries(3);
            ClientBuilder::new(reqwest_client)
                // Retry failed requests.
                .with(RetryTransientMiddleware::new_with_policy(retry_policy))
                .build()
        };

        let (forge, remote) = match forge {
            GitForge::Github(g) => (ForgeType::Github, g.remote),
            GitForge::Gitea(g) => (ForgeType::Gitea, g.remote),
            GitForge::Gitlab(g) => (ForgeType::Gitlab, g.remote),
        };
        Ok(Self {
            forge,
            remote,
            client,
        })
    }

    pub fn per_page(&self) -> &str {
        match self.forge {
            ForgeType::Github | ForgeType::Gitlab => "per_page",
            ForgeType::Gitea => "limit",
        }
    }

    /// Creates a GitHub/Gitea release.
    pub async fn create_release(&self, release_info: &GitReleaseInfo) -> anyhow::Result<()> {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => self.create_github_release(release_info).await,
            ForgeType::Gitlab => self.create_gitlab_release(release_info).await,
        }
        .context("Failed to create release")
    }

    /// Same as Gitea.
    pub async fn create_github_release(&self, release_info: &GitReleaseInfo) -> anyhow::Result<()> {
        if release_info.latest.is_some() && self.forge == ForgeType::Gitea {
            anyhow::bail!("Gitea does not support the `git_release_latest` option");
        }
        let create_release_options = CreateReleaseOption {
            tag_name: &release_info.git_tag,
            body: &release_info.release_body,
            name: &release_info.release_name,
            draft: &release_info.draft,
            prerelease: &release_info.pre_release,
            make_latest: release_info.latest.map(|l| l.to_string()),
        };
        self.client
            .post(format!("{}/releases", self.repo_url()))
            .json(&create_release_options)
            .send()
            .await?
            .error_for_status()
            .map_err(|e| {
                if let Some(status) = e.status()
                    && status == reqwest::StatusCode::FORBIDDEN
                {
                    return anyhow::anyhow!(e).context(
                        "Make sure your token has sufficient permissions. Learn more at https://release-plz.dev/docs/usage/release or https://release-plz.dev/docs/github/token",
                    );
                }
                anyhow::anyhow!(e)
            })?;
        Ok(())
    }

    pub async fn create_gitlab_release(&self, release_info: &GitReleaseInfo) -> anyhow::Result<()> {
        #[derive(Serialize)]
        pub struct GitlabReleaseOption<'a> {
            name: &'a str,
            tag_name: &'a str,
            description: &'a str,
        }
        let gitlab_release_options = GitlabReleaseOption {
            name: &release_info.release_name,
            tag_name: &release_info.git_tag,
            description: &release_info.release_body,
        };
        self.client
            .post(format!("{}/releases", self.remote.base_url))
            .json(&gitlab_release_options)
            .send()
            .await?
            .error_for_status()
            .map_err(|e| {
                if let Some(status) = e.status()
                    && status == reqwest::StatusCode::FORBIDDEN {
                        return anyhow::anyhow!(e).context(
                            "Make sure your token has sufficient permissions. Learn more at https://release-plz.dev/docs/usage/release#gitlab",
                        );
                    }

                anyhow::anyhow!(e)
            })?;
        Ok(())
    }

    pub fn pulls_url(&self) -> String {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => {
                format!("{}/pulls", self.repo_url())
            }
            ForgeType::Gitlab => {
                format!("{}/merge_requests", self.repo_url())
            }
        }
    }

    pub fn issues_url(&self) -> String {
        format!("{}/issues", self.repo_url())
    }

    pub fn param_value_pr_state_open(&self) -> &'static str {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => "open",
            ForgeType::Gitlab => "opened",
        }
    }

    fn repo_url(&self) -> String {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => {
                format!(
                    "{}repos/{}",
                    self.remote.base_url,
                    self.remote.owner_slash_repo()
                )
            }
            ForgeType::Gitlab => self.remote.base_url.to_string(),
        }
    }

    /// Get all opened Prs which branch starts with the given `branch_prefix`.
    pub async fn opened_prs(&self, branch_prefix: &str) -> anyhow::Result<Vec<GitPr>> {
        let mut page = 1;
        let page_size = 30;
        let mut release_prs: Vec<GitPr> = vec![];
        loop {
            debug!(
                "Loading prs from {}, page {page}",
                self.remote.owner_slash_repo()
            );
            let prs: Vec<GitPr> = self
                .opened_prs_page(page, page_size)
                .await
                .context("Failed to retrieve open PRs")?;
            let prs_len = prs.len();
            let current_release_prs: Vec<GitPr> = prs
                .into_iter()
                .filter(|pr| pr.head.ref_field.starts_with(branch_prefix))
                .collect();
            release_prs.extend(current_release_prs);
            if prs_len < page_size {
                break;
            }
            page += 1;
        }
        Ok(release_prs)
    }

    async fn opened_prs_page(&self, page: i32, page_size: usize) -> anyhow::Result<Vec<GitPr>> {
        let mut url = Url::parse(&self.pulls_url()).context("invalid pulls URL")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("state", self.param_value_pr_state_open());
            qp.append_pair("page", &page.to_string());
            qp.append_pair(self.per_page(), &page_size.to_string());
        }

        let resp = self
            .client
            .get(url)
            .send()
            .await?
            .successful_status()
            .await?;

        self.prs_from_response(resp).await
    }

    async fn prs_from_response(&self, resp: Response) -> anyhow::Result<Vec<GitPr>> {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => resp.json().await.context("failed to parse pr"),
            ForgeType::Gitlab => {
                let gitlab_mrs: Vec<GitLabMr> =
                    resp.json().await.context("failed to parse gitlab mr")?;
                let git_prs: Vec<GitPr> = gitlab_mrs.into_iter().map(|mr| mr.into()).collect();
                Ok(git_prs)
            }
        }
    }

    async fn pr_from_response(&self, resp: Response) -> anyhow::Result<GitPr> {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => resp.json().await.context("failed to parse pr"),
            ForgeType::Gitlab => {
                let gitlab_mr: GitLabMr = resp.json().await.context("failed to parse gitlab mr")?;
                Ok(gitlab_mr.into())
            }
        }
    }

    #[instrument(skip(self))]
    pub async fn close_pr(&self, pr_number: u64) -> anyhow::Result<()> {
        debug!("closing pr #{pr_number}");
        let edit = PrEdit::new().with_state(self.closed_pr_state());
        self.edit_pr(pr_number, edit)
            .await
            .with_context(|| format!("cannot close pr {pr_number}"))?;
        info!("closed pr #{pr_number}");
        Ok(())
    }

    fn closed_pr_state(&self) -> &'static str {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => "closed",
            ForgeType::Gitlab => "close",
        }
    }

    pub async fn edit_pr(&self, pr_number: u64, pr_edit: PrEdit) -> anyhow::Result<()> {
        let req = match self.forge {
            ForgeType::Github | ForgeType::Gitea => self
                .client
                .patch(format!("{}/{}", self.pulls_url(), pr_number))
                .json(&pr_edit),
            ForgeType::Gitlab => {
                let edit_mr: GitLabMrEdit = pr_edit.into();
                self.client
                    .put(format!("{}/merge_requests/{pr_number}", self.repo_url()))
                    .json(&edit_mr)
            }
        };
        debug!("editing pr: {req:?}");

        req.send()
            .await
            .with_context(|| format!("cannot edit pr {pr_number}"))?;

        Ok(())
    }

    #[instrument(skip(self, pr))]
    pub async fn open_pr(&self, pr: &Pr) -> anyhow::Result<GitPr> {
        debug!("Opening PR in {}", self.remote.owner_slash_repo());

        let json_body = match self.forge {
            ForgeType::Github | ForgeType::Gitea => json!({
                "title": pr.title,
                "body": pr.body,
                "base": pr.base_branch,
                "head": pr.branch,
                "draft": pr.draft,
            }),
            // Docs: https://docs.gitlab.com/api/merge_requests/#create-mr
            ForgeType::Gitlab => json!({
                "title": pr.title,
                "description": pr.body,
                "target_branch": pr.base_branch,
                "source_branch": pr.branch,
                "draft": pr.draft,
                // By default, remove the source branch when merging the PR.
                // The checkbox can be unchecked in the UI before merging.
                "remove_source_branch": true
            }),
        };

        let rep = self
            .client
            .post(self.pulls_url())
            .json(&json_body)
            .send()
            .await
            .context("failed when sending the response")?
            .successful_status()
            .await
            .context("received unexpected response")?;

        let git_pr: GitPr = match self.forge {
            ForgeType::Github | ForgeType::Gitea => {
                rep.json().await.context("Failed to parse PR")?
            }
            ForgeType::Gitlab => {
                let gitlab_mr: GitLabMr = rep.json().await.context("Failed to parse Gitlab MR")?;
                gitlab_mr.into()
            }
        };

        info!("opened pr: {}", git_pr.html_url);
        self.add_labels(&pr.labels, git_pr.number)
            .await
            .context("Failed to add labels")?;
        Ok(git_pr)
    }

    #[instrument(skip(self))]
    pub async fn add_labels(&self, labels: &[String], pr_number: u64) -> anyhow::Result<()> {
        if labels.is_empty() {
            return Ok(());
        }

        match self.forge {
            ForgeType::Github => self.post_github_labels(labels, pr_number).await,
            ForgeType::Gitlab => self.post_gitlab_labels(labels, pr_number).await,
            ForgeType::Gitea => self.post_gitea_labels(labels, pr_number).await,
        }
    }

    fn pr_labels_url(&self, pr_number: u64) -> String {
        format!("{}/{}/labels", self.issues_url(), pr_number)
    }

    /// Add all labels to PR
    async fn post_github_labels(&self, labels: &[String], pr_number: u64) -> anyhow::Result<()> {
        self.client
            .post(self.pr_labels_url(pr_number))
            .json(&json!({
                "labels": labels
            }))
            .send()
            .await?
            .successful_status()
            .await?;

        Ok(())
    }

    /// Add all labels to PR
    async fn post_gitlab_labels(&self, labels: &[String], pr_number: u64) -> anyhow::Result<()> {
        self.client
            .put(format!("{}/{}", self.pulls_url(), pr_number))
            .json(&json!({
                "add_labels": labels.iter().join(",")
            }))
            .send()
            .await?
            .successful_status()
            .await?;

        Ok(())
    }

    /// Add all labels to PR
    async fn post_gitea_labels(&self, labels: &[String], pr_number: u64) -> anyhow::Result<()> {
        let (labels_to_create, mut label_ids) = self
            .get_labels_info_and_categorize_labels(labels, pr_number)
            .await?;
        let new_label_ids = self.create_gitea_labels(&labels_to_create).await?;
        label_ids.extend(new_label_ids);
        anyhow::ensure!(
            !label_ids.is_empty(),
            "The provided labels: {labels:?} \n
                were not added to PR #{pr_number}",
        );
        self.client
            .post(self.pr_labels_url(pr_number))
            .json(&json!({ "labels": label_ids }))
            .send()
            .await?
            .successful_status()
            .await?;
        Ok(())
    }

    /// Get Gitea and GitHub repository labels
    async fn get_repository_labels(&self) -> anyhow::Result<Vec<Label>> {
        self.client
            .get(format!("{}/labels", self.repo_url()))
            .send()
            .await?
            .successful_status()
            .await?
            .json()
            .await
            .context("failed to parse labels")
    }

    /// Retrieves and categorizes labels for a PR, ensuring exact matching and deduplication
    /// within the input and against existing PR labels.
    /// # Returns
    /// A tuple containing:
    /// - Vec<String>: Labels that need to be created in the repository
    /// - Vec<u64>: IDs of existing labels to be added to the PR (excluding duplicates and ones already present)
    async fn get_labels_info_and_categorize_labels(
        &self,
        labels: &[String],
        pr_number: u64,
    ) -> anyhow::Result<(Vec<String>, Vec<u64>)> {
        // Fetch both existing repository labels and current PR labels concurrently
        let (existing_labels, pr_info) =
            tokio::try_join!(self.get_repository_labels(), self.get_pr_info(pr_number))?;

        // Create map for lookups
        let existing_label_map: HashMap<&str, &Label> = existing_labels
            .iter()
            .map(|l| (l.name.as_str(), l))
            .collect();

        // Get current PR labels
        let current_pr_labels: HashSet<&str> =
            pr_info.labels.iter().map(|l| l.name.as_str()).collect();

        let mut labels_to_create: Vec<String> = vec![];
        let mut label_ids = Vec::new();

        for label in labels {
            match existing_label_map.get(label.as_str()) {
                Some(l) => {
                    // The label already exists in the repository.
                    // If the label isn't already in the PR, we add it using the label ID.
                    if !current_pr_labels.contains(label.as_str()) {
                        // The label ID is present for Gitea and GitHub
                        label_ids.push(l.id.with_context(|| {
                            format!("failed to extract id from existing label '{}'", l.name)
                        })?);
                    }
                }
                None => {
                    // The label doesn't exist in the repository, so we need to create it.
                    if !labels_to_create.contains(label) {
                        labels_to_create.push(label.clone());
                    }
                }
            }
        }

        Ok((labels_to_create, label_ids))
    }

    async fn create_gitea_labels(&self, labels_to_create: &[String]) -> anyhow::Result<Vec<u64>> {
        let mut label_ids = Vec::new();

        for label in labels_to_create {
            let label_id = self.create_gitea_repository_label(label).await?;
            label_ids.push(label_id);
        }

        Ok(label_ids)
    }

    async fn create_gitea_repository_label(&self, label: &str) -> anyhow::Result<u64> {
        debug!("Forge Gitea creating label: {label}");
        let res = self
            .client
            .post(format!("{}/labels", self.repo_url()))
            .json(&json!({
                "name": label.trim(),
                // Required field - using white (#FFFFFF) as default color
                "color": "#FFFFFF"
            }))
            .send()
            .await?
            .error_for_status()
            .map_err(|err| {
                let status = err.status();
                let err = anyhow::anyhow!(err);
                match status {
                    Some(StatusCode::NOT_FOUND) => {
                        err.context(format!(
                        "Please check if the repository URL '{}' is correct and the user has the necessary permissions to add labels",
                        self.repo_url()
                        ))
                    }
                    Some(StatusCode::UNPROCESSABLE_ENTITY) => {
                        err.context("Please open a GitHub issue: https://github.com/release-plz/release-plz/issues")
                    }
                    _ => {
                        err.context("HTTP response contained no status code when creating label")
                    }
                }
                .context(format!("failed to create label '{label}'"))
        })?;

        let new_label: Label = res.json().await?;
        let label_id = new_label
            .id
            .with_context(|| format!("failed to extract id from label {label}"))?;
        Ok(label_id)
    }

    pub async fn pr_commits(&self, pr_number: u64) -> anyhow::Result<Vec<PrCommit>> {
        let resp = self
            .client
            .get(format!("{}/{}/commits", self.pulls_url(), pr_number))
            .send()
            .await?
            .successful_status()
            .await?;
        self.parse_pr_commits(resp).await
    }

    async fn parse_pr_commits(&self, resp: Response) -> anyhow::Result<Vec<PrCommit>> {
        match self.forge {
            ForgeType::Github | ForgeType::Gitea => {
                resp.json().await.context("failed to parse pr commits")
            }
            ForgeType::Gitlab => {
                let gitlab_commits: Vec<GitLabMrCommit> =
                    resp.json().await.context("failed to parse gitlab mr")?;
                let pr_commits = gitlab_commits
                    .into_iter()
                    .map(|commit| commit.into())
                    .collect();
                Ok(pr_commits)
            }
        }
    }

    /// Only works for GitHub.
    /// From my tests, Gitea doesn't work yet,
    /// but this implementation should be correct.
    pub async fn associated_prs(&self, commit: &str) -> anyhow::Result<Vec<GitPr>> {
        let url = match self.forge {
            ForgeType::Github => {
                format!("{}/commits/{}/pulls", self.repo_url(), commit)
            }
            ForgeType::Gitea => {
                format!("{}/commits/{}/pull", self.repo_url(), commit)
            }
            ForgeType::Gitlab => {
                format!(
                    "{}/repository/commits/{}/merge_requests",
                    self.repo_url(),
                    commit
                )
            }
        };

        let response = self.client.get(url).send().await?;
        if response.status() == StatusCode::NOT_FOUND
            // GitHub returns 422 if the commit doesn't exist/hasn't been pushed to the remote repository.
            || (response.status() == StatusCode::UNPROCESSABLE_ENTITY
                && self.forge == ForgeType::Github)
        {
            debug!(
                "No associated PRs for commit {commit}. This can happen if the commit is not pushed to the remote repository."
            );
            return Ok(vec![]);
        }
        let response = response.successful_status().await?;
        debug!("Associated PR found. Status: {}", response.status());

        let prs = match self.forge {
            ForgeType::Github => {
                let prs: Vec<GitPr> = response
                    .json()
                    .await
                    .context("can't parse associated PRs")?;
                prs
            }
            ForgeType::Gitea => {
                let pr: GitPr = response.json().await.context("can't parse associated PR")?;
                vec![pr]
            }
            ForgeType::Gitlab => {
                let gitlab_mrs: Vec<GitLabMr> = response
                    .json()
                    .await
                    .context("can't parse associated Gitlab MR")?;
                let git_prs: Vec<GitPr> = gitlab_mrs.into_iter().map(|mr| mr.into()).collect();
                git_prs
            }
        };

        let prs_numbers = prs.iter().map(|pr| pr.number).collect::<Vec<_>>();
        debug!("Associated PRs for commit {commit}: {:?}", prs_numbers);
        Ok(prs)
    }

    pub async fn get_pr_info(&self, pr_number: u64) -> anyhow::Result<GitPr> {
        let response = self
            .client
            .get(format!("{}/{}", self.pulls_url(), pr_number))
            .send()
            .await?
            .successful_status()
            .await?;

        self.pr_from_response(response).await
    }

    pub async fn get_prs_info(&self, pr_numbers: &[u64]) -> anyhow::Result<Vec<GitPr>> {
        let mut prs = vec![];
        for pr_number in pr_numbers {
            let pr = self.get_pr_info(*pr_number).await?;
            prs.push(pr);
        }
        Ok(prs)
    }

    pub async fn get_remote_commit(&self, commit: &str) -> Result<RemoteCommit, anyhow::Error> {
        let api_path = self.commits_api_path(commit);
        let response = self.client.get(api_path).send().await?;

        if let Err(err) = response.error_for_status_ref()
            && let Some(StatusCode::NOT_FOUND | StatusCode::UNPROCESSABLE_ENTITY) = err.status()
        {
            // The user didn't push the commit to the remote repository.
            // This can happen if people need to do edits before running release-plz (e.g. cargo hakari).
            // I'm not sure why GitHub returns 422 if the commit doesn't exist.
            return Ok(RemoteCommit { username: None });
        }

        let remote_commit: GitHubCommit = response
            .successful_status()
            .await?
            .json()
            .await
            .context("can't parse commits")?;

        let username = remote_commit.author.and_then(|author| author.login);
        Ok(RemoteCommit { username })
    }

    fn commits_api_path(&self, commit: &str) -> String {
        let commits_path = "commits/";
        let commits_api_path = match self.forge {
            ForgeType::Gitea => {
                format!("git/{commits_path}")
            }
            ForgeType::Github => commits_path.to_string(),
            ForgeType::Gitlab => {
                unimplemented!("Gitlab support for `release-plz release-pr is not implemented yet")
            }
        };
        format!("{}/{commits_api_path}{commit}", self.repo_url())
    }

    /// Create a new branch from the given SHA.
    pub async fn create_branch(&self, branch_name: &str, sha: &str) -> anyhow::Result<()> {
        match self.forge {
            ForgeType::Github => {
                self.post_github_ref(&format!("refs/heads/{branch_name}"), sha)
                    .await
            }
            ForgeType::Gitlab => self.post_gitlab_branch(branch_name, sha).await,
            ForgeType::Gitea => self.post_gitea_branch(branch_name, sha).await,
        }
    }

    async fn post_github_ref(&self, ref_name: &str, sha: &str) -> anyhow::Result<()> {
        let response = self
            .client
            .post(format!("{}/git/refs", self.repo_url()))
            .json(&json!({
                "ref": ref_name,
                "sha": sha
            }))
            .send()
            .await?;

        // GitHub returns 422 (Unprocessable Entity) when the provided commit SHA
        // only exists locally (i.e. it has not been pushed to the remote).
        if response.status() == StatusCode::UNPROCESSABLE_ENTITY {
            // Try to capture the body for extra diagnostics.
            let body = response
                .text()
                .await
                .unwrap_or_else(|_| "<failed to read response body>".to_string());
            anyhow::bail!(
                "failed to create ref {ref_name} with sha {sha}. \
The commit {sha} likely hasn't been pushed to the remote repository yet. \
Please push your local commits and run release-plz again.\nResponse body: {body}"
            );
        }

        response
            .successful_status()
            .await
            .with_context(|| format!("failed to create ref {ref_name} with sha {sha}"))?;
        Ok(())
    }

    async fn post_gitlab_branch(&self, branch_name: &str, sha: &str) -> anyhow::Result<()> {
        self.client
            .post(format!("{}/repository/branches", self.repo_url()))
            .json(&json!({
                "branch": branch_name,
                "ref": sha
            }))
            .send()
            .await?
            .successful_status()
            .await
            .with_context(|| format!("failed to create branch {branch_name} with sha {sha}"))?;
        Ok(())
    }

    async fn post_gitea_branch(&self, branch_name: &str, sha: &str) -> anyhow::Result<()> {
        self.client
            .post(format!("{}/branches", self.repo_url()))
            .json(&json!({
                "new_branch_name": branch_name,
                "old_ref_name": sha
            }))
            .send()
            .await?
            .successful_status()
            .await
            .with_context(|| format!("failed to create branch {branch_name} with sha {sha}"))?;
        Ok(())
    }

    pub async fn patch_github_ref(&self, ref_name: &str, sha: &str) -> anyhow::Result<()> {
        self.client
            .patch(format!("{}/git/refs/{}", self.repo_url(), ref_name))
            .json(&json!({
                "sha": sha,
                "force": true
            }))
            .send()
            .await?
            .successful_status()
            .await
            .with_context(|| format!("failed to update ref {ref_name} with sha {sha}"))?;
        Ok(())
    }

    /// Delete a branch.
    pub async fn delete_branch(&self, branch_name: &str) -> anyhow::Result<()> {
        let url = match self.forge {
            ForgeType::Github => format!("{}/git/refs/heads/{}", self.repo_url(), branch_name),
            ForgeType::Gitlab => format!(
                "{}/repository/branches/{}",
                self.repo_url(),
                urlencoding::encode(branch_name)
            ),
            ForgeType::Gitea => format!(
                "{}/branches/{}",
                self.repo_url(),
                urlencoding::encode(branch_name)
            ),
        };
        self.client
            .delete(url)
            .send()
            .await?
            .successful_status()
            .await
            .context("failed to delete branch")?;
        Ok(())
    }

    /// Creates an annotated tag.
    pub async fn create_tag(
        &self,
        tag_name: &str,
        message: &str,
        sha: &str,
    ) -> Result<(), anyhow::Error> {
        match self.forge {
            ForgeType::Github => self.create_github_tag(tag_name, message, sha).await,
            ForgeType::Gitlab => self.create_gitlab_tag(tag_name, message, sha).await,
            ForgeType::Gitea => self.create_gitea_tag(tag_name, message, sha).await,
        }
    }

    async fn create_github_tag(
        &self,
        tag_name: &str,
        message: &str,
        sha: &str,
    ) -> Result<(), anyhow::Error> {
        let tag_object_sha = self
            .client
            .post(format!("{}/git/tags", self.repo_url()))
            .json(&json!({
                "tag": tag_name,
                "message": message,
                "object": sha,
                "type": "commit"
            }))
            .send()
            .await?
            .successful_status()
            .await?
            .json::<serde_json::Value>()
            .await?
            .get("sha")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .with_context(|| {
                format!("failed to create git tag object for tag '{tag_name}' on '{sha}'")
            })?;
        self.post_github_ref(&format!("refs/tags/{tag_name}"), &tag_object_sha)
            .await
    }

    async fn create_gitlab_tag(
        &self,
        tag_name: &str,
        message: &str,
        sha: &str,
    ) -> Result<(), anyhow::Error> {
        self.client
            .post(format!("{}/repository/tags", self.repo_url()))
            .json(&json!({
                "tag_name": tag_name,
                "ref": sha,
                "message": message
            }))
            .send()
            .await?
            .successful_status()
            .await
            .with_context(|| format!("failed to create git tag '{tag_name}' with ref '{sha}'"))?;
        Ok(())
    }

    async fn create_gitea_tag(
        &self,
        tag_name: &str,
        message: &str,
        sha: &str,
    ) -> Result<(), anyhow::Error> {
        self.client
            .post(format!("{}/tags", self.repo_url()))
            .json(&json!({
                "tag_name": tag_name,
                "target": sha,
                "message": message
            }))
            .send()
            .await?
            .successful_status()
            .await
            .with_context(|| format!("failed to create git tag '{tag_name}' with ref '{sha}'"))?;
        Ok(())
    }
}

pub fn validate_labels(labels: &[String]) -> anyhow::Result<()> {
    let mut unique_labels: HashSet<&str> = HashSet::new();

    for l in labels {
        // use a closure to avoid allocating the error message string unless needed
        let error_msg = || format!("Failed to add label `{l}`:");

        if l.len() > 50 {
            anyhow::bail!(
                "{} it exceeds maximum length of 50 characters.",
                error_msg()
            );
        }

        if l.trim() != l {
            anyhow::bail!(
                "{} leading or trailing whitespace is not allowed.",
                error_msg()
            );
        }

        if l.is_empty() {
            anyhow::bail!("{} empty labels are not allowed.", error_msg());
        }

        let is_label_new = unique_labels.insert(l.as_str());
        if !is_label_new {
            anyhow::bail!("{} duplicate labels are not allowed.", error_msg());
        }
    }
    Ok(())
}

/// Representation of a single commit.
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GitHubCommit {
    /// SHA.
    pub sha: String,
    /// Author of the commit.
    pub author: Option<GitHubCommitAuthor>,
}

/// Author of the commit.
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GitHubCommitAuthor {
    /// Username.
    pub login: Option<String>,
}

/// Returns the list of contributors for the given commits,
/// excluding the PR author and bots.
pub fn contributors_from_commits(commits: &[PrCommit], forge: ForgeType) -> Vec<String> {
    let mut contributors = commits
        .iter()
        .skip(1) // skip pr author
        .flat_map(|commit| &commit.author)
        .filter(|author| {
            let is_gitea_actions_account = forge == ForgeType::Gitea && author.id == -2;
            let is_bot = author.login.ends_with("[bot]") || is_gitea_actions_account;
            !is_bot
        })
        .map(|author| author.login.clone())
        .collect::<Vec<_>>();
    contributors.dedup();
    contributors
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contributors_are_extracted_from_commits() {
        let commits = vec![
            PrCommit {
                author: Some(Author {
                    id: 1,
                    login: "bob".to_string(),
                }),
                sha: "abc".to_string(),
            },
            PrCommit {
                author: Some(Author {
                    id: 2,
                    login: "marco".to_string(),
                }),
                sha: "abc".to_string(),
            },
            PrCommit {
                author: Some(Author {
                    id: 3,
                    login: "release[bot]".to_string(),
                }),
                sha: "abc".to_string(),
            },
            PrCommit {
                author: Some(Author {
                    id: -2,
                    login: "gitea-actions".to_string(),
                }),
                sha: "abc".to_string(),
            },
            PrCommit {
                author: None,
                sha: "abc".to_string(),
            },
        ];
        let contributors = contributors_from_commits(&commits, ForgeType::Gitea);
        assert_eq!(contributors, vec!["marco"]);
    }
}