pcu 0.6.14

A CI tool to update change log in a PR
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
use std::{
    fmt::Display,
    io::Write,
    path::Path,
    process::{Command, Stdio},
};

use clap::ValueEnum;
use git2::{
    build::CheckoutBuilder, BranchType, Direction, FetchOptions, Oid, PushOptions, RemoteCallbacks,
    Signature, Status, StatusOptions,
};
use git2_credentials::CredentialHandler;
use log::log_enabled;
// use octocrate::repos::list_tags::Query;
use owo_colors::{OwoColorize, Style};
use tracing::instrument;

use crate::{
    client::graphql::{GraphQLGetOpenPRs, GraphQLGetTag, GraphQLLabelPR},
    Client, Error,
};

const GIT_USER_SIGNATURE: &str = "user.signingkey";
const DEFAULT_COMMIT_MESSAGE: &str = "chore: commit staged files";
const DEFAULT_REBASE_LOGINS: &str = "renovate,mend,app/renovate";

#[derive(ValueEnum, Debug, Default, Clone, Copy, PartialEq)]
pub enum Sign {
    #[default]
    Gpg,
    None,
}

/// Represents commit signing configuration with optional signoff
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SignConfig {
    pub sign: Sign,
    pub signoff: bool,
}

impl Default for SignConfig {
    fn default() -> Self {
        SignConfig {
            sign: Sign::Gpg,
            signoff: true,
        }
    }
}

impl SignConfig {
    /// Create a new SignConfig with the given sign type and signoff enabled
    pub fn new(sign: Sign) -> Self {
        SignConfig {
            sign,
            signoff: true,
        }
    }

    /// Create a new SignConfig with signoff setting
    pub fn with_signoff(sign: Sign, signoff: bool) -> Self {
        SignConfig { sign, signoff }
    }

    /// Check if signoff is enabled
    pub fn is_signoff_enabled(&self) -> bool {
        self.signoff
    }

    /// Set signoff enabled or disabled
    pub fn set_signoff(mut self, enabled: bool) -> Self {
        self.signoff = enabled;
        self
    }
}

/// Generate a signoff line from a git signature
/// Returns a string in the format: "Signed-off-by: Name \<email\>"
fn generate_signoff(sig: &Signature) -> String {
    format!(
        "Signed-off-by: {} <{}>",
        sig.name().unwrap_or(""),
        sig.email().unwrap_or("")
    )
}

/// Append signoff to commit message if enabled
fn append_signoff_to_message(message: &str, sig: &Signature, sign_config: &SignConfig) -> String {
    if !sign_config.is_signoff_enabled() {
        return message.to_string();
    }

    let signoff = generate_signoff(sig);

    // Check if message already contains this exact signoff
    if message.contains(&signoff) {
        return message.to_string();
    }

    // Append signoff with a blank line before it
    if message.is_empty() {
        signoff
    } else {
        format!("{message}\n\n{signoff}")
    }
}

#[derive(Debug, Default)]
pub struct BranchReport {
    pub ahead: usize,
    pub behind: usize,
}

impl Display for BranchReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BranchReport {
                ahead: 0,
                behind: 0,
            } => write!(f, "Your branch is up to date."),
            _ => write!(
                f,
                "Your branch is {} commits ahead and {} commits behind",
                self.ahead, self.behind
            ),
        }
    }
}

pub trait GitOps {
    fn fetch_origin(&self) -> Result<(), Error>;
    fn fetch_branch(&self, branch: &str) -> Result<(), Error>;
    fn checkout_branch(&self, branch: &str) -> Result<(), Error>;
    fn branch_status(&self) -> Result<BranchReport, Error>;
    fn branch_list(&self) -> Result<String, Error>;
    fn repo_status(&self) -> Result<String, Error>;
    fn repo_files_not_staged(&self) -> Result<Vec<(String, Status)>, Error>;
    fn repo_files_staged(&self) -> Result<Vec<(String, Status)>, Error>;
    fn stage_files(&self, files: Vec<(String, Status)>) -> Result<(), Error>;
    #[allow(async_fn_in_trait)]
    async fn commit_changed_files(
        &self,
        sign_config: SignConfig,
        commit_message: &str,
        prefix: &str,
        tag_opt: Option<&str>,
    ) -> Result<(), Error>;
    fn commit_staged(
        &self,
        sign_config: SignConfig,
        commit_message: &str,
        prefix: &str,
        tag: Option<&str>,
    ) -> Result<(), Error>;
    fn push_commit(
        &self,
        prefix: &str,
        version: Option<&str>,
        no_push: bool,
        bot_user_name: &str,
    ) -> Result<(), Error>;
    #[allow(async_fn_in_trait)]
    async fn label_next_pr(
        &self,
        authors: &[String],
        label: Option<&str>,
        desc: Option<&str>,
        colour: Option<&str>,
    ) -> Result<Option<String>, Error>;
    fn create_tag(&self, tag: &str, commit_id: Oid, sig: &Signature) -> Result<(), Error>;
    fn create_signed_tag(&self, tag: &str) -> Result<(), Error>;
    #[allow(async_fn_in_trait)]
    async fn tag_exists(&self, tag: &str) -> bool;
    #[allow(async_fn_in_trait)]
    async fn get_commitish_for_tag(&self, version: &str) -> Result<String, Error>;
}

impl GitOps for Client {
    fn create_tag(&self, tag: &str, commit_id: Oid, sig: &Signature) -> Result<(), Error> {
        let object = self.git_repo.find_object(commit_id, None)?;
        self.git_repo.tag(tag, &object, sig, tag, true)?;

        let mut revwalk = self.git_repo.revwalk()?;
        let reference = format!("refs/tags/{tag}");
        revwalk.push_ref(&reference)?;
        Ok(())
    }

    fn create_signed_tag(&self, tag: &str) -> Result<(), Error> {
        let workdir = self
            .git_repo
            .workdir()
            .ok_or_else(|| Error::GitError("repository has no working directory".into()))?;

        log::trace!("Creating GPG-signed tag {tag} in {}", workdir.display());

        let output = Command::new("git")
            .args(["tag", "-s", tag, "-m", tag])
            .current_dir(workdir)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::GpgError(format!(
                "failed to create signed tag '{tag}': {stderr}"
            )));
        }

        log::info!("Created GPG-signed tag {tag}");
        Ok(())
    }

    // fn tag_exists(&self, tag: &str) -> bool {
    //     let names = self.git_repo.tag_names(Some(tag));

    //     if names.is_err() {
    //         return false;
    //     };

    //     let names = names.unwrap();

    //     if names.is_empty() {
    //         return false;
    //     }

    //     true
    // }

    async fn tag_exists(&self, tag: &str) -> bool {
        self.get_tag(tag).await.is_ok()
    }

    async fn get_commitish_for_tag(&self, tag: &str) -> Result<String, Error> {
        log::trace!("Get commitish for tag: {tag}");
        log::trace!(
            "Get tags for owner {:?} and repo: {:?}",
            self.owner(),
            self.repo()
        );

        let tags = self.get_tag(tag).await?;

        if let Some(commit_id) = tags.commit_sha() {
            log::trace!("Commit id: {commit_id}");
            Ok(commit_id)
        } else {
            Err(Error::TagNotFound(tag.to_string()))
        }

        // let mut page_number = 1;
        // let mut more_pages = true;
        // while more_pages {
        //     let query = Query {
        //         per_page: Some(50),
        //         page: Some(page_number),
        //     };

        //     let page = self
        //         .github_rest
        //         .repos
        //         .list_tags(self.owner(), self.repo())
        //         .query(&query)
        //         .send_with_response()
        //         .await?;

        //     for t in page.data {
        //         log::trace!("Tag: {}", t.name);
        //         if t.name == tag {
        //             return Ok(t.commit.sha);
        //         }
        //     }

        //     if let Some(link) = page.headers.get("link") {
        //         if let Ok(link) = link.to_str() {
        //             if !link.contains("rel=\"next\"") {
        //                 more_pages = false
        //             };
        //         }
        //     } else {
        //         more_pages = false;
        //     }

        //     page_number += 1;
        // }

        // Err(Error::TagNotFound(tag.to_string()))
    }

    /// Report the status of the git repo in a human readable format
    fn repo_status(&self) -> Result<String, Error> {
        let statuses = self.git_repo.statuses(None)?;

        log::trace!("Repo status length: {:?}", statuses.len());

        Ok(print_long(&statuses))
    }

    /// Report a list of the files that have not been staged
    fn repo_files_not_staged(&self) -> Result<Vec<(String, Status)>, Error> {
        let mut options = StatusOptions::new();
        options
            .show(git2::StatusShow::Workdir)
            .include_untracked(true)
            .recurse_untracked_dirs(true);
        log::trace!("Options: Show Workdir, include untracked, recurse ignored dirs");

        let statuses = self.git_repo.statuses(Some(&mut options))?;

        log::trace!("Repo status length: {:?}", statuses.len());
        if log::log_enabled!(log::Level::Trace) {
            for status in statuses.iter() {
                for status in status.status() {
                    log::trace!("Status: {status:?}");
                }
            }
        }

        let files: Vec<(String, Status)> = statuses
            .iter()
            .map(|s| (s.path().unwrap_or_default().to_string(), s.status()))
            .collect();

        log::trace!("Files: {files:#?}");

        Ok(files)
    }

    /// Report a list of the files that have not been staged
    fn repo_files_staged(&self) -> Result<Vec<(String, Status)>, Error> {
        let mut options = StatusOptions::new();
        options
            .show(git2::StatusShow::Index)
            .include_untracked(true)
            .recurse_untracked_dirs(true);
        log::trace!("Options: Show Index, include untracked, recurse ignored dirs");

        let statuses = self.git_repo.statuses(Some(&mut options))?;

        log::trace!("Repo status length: {:?}", statuses.len());

        let files: Vec<(String, Status)> = statuses
            .iter()
            .map(|s| (s.path().unwrap_or_default().to_string(), s.status()))
            .collect();

        Ok(files)
    }

    fn stage_files(&self, files: Vec<(String, Status)>) -> Result<(), Error> {
        let mut index = self.git_repo.index()?;

        for file in files {
            match file.1 {
                Status::INDEX_NEW
                | Status::INDEX_MODIFIED
                | Status::WT_NEW
                | Status::WT_MODIFIED => {
                    index.add_path(Path::new(&file.0))?;
                }
                Status::INDEX_DELETED | Status::WT_DELETED => {
                    index.remove_path(Path::new(&file.0))?;
                }
                _ => {}
            }
        }

        index.write()?;

        Ok(())
    }

    async fn commit_changed_files(
        &self,
        sign_config: SignConfig,
        commit_message: &str,
        prefix: &str,
        tag_opt: Option<&str>,
    ) -> Result<(), Error> {
        let hdr_style = Style::new().bold().underline();
        log::debug!("{}", "Check WorkDir".style(hdr_style));

        let files_in_workdir = self.repo_files_not_staged()?;

        log::debug!("WorkDir files:\n\t{files_in_workdir:?}");
        log::debug!("Staged files:\n\t{:?}", self.repo_files_staged()?);
        log::debug!("Branch status: {}", self.branch_status()?);

        log::info!("Stage the changes for commit");

        if !files_in_workdir.is_empty() {
            self.stage_files(files_in_workdir)?;
        }

        log::debug!("{}", "Check Staged".style(hdr_style));
        log::debug!("WorkDir files:\n\t{:?}", self.repo_files_not_staged()?);

        let files_staged_for_commit = self.repo_files_staged()?;

        log::debug!("Staged files:\n\t{files_staged_for_commit:?}");
        log::debug!("Branch status: {}", self.branch_status()?);

        if !files_staged_for_commit.is_empty() {
            log::info!("Commit the staged changes with commit message: {commit_message}");
            self.commit_staged(sign_config, commit_message, prefix, tag_opt)?;
            log::debug!("{}", "Check Committed".style(hdr_style));
            log::debug!("WorkDir files:\n\t{:?}", self.repo_files_not_staged()?);
            let files_staged_for_commit = self.repo_files_staged()?;
            log::debug!("Staged files:\n\t{files_staged_for_commit:?}");
            log::info!("Branch status: {}", self.branch_status()?);
        } else {
            log::info!("No files to commit")
        }

        Ok(())
    }

    fn commit_staged(
        &self,
        sign_config: SignConfig,
        commit_message: &str,
        prefix: &str,
        tag: Option<&str>,
    ) -> Result<(), Error> {
        log::trace!("Commit staged with sign {:?}", sign_config.sign);

        log::trace!("Checking commit message: `{commit_message}`");
        let commit_message = if !commit_message.is_empty() {
            log::trace!("Using commit message passed to the function");
            commit_message
        } else if !self.commit_message.is_empty() {
            log::trace!("Using commit message set in the calling struct");
            &self.commit_message.clone()
        } else {
            log::trace!("Using default commit message");
            DEFAULT_COMMIT_MESSAGE
        };

        log::debug!("Commit message: {commit_message}");

        let mut index = self.git_repo.index()?;
        let tree_id = index.write_tree()?;
        let head = self.git_repo.head()?;
        let parent = self.git_repo.find_commit(head.target().unwrap())?;
        let sig = self.git_repo.signature()?;

        // Append signoff to commit message if enabled
        let commit_message_with_signoff =
            append_signoff_to_message(commit_message, &sig, &sign_config);
        log::trace!("Commit message with signoff: {commit_message_with_signoff}");

        let commit_id = match sign_config.sign {
            Sign::None => self.git_repo.commit(
                Some("HEAD"),
                &sig,
                &sig,
                &commit_message_with_signoff,
                &self.git_repo.find_tree(tree_id)?,
                &[&parent],
            )?,
            Sign::Gpg => {
                let commit_buffer = self.git_repo.commit_create_buffer(
                    &sig,
                    &sig,
                    &commit_message_with_signoff,
                    &self.git_repo.find_tree(tree_id)?,
                    &[&parent],
                )?;
                let commit_str = std::str::from_utf8(&commit_buffer).unwrap();

                let signature = self.git_repo.config()?.get_string(GIT_USER_SIGNATURE)?;

                let short_sign = signature[12..].to_string();
                log::trace!("Signature short: {short_sign}");

                let gpg_args = vec!["--status-fd", "2", "-bsau", signature.as_str()];
                log::trace!("gpg args: {gpg_args:?}");

                let mut cmd = Command::new("gpg");
                cmd.args(gpg_args)
                    .stdin(Stdio::piped())
                    .stdout(Stdio::piped())
                    .stderr(Stdio::piped());

                let mut child = cmd.spawn()?;

                let mut stdin = child.stdin.take().ok_or(Error::Stdin)?;
                log::trace!("Secured access to stdin");

                log::trace!("Input for signing:\n-----\n{commit_str}\n-----");

                stdin.write_all(commit_str.as_bytes())?;
                log::trace!("writing complete");
                drop(stdin); // close stdin to not block indefinitely
                log::trace!("stdin closed");

                let output = child.wait_with_output()?;
                log::trace!("secured output");

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    log::trace!("stderr: {stderr}");
                    return Err(Error::Stdout(stderr.to_string()));
                }

                let stderr = std::str::from_utf8(&output.stderr)?;

                if !stderr.contains("\n[GNUPG:] SIG_CREATED ") {
                    return Err(Error::GpgError(
                        "failed to sign data, program gpg failed, SIG_CREATED not seen in stderr"
                            .to_string(),
                    ));
                }
                log::trace!("Error checking completed without error");

                let commit_signature = std::str::from_utf8(&output.stdout)?;

                log::trace!("secured signed commit:\n{commit_signature}");

                let commit_id =
                    self.git_repo
                        .commit_signed(commit_str, commit_signature, Some("gpgsig"))?;

                // manually advance to the new commit id
                self.git_repo
                    .head()?
                    .set_target(commit_id, commit_message)?;

                log::trace!("head updated");

                commit_id
            }
        };

        if let Some(version_tag) = tag {
            let version_tag = format!("{prefix}{version_tag}");
            if requires_signed_tag(&sign_config.sign) {
                self.create_signed_tag(&version_tag)?;
            } else {
                self.create_tag(&version_tag, commit_id, &sig)?;
            }
        }

        Ok(())
    }

    fn push_commit(
        &self,
        prefix: &str,
        version: Option<&str>,
        no_push: bool,
        _bot_user_name: &str,
    ) -> Result<(), Error> {
        log::trace!("version: {version:?} and no_push: {no_push}");
        let mut remote = self.git_repo.find_remote("origin")?;
        let remote_url = remote.url().unwrap_or("<unknown>").to_string();
        log::info!("Push target: {remote_url}");

        // Use the stored GitHub token directly for HTTPS remotes (GitHub App
        // installation token or PAT), falling back to CredentialHandler (SSH
        // key agent) for SSH remotes.  This ensures pcu always authenticates
        // as its intended identity regardless of how CircleCI triggered the
        // pipeline (OAuth/SSH vs GitHub App/HTTPS).
        let token_connect = self.github_token.clone();
        let mut callbacks = RemoteCallbacks::new();
        callbacks.credentials(move |url, username, allowed| {
            log::info!(
                "Push auth: url={url}, username={}, credential_types={allowed:?}",
                username.unwrap_or("<none>")
            );
            if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT)
                && !token_connect.is_empty()
            {
                log::info!("Authenticating with GitHub App/PAT token");
                git2::Cred::userpass_plaintext("x-access-token", &token_connect)
            } else {
                let git_config = git2::Config::open_default().unwrap();
                CredentialHandler::new(git_config).try_next_credential(url, username, allowed)
            }
        });
        let mut connection = remote.connect_auth(Direction::Push, Some(callbacks), None)?;
        let remote = connection.remote();

        let local_branch = self
            .git_repo
            .find_branch(self.branch_or_main(), BranchType::Local)?;
        log::trace!("Found local branch: {}", local_branch.name()?.unwrap());

        if log_enabled!(log::Level::Trace) {
            list_tags();
        };

        let branch_ref = local_branch.into_reference();
        let mut push_refs = Vec::new();
        let commit_ref = if let Some(br) = branch_ref.name() {
            let r = format!("{br}:{br}");
            r
        } else {
            "".to_string()
        };

        if !commit_ref.is_empty() {
            push_refs.push(&commit_ref)
        }

        #[allow(unused_assignments)]
        let mut tag_ref = String::from("");

        if let Some(version_tag) = version {
            log::trace!("Found version tag: {prefix}{version_tag}");
            tag_ref = format!("refs/tags/{prefix}{version_tag}:refs/tags/{prefix}{version_tag}");
            log::trace!("Tag ref: {tag_ref}");
            push_refs.push(&tag_ref);
        };

        log::trace!("Push refs: {push_refs:?}");
        let token_push = self.github_token.clone();
        let mut call_backs = RemoteCallbacks::new();
        call_backs.credentials(move |url, username, allowed| {
            log::info!(
                "Push auth: url={url}, username={}, credential_types={allowed:?}",
                username.unwrap_or("<none>")
            );
            if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) && !token_push.is_empty()
            {
                log::info!("Authenticating with GitHub App/PAT token");
                git2::Cred::userpass_plaintext("x-access-token", &token_push)
            } else {
                let git_config = git2::Config::open_default().unwrap();
                CredentialHandler::new(git_config).try_next_credential(url, username, allowed)
            }
        });
        call_backs.push_transfer_progress(progress_bar);
        let mut push_opts = PushOptions::new();
        push_opts.remote_callbacks(call_backs);

        if !no_push {
            remote.push(&push_refs, Some(&mut push_opts))?;
        }

        Ok(())
    }

    /// Rebase the next pr of dependency updates if any
    #[instrument(skip(self))]
    async fn label_next_pr(
        &self,
        authors: &[String],
        label: Option<&str>,
        desc: Option<&str>,
        colour: Option<&str>,
    ) -> Result<Option<String>, Error> {
        log::debug!("Rebase next PR");

        let prs = self.get_open_pull_requests().await?;

        if prs.is_empty() {
            return Ok(None);
        };

        log::trace!("Found {prs:?} open PRs");

        let qualified_authors: Vec<String> = if authors.is_empty() {
            DEFAULT_REBASE_LOGINS
                .split(',')
                .map(|i| i.to_string())
                .collect()
        } else {
            authors.to_vec()
        };

        let mut prs: Vec<_> = prs
            .iter()
            .filter(|pr| qualified_authors.contains(&pr.login))
            .collect();

        if prs.is_empty() {
            log::trace!("Found no open PRs for {qualified_authors:?}");
            return Ok(None);
        };

        log::trace!("Found {prs:?} open PRs for {qualified_authors:?}");

        prs.sort_by(|a, b| a.number.cmp(&b.number));
        let next_pr = &prs[0];

        log::trace!("Next PR: {}", next_pr.number);

        self.add_label_to_pr(next_pr.number, label, desc, colour)
            .await?;

        Ok(Some(next_pr.number.to_string()))
    }

    fn branch_list(&self) -> Result<String, Error> {
        let branches = self.git_repo.branches(None)?;

        let mut output = String::from("\nList of branches:\n");
        for item in branches {
            let (branch, branch_type) = item?;
            output = format!(
                "{}\n# Branch and type: {:?}\t{:?}",
                output,
                branch.name(),
                branch_type
            );
        }
        output = format!("{output}\n");

        Ok(output)
    }

    fn fetch_origin(&self) -> Result<(), Error> {
        let mut remote = self.git_repo.find_remote("origin")?;
        let mut callbacks = RemoteCallbacks::new();
        let git_config = git2::Config::open_default().unwrap();
        let mut ch = CredentialHandler::new(git_config);
        callbacks.credentials(move |url, username, allowed| {
            ch.try_next_credential(url, username, allowed)
        });
        let mut fetch_opts = FetchOptions::new();
        fetch_opts.remote_callbacks(callbacks);
        remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?;
        Ok(())
    }

    fn fetch_branch(&self, branch: &str) -> Result<(), Error> {
        let mut remote = self.git_repo.find_remote("origin")?;
        let git_config = git2::Config::open_default().unwrap();
        let mut ch = CredentialHandler::new(git_config);
        let mut callbacks = RemoteCallbacks::new();
        callbacks.credentials(move |url, username, allowed| {
            ch.try_next_credential(url, username, allowed)
        });

        let mut fetch_opts = FetchOptions::new();
        fetch_opts.remote_callbacks(callbacks);

        let refspec = format!("refs/heads/{branch}:refs/remotes/origin/{branch}");
        remote.fetch(&[&refspec], Some(&mut fetch_opts), None)?;

        log::debug!("Fetched branch: {branch}");
        Ok(())
    }

    fn checkout_branch(&self, branch: &str) -> Result<(), Error> {
        let origin_ref = format!("origin/{branch}");
        let remote_branch = self.git_repo.find_branch(&origin_ref, BranchType::Remote)?;
        let commit = remote_branch.get().peel_to_commit()?;

        // Create or fast-forward local branch to match the remote
        match self.git_repo.find_branch(branch, BranchType::Local) {
            Ok(local_branch) => {
                let mut reference = local_branch.into_reference();
                reference.set_target(commit.id(), "checkout: fast-forward")?;
            }
            Err(_) => {
                self.git_repo.branch(branch, &commit, false)?;
            }
        }

        self.git_repo.set_head(&format!("refs/heads/{branch}"))?;
        self.git_repo
            .checkout_head(Some(CheckoutBuilder::default().force()))?;

        log::debug!("Checked out branch: {branch}");
        Ok(())
    }

    fn branch_status(&self) -> Result<BranchReport, Error> {
        let branch_remote = self.git_repo.find_branch(
            format!("origin/{}", self.branch_or_main()).as_str(),
            git2::BranchType::Remote,
        )?;

        if branch_remote.get().target() == self.git_repo.head()?.target() {
            return Ok(BranchReport::default());
        }

        let local = self.git_repo.head()?.target().unwrap();
        let remote = branch_remote.get().target().unwrap();

        let (ahead, behind) = self.git_repo.graph_ahead_behind(local, remote)?;

        Ok(BranchReport { ahead, behind })
    }
}

fn progress_bar(current: usize, total: usize, bytes: usize) {
    let percent = (current as f32 / total as f32) * 100.0;

    let percent = percent as u8;

    log::trace!("Calculated percent: {percent}");

    match percent {
        10 => log::trace!("{percent}%"),
        25 => log::trace!("{percent}%"),
        40 => log::trace!("{percent}%"),
        55 => log::trace!("{percent}%"),
        80 => log::trace!("{percent}%"),
        95 => log::trace!("{percent}%"),
        100 => log::trace!("{percent}%"),
        _ => {}
    }

    log::trace!(
        "{}:- current: {}, total: {}, bytes: {}",
        "Push progress".blue().underline().bold(),
        current.blue().bold(),
        total.blue().bold(),
        bytes.blue().bold()
    );
}

fn list_tags() {
    let output = Command::new("ls")
        .arg("-R")
        .arg(".git/refs")
        .output()
        .expect("ls of the git refs");
    let stdout = output.stdout;
    log::trace!("ls: {}", String::from_utf8_lossy(&stdout));

    let out_string = String::from_utf8_lossy(&stdout);

    let files = out_string.split_terminator("\n").collect::<Vec<&str>>();
    log::trace!("Files: {files:#?}");
}

// This function print out an output similar to git's status command in long
// form, including the command-line hints.
fn print_long(statuses: &git2::Statuses) -> String {
    let mut header = false;
    let mut rm_in_workdir = false;
    let mut changes_in_index = false;
    let mut changed_in_workdir = false;

    let mut output = String::new();

    // Print index changes
    for entry in statuses
        .iter()
        .filter(|e| e.status() != git2::Status::CURRENT)
    {
        if entry.status().contains(git2::Status::WT_DELETED) {
            rm_in_workdir = true;
        }
        let is_status = match entry.status() {
            s if s.contains(git2::Status::INDEX_NEW) => "new file: ",
            s if s.contains(git2::Status::INDEX_MODIFIED) => "modified: ",
            s if s.contains(git2::Status::INDEX_DELETED) => "deleted: ",
            s if s.contains(git2::Status::INDEX_RENAMED) => "renamed: ",
            s if s.contains(git2::Status::INDEX_TYPECHANGE) => "typechange:",
            _ => continue,
        };
        if !header {
            output = format!(
                "{output}\n\
                # Changes to be committed:
                #   (use \"git reset HEAD <file>...\" to unstage)
                #"
            );
            header = true;
        }

        let old_path = entry.head_to_index().unwrap().old_file().path();
        let new_path = entry.head_to_index().unwrap().new_file().path();
        match (old_path, new_path) {
            (Some(old), Some(new)) if old != new => {
                output = format!(
                    "{}\n#\t{}  {} -> {}",
                    output,
                    is_status,
                    old.display(),
                    new.display()
                );
            }
            (old, new) => {
                output = format!(
                    "{}\n#\t{}  {}",
                    output,
                    is_status,
                    old.or(new).unwrap().display()
                );
            }
        }
    }

    if header {
        changes_in_index = true;
        output = format!("{output}\n");
    }
    header = false;

    // Print workdir changes to tracked files
    for entry in statuses.iter() {
        // With `Status::OPT_INCLUDE_UNMODIFIED` (not used in this example)
        // `index_to_workdir` may not be `None` even if there are no differences,
        // in which case it will be a `Delta::Unmodified`.
        if entry.status() == git2::Status::CURRENT || entry.index_to_workdir().is_none() {
            continue;
        }

        let is_status = match entry.status() {
            s if s.contains(git2::Status::WT_MODIFIED) => "modified: ",
            s if s.contains(git2::Status::WT_DELETED) => "deleted: ",
            s if s.contains(git2::Status::WT_RENAMED) => "renamed: ",
            s if s.contains(git2::Status::WT_TYPECHANGE) => "typechange:",
            _ => continue,
        };

        if !header {
            output = format!(
                "{}\n# Changes not staged for commit:\n#   (use \"git add{} <file>...\" to update what will be committed)\n#   (use \"git checkout -- <file>...\" to discard changes in working directory)\n#               ",
                output,
                if rm_in_workdir { "/rm" } else { "" }
            );
            header = true;
        }

        let old_path = entry.index_to_workdir().unwrap().old_file().path();
        let new_path = entry.index_to_workdir().unwrap().new_file().path();
        match (old_path, new_path) {
            (Some(old), Some(new)) if old != new => {
                output = format!(
                    "{}\n#\t{}  {} -> {}",
                    output,
                    is_status,
                    old.display(),
                    new.display()
                );
            }
            (old, new) => {
                output = format!(
                    "{}\n#\t{}  {}",
                    output,
                    is_status,
                    old.or(new).unwrap().display()
                );
            }
        }
    }

    if header {
        changed_in_workdir = true;
        output = format!("{output}\n#\n");
    }
    header = false;

    // Print untracked files
    for entry in statuses
        .iter()
        .filter(|e| e.status() == git2::Status::WT_NEW)
    {
        if !header {
            output = format!(
                "{output}# Untracked files\n#   (use \"git add <file>...\" to include in what will be committed)\n#"
            );
            header = true;
        }
        let file = entry.index_to_workdir().unwrap().old_file().path().unwrap();
        output = format!("{}\n#\t{}", output, file.display());
    }
    header = false;

    // Print ignored files
    for entry in statuses
        .iter()
        .filter(|e| e.status() == git2::Status::IGNORED)
    {
        if !header {
            output = format!(
                "{output}\n# Ignored files\n#   (use \"git add -f <file>...\" to include in what will be committed)\n#"
            );
            header = true;
        }
        let file = entry.index_to_workdir().unwrap().old_file().path().unwrap();
        output = format!("{}\n#\t{}", output, file.display());
    }

    if !changes_in_index && changed_in_workdir {
        output = format!(
            "{output}\n
            no changes added to commit (use \"git add\" and/or \
            \"git commit -a\")"
        );
    }

    output
}

/// Returns `true` when tags created during a commit should be GPG-signed.
pub(crate) fn requires_signed_tag(sign: &Sign) -> bool {
    matches!(sign, Sign::Gpg)
}

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

    #[test]
    fn test_default_rebase_logins_includes_app_renovate() {
        let logins: Vec<&str> = DEFAULT_REBASE_LOGINS.split(',').collect();
        assert!(
            logins.contains(&"app/renovate"),
            "DEFAULT_REBASE_LOGINS should include 'app/renovate' (GitHub App bot login), got: {logins:?}"
        );
    }

    #[test]
    fn test_default_rebase_logins_preserves_existing_defaults() {
        let logins: Vec<&str> = DEFAULT_REBASE_LOGINS.split(',').collect();
        assert!(logins.contains(&"renovate"), "should include 'renovate'");
        assert!(logins.contains(&"mend"), "should include 'mend'");
    }

    #[test]
    fn test_sign_default() {
        let sign = Sign::default();
        assert_eq!(sign, Sign::Gpg, "Default should be Gpg");
    }

    #[test]
    fn test_sign_config_default() {
        let sign_config = SignConfig::default();
        assert_eq!(sign_config.sign, Sign::Gpg);
        assert!(sign_config.signoff, "Default should have signoff enabled");
    }

    #[test]
    fn test_sign_config_is_signoff_enabled() {
        let config_enabled = SignConfig::with_signoff(Sign::Gpg, true);
        assert!(config_enabled.is_signoff_enabled());

        let config_disabled = SignConfig::with_signoff(Sign::Gpg, false);
        assert!(!config_disabled.is_signoff_enabled());

        let config_none_enabled = SignConfig::with_signoff(Sign::None, true);
        assert!(config_none_enabled.is_signoff_enabled());

        let config_none_disabled = SignConfig::with_signoff(Sign::None, false);
        assert!(!config_none_disabled.is_signoff_enabled());
    }

    #[test]
    fn test_sign_config_set_signoff() {
        let config = SignConfig::new(Sign::Gpg);
        assert!(config.is_signoff_enabled());

        let config_disabled = config.set_signoff(false);
        assert!(!config_disabled.is_signoff_enabled());
        assert_eq!(config_disabled.sign, Sign::Gpg);

        let config_none = SignConfig::new(Sign::None);
        let config_enabled = config_none.set_signoff(true);
        assert!(config_enabled.is_signoff_enabled());
        assert_eq!(config_enabled.sign, Sign::None);
    }

    #[test]
    fn test_generate_signoff() {
        let sig = Signature::now("Test User", "test@example.com").unwrap();
        let signoff = generate_signoff(&sig);
        assert_eq!(signoff, "Signed-off-by: Test User <test@example.com>");
    }

    #[rstest]
    #[case(
        "feat: add new feature",
        true,
        "feat: add new feature\n\nSigned-off-by: Test User <test@example.com>"
    )]
    #[case("feat: add new feature", false, "feat: add new feature")]
    #[case("", true, "Signed-off-by: Test User <test@example.com>")]
    #[case("", false, "")]
    fn test_append_signoff_to_message(
        #[case] message: &str,
        #[case] signoff_enabled: bool,
        #[case] expected: &str,
    ) {
        let sig = Signature::now("Test User", "test@example.com").unwrap();
        let sign_config = SignConfig::with_signoff(Sign::Gpg, signoff_enabled);
        let result = append_signoff_to_message(message, &sig, &sign_config);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_append_signoff_already_contains_signoff() {
        let sig = Signature::now("Test User", "test@example.com").unwrap();
        let sign_config = SignConfig::with_signoff(Sign::Gpg, true);
        let message = "feat: add feature\n\nSigned-off-by: Test User <test@example.com>";
        let result = append_signoff_to_message(message, &sig, &sign_config);
        // Should not duplicate the signoff
        assert_eq!(result, message);
    }

    #[test]
    fn test_append_signoff_with_different_signoff() {
        let sig = Signature::now("Test User", "test@example.com").unwrap();
        let sign_config = SignConfig::with_signoff(Sign::Gpg, true);
        let message = "feat: add feature\n\nSigned-off-by: Other User <other@example.com>";
        let result = append_signoff_to_message(message, &sig, &sign_config);
        // Should append a second signoff since it's different
        assert_eq!(result, "feat: add feature\n\nSigned-off-by: Other User <other@example.com>\n\nSigned-off-by: Test User <test@example.com>");
    }

    #[test]
    fn test_append_signoff_none_variant() {
        let sig = Signature::now("Test User", "test@example.com").unwrap();
        let sign_enabled = SignConfig::with_signoff(Sign::None, true);
        let sign_disabled = SignConfig::with_signoff(Sign::None, false);

        let message = "chore: update files";

        let result_enabled = append_signoff_to_message(message, &sig, &sign_enabled);
        assert_eq!(
            result_enabled,
            "chore: update files\n\nSigned-off-by: Test User <test@example.com>"
        );

        let result_disabled = append_signoff_to_message(message, &sig, &sign_disabled);
        assert_eq!(result_disabled, "chore: update files");
    }

    #[test]
    fn test_requires_signed_tag_gpg() {
        assert!(
            requires_signed_tag(&Sign::Gpg),
            "Sign::Gpg must produce a GPG-signed tag"
        );
    }

    #[test]
    fn test_requires_signed_tag_none() {
        assert!(
            !requires_signed_tag(&Sign::None),
            "Sign::None must not sign the tag"
        );
    }
}