gitgrip 0.10.0

Multi-repo workflow tool - manage multiple git repositories as one
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
//! GitHub platform adapter

use async_trait::async_trait;
use octocrab::Octocrab;
use std::env;
use std::time::Duration;

use super::traits::{HostingPlatform, LinkedPRRef, PlatformError};
use super::types::*;
use crate::core::manifest::PlatformType;

/// Default connection timeout in seconds
const CONNECT_TIMEOUT_SECS: u64 = 10;
/// Default read timeout in seconds
const READ_TIMEOUT_SECS: u64 = 30;
/// Default write timeout in seconds
const WRITE_TIMEOUT_SECS: u64 = 30;

#[allow(unused_imports)]
use super::rate_limit::{check_rate_limit_warning, parse_github_rate_limits};

#[cfg(feature = "telemetry")]
use crate::telemetry::metrics::GLOBAL_METRICS;
#[cfg(feature = "telemetry")]
use std::time::Instant;
#[cfg(feature = "telemetry")]
use tracing::debug;

#[cfg(not(feature = "telemetry"))]
use tracing::debug;

/// GitHub API adapter
pub struct GitHubAdapter {
    base_url: Option<String>,
}

impl GitHubAdapter {
    /// Create a new GitHub adapter
    pub fn new(base_url: Option<&str>) -> Self {
        Self {
            base_url: base_url.map(|s| s.to_string()),
        }
    }

    /// Create a configured HTTP client with timeouts
    fn http_client() -> reqwest::Client {
        reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
            .timeout(Duration::from_secs(READ_TIMEOUT_SECS))
            .build()
            .unwrap_or_else(|err| {
                debug!(
                    error = %err,
                    "Failed to build HTTP client with timeouts; falling back to default client"
                );
                reqwest::Client::new()
            })
    }

    /// Get configured Octocrab instance with proper timeouts
    async fn get_client(&self) -> Result<Octocrab, PlatformError> {
        let token = self.get_token().await?;

        let mut builder = Octocrab::builder()
            .personal_token(token)
            .set_connect_timeout(Some(Duration::from_secs(CONNECT_TIMEOUT_SECS)))
            .set_read_timeout(Some(Duration::from_secs(READ_TIMEOUT_SECS)))
            .set_write_timeout(Some(Duration::from_secs(WRITE_TIMEOUT_SECS)));

        if let Some(ref base_url) = self.base_url {
            builder = builder
                .base_uri(base_url)
                .map_err(|e| PlatformError::ApiError(format!("Invalid base URL: {}", e)))?;
        }

        builder
            .build()
            .map_err(|e| PlatformError::ApiError(format!("Failed to create client: {}", e)))
    }
}

#[async_trait]
impl HostingPlatform for GitHubAdapter {
    fn platform_type(&self) -> PlatformType {
        PlatformType::GitHub
    }

    async fn get_token(&self) -> Result<String, PlatformError> {
        // Try environment variables first
        if let Ok(token) = env::var("GITHUB_TOKEN") {
            return Ok(token);
        }
        if let Ok(token) = env::var("GH_TOKEN") {
            return Ok(token);
        }

        // Try gh CLI auth
        debug!(target: "gitgrip::cmd", program = "gh", args = ?["auth", "token"], "exec");
        let output = tokio::process::Command::new("gh")
            .args(["auth", "token"])
            .output()
            .await
            .map_err(|e| PlatformError::AuthError(format!("Failed to run gh auth: {}", e)))?;

        if output.status.success() {
            let token = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !token.is_empty() {
                return Ok(token);
            }
        }

        Err(PlatformError::AuthError(
            "No GitHub token found. Set GITHUB_TOKEN or run 'gh auth login'".to_string(),
        ))
    }

    async fn create_pull_request(
        &self,
        owner: &str,
        repo: &str,
        head: &str,
        base: &str,
        title: &str,
        body: Option<&str>,
        draft: bool,
    ) -> Result<PRCreateResult, PlatformError> {
        #[cfg(feature = "telemetry")]
        let start = Instant::now();

        let client = self.get_client().await?;

        let result = client
            .pulls(owner, repo)
            .create(title, head, base)
            .body(body.unwrap_or(""))
            .draft(draft)
            .send()
            .await;

        #[cfg(feature = "telemetry")]
        {
            let duration = start.elapsed();
            let success = result.is_ok();
            GLOBAL_METRICS.record_platform("github", "create_pr", duration, success);
            debug!(
                owner,
                repo,
                head,
                base,
                draft,
                success,
                duration_ms = duration.as_millis() as u64,
                "GitHub create PR complete"
            );
        }

        let pr =
            result.map_err(|e| PlatformError::ApiError(format!("Failed to create PR: {}", e)))?;

        Ok(PRCreateResult {
            number: pr.number,
            url: pr.html_url.map(|u| u.to_string()).unwrap_or_default(),
        })
    }

    async fn get_pull_request(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<PullRequest, PlatformError> {
        let client = self.get_client().await?;

        let pr = client
            .pulls(owner, repo)
            .get(pull_number)
            .await
            .map_err(|e| {
                if e.to_string().contains("404") {
                    PlatformError::NotFound(format!("PR #{} not found", pull_number))
                } else {
                    PlatformError::ApiError(format!("Failed to get PR: {}", e))
                }
            })?;

        let state = if pr.merged_at.is_some() {
            PRState::Merged
        } else {
            match pr.state {
                Some(octocrab::models::IssueState::Open) => PRState::Open,
                Some(octocrab::models::IssueState::Closed) => PRState::Closed,
                _ => PRState::Open,
            }
        };

        Ok(PullRequest {
            number: pr.number,
            url: pr.html_url.map(|u| u.to_string()).unwrap_or_default(),
            title: pr.title.clone().unwrap_or_default(),
            body: pr.body.clone().unwrap_or_default(),
            state,
            merged: pr.merged_at.is_some(),
            mergeable: pr.mergeable,
            head: PRHead {
                ref_name: pr.head.ref_field.clone(),
                sha: pr.head.sha.clone(),
            },
            base: PRBase {
                ref_name: pr.base.ref_field.clone(),
            },
        })
    }

    async fn update_pull_request_body(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        body: &str,
    ) -> Result<(), PlatformError> {
        let client = self.get_client().await?;

        client
            .pulls(owner, repo)
            .update(pull_number)
            .body(body)
            .send()
            .await
            .map_err(|e| PlatformError::ApiError(format!("Failed to update PR body: {}", e)))?;

        Ok(())
    }

    async fn merge_pull_request(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        method: Option<MergeMethod>,
        _delete_branch: bool,
    ) -> Result<bool, PlatformError> {
        #[cfg(feature = "telemetry")]
        let start = Instant::now();

        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        let merge_method_str = match method.unwrap_or(MergeMethod::Merge) {
            MergeMethod::Merge => "merge",
            MergeMethod::Squash => "squash",
            MergeMethod::Rebase => "rebase",
        };

        let url = format!(
            "{}/repos/{}/{}/pulls/{}/merge",
            base_url, owner, repo, pull_number
        );

        let http_client = Self::http_client();
        let response = http_client
            .put(&url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .json(&serde_json::json!({ "merge_method": merge_method_str }))
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        let status = response.status().as_u16();
        let body_text = response.text().await.unwrap_or_default();

        #[cfg(feature = "telemetry")]
        {
            let duration = start.elapsed();
            let success = status == 200;
            GLOBAL_METRICS.record_platform("github", "merge_pr", duration, success);
            debug!(
                owner,
                repo,
                pull_number,
                success,
                duration_ms = duration.as_millis() as u64,
                "GitHub merge PR complete"
            );
        }

        let body_lower = body_text.to_lowercase();

        match status {
            200 => {
                // Parse merged field from response
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body_text) {
                    Ok(parsed["merged"].as_bool().unwrap_or(false))
                } else {
                    Ok(true) // 200 status means success
                }
            }
            405 => {
                if body_lower.contains("head branch was behind")
                    || body_lower.contains("not up to date")
                {
                    Err(PlatformError::BranchBehind(format!(
                        "PR #{} branch is behind base branch",
                        pull_number
                    )))
                } else {
                    // Other 405 errors (not mergeable, etc.)
                    Ok(false)
                }
            }
            403 => {
                if body_lower.contains("protected branch") || body_lower.contains("required") {
                    Err(PlatformError::BranchProtected(format!(
                        "PR #{} is blocked by branch protection rules",
                        pull_number
                    )))
                } else {
                    Err(PlatformError::ApiError(format!(
                        "Failed to merge PR (403): {}",
                        body_text
                    )))
                }
            }
            _ => Err(PlatformError::ApiError(format!(
                "Failed to merge PR ({}): {}",
                status, body_text
            ))),
        }
    }

    async fn update_branch(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<bool, PlatformError> {
        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        let url = format!(
            "{}/repos/{}/{}/pulls/{}/update-branch",
            base_url, owner, repo, pull_number
        );

        let http_client = Self::http_client();
        let response = http_client
            .put(&url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .json(&serde_json::json!({}))
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        match response.status().as_u16() {
            202 => Ok(true),
            422 => Err(PlatformError::ApiError(
                "Cannot update branch: conflicts exist that must be resolved manually".to_string(),
            )),
            status => {
                let error_text = response.text().await.unwrap_or_default();
                Err(PlatformError::ApiError(format!(
                    "Failed to update branch ({}): {}",
                    status, error_text
                )))
            }
        }
    }

    /// Enable auto-merge via `gh` CLI. Uses the CLI instead of the GraphQL API
    /// because the REST API doesn't support auto-merge and the GraphQL mutation
    /// is complex.
    ///
    /// TODO: This ignores `self.base_url`, so it won't work with GitHub
    /// Enterprise instances that use a custom API URL. To support GHE, either
    /// use the GraphQL API or pass `--hostname` to `gh`.
    async fn enable_auto_merge(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        method: Option<MergeMethod>,
    ) -> Result<bool, PlatformError> {
        let merge_flag = match method.unwrap_or(MergeMethod::Squash) {
            MergeMethod::Merge => "--merge",
            MergeMethod::Squash => "--squash",
            MergeMethod::Rebase => "--rebase",
        };

        let repo_arg = format!("{}/{}", owner, repo);
        let pr_str = pull_number.to_string();

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args([
            "pr", "merge", &pr_str, "--auto", merge_flag, "--repo", &repo_arg,
        ]);

        debug!(target: "gitgrip::cmd", program = "gh", args = ?["pr", "merge", &pr_str, "--auto", merge_flag, "--repo", &repo_arg], "exec");
        let output = cmd
            .output()
            .await
            .map_err(|e| PlatformError::ApiError(format!("Failed to run gh CLI: {}", e)))?;

        if output.status.success() {
            Ok(true)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(PlatformError::ApiError(format!(
                "Failed to enable auto-merge for PR #{}: {}",
                pull_number,
                stderr.trim()
            )))
        }
    }

    async fn find_pr_by_branch(
        &self,
        owner: &str,
        repo: &str,
        branch: &str,
    ) -> Result<Option<PRCreateResult>, PlatformError> {
        let client = self.get_client().await?;

        let prs = client
            .pulls(owner, repo)
            .list()
            .state(octocrab::params::State::Open)
            .head(format!("{}:{}", owner, branch))
            .send()
            .await
            .map_err(|e| PlatformError::ApiError(format!("Failed to find PR: {}", e)))?;

        if let Some(pr) = prs.items.first() {
            Ok(Some(PRCreateResult {
                number: pr.number,
                url: pr
                    .html_url
                    .as_ref()
                    .map(|u| u.to_string())
                    .unwrap_or_default(),
            }))
        } else {
            Ok(None)
        }
    }

    async fn is_pull_request_approved(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<bool, PlatformError> {
        let reviews = self
            .get_pull_request_reviews(owner, repo, pull_number)
            .await?;

        // Check for at least one approval and no changes requested.
        // State comes from Debug formatting of octocrab's ReviewState enum,
        // which gives title case without underscores (e.g. "Approved", "ChangesRequested").
        let state_matches = |state: &str, target: &str| -> bool {
            let normalized: String = state.chars().filter(|c| *c != '_').collect();
            normalized.eq_ignore_ascii_case(target)
        };
        let has_approval = reviews.iter().any(|r| state_matches(&r.state, "Approved"));
        let has_changes_requested = reviews
            .iter()
            .any(|r| state_matches(&r.state, "ChangesRequested"));

        Ok(has_approval && !has_changes_requested)
    }

    async fn get_pull_request_reviews(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<Vec<PRReview>, PlatformError> {
        let client = self.get_client().await?;

        let reviews = client
            .pulls(owner, repo)
            .list_reviews(pull_number)
            .send()
            .await
            .map_err(|e| PlatformError::ApiError(format!("Failed to get reviews: {}", e)))?;

        Ok(reviews
            .items
            .iter()
            .map(|r| PRReview {
                state: r.state.map(|s| format!("{:?}", s)).unwrap_or_default(),
                user: r.user.as_ref().map(|u| u.login.clone()).unwrap_or_default(),
            })
            .collect())
    }

    async fn get_status_checks(
        &self,
        owner: &str,
        repo: &str,
        ref_name: &str,
    ) -> Result<StatusCheckResult, PlatformError> {
        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        // Try Check Runs API first (newer GitHub Actions)
        let check_runs_url = format!(
            "{}/repos/{}/{}/commits/{}/check-runs",
            base_url, owner, repo, ref_name
        );

        let http_client = Self::http_client();
        let response = http_client
            .get(&check_runs_url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        if response.status().is_success() {
            #[derive(serde::Deserialize)]
            struct CheckRunsResponse {
                total_count: i64,
                check_runs: Vec<CheckRun>,
            }

            #[derive(serde::Deserialize)]
            struct CheckRun {
                name: String,
                status: String,
                conclusion: Option<String>,
            }

            let check_runs: CheckRunsResponse = response
                .json()
                .await
                .map_err(|e| PlatformError::ParseError(e.to_string()))?;

            if check_runs.total_count > 0 {
                // Determine overall state from check runs
                let (aggregate_state, statuses): (CheckState, Vec<StatusCheck>) =
                    check_runs.check_runs.into_iter().fold(
                        (CheckState::Success, Vec::new()),
                        |(aggregate_state, mut acc), cr| {
                            let check_state = match cr.conclusion.as_deref() {
                                Some("success") => CheckState::Success,
                                Some("failure") | Some("timed_out") => CheckState::Failure,
                                Some("cancelled") => CheckState::Failure,
                                _ => CheckState::Pending, // "in_progress", "queued", "neutral", or null
                            };

                            // Aggregate: any failure = failure, any pending = pending
                            let new_aggregate = match (aggregate_state, check_state) {
                                (CheckState::Failure, _) => CheckState::Failure,
                                (_, CheckState::Failure) => CheckState::Failure,
                                (CheckState::Pending, _) | (_, CheckState::Pending) => {
                                    CheckState::Pending
                                }
                                (CheckState::Success, CheckState::Success) => CheckState::Success,
                            };

                            acc.push(StatusCheck {
                                context: cr.name.clone(),
                                state: cr.conclusion.unwrap_or(cr.status),
                            });

                            (new_aggregate, acc)
                        },
                    );

                return Ok(StatusCheckResult {
                    state: aggregate_state,
                    statuses,
                });
            }
        }

        // Fallback to legacy status checks API
        let status_url = format!(
            "{}/repos/{}/{}/commits/{}/status",
            base_url, owner, repo, ref_name
        );

        let response = http_client
            .get(&status_url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(PlatformError::ApiError(format!(
                "Failed to get status: {}",
                response.status()
            )));
        }

        #[derive(serde::Deserialize)]
        struct CombinedStatus {
            state: String,
            statuses: Vec<StatusEntry>,
        }

        #[derive(serde::Deserialize)]
        struct StatusEntry {
            context: Option<String>,
            state: String,
        }

        let status: CombinedStatus = response
            .json()
            .await
            .map_err(|e| PlatformError::ParseError(e.to_string()))?;

        let state = match status.state.as_str() {
            "success" => CheckState::Success,
            "failure" | "error" => CheckState::Failure,
            _ => CheckState::Pending,
        };

        let statuses = status
            .statuses
            .iter()
            .map(|s| StatusCheck {
                context: s.context.clone().unwrap_or_default(),
                state: s.state.clone(),
            })
            .collect();

        Ok(StatusCheckResult { state, statuses })
    }

    async fn get_allowed_merge_methods(
        &self,
        owner: &str,
        repo: &str,
    ) -> Result<AllowedMergeMethods, PlatformError> {
        let client = self.get_client().await?;

        let repo_info = client
            .repos(owner, repo)
            .get()
            .await
            .map_err(|e| PlatformError::ApiError(format!("Failed to get repo: {}", e)))?;

        Ok(AllowedMergeMethods {
            merge: repo_info.allow_merge_commit.unwrap_or(true),
            squash: repo_info.allow_squash_merge.unwrap_or(true),
            rebase: repo_info.allow_rebase_merge.unwrap_or(true),
        })
    }

    async fn get_pull_request_diff(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<String, PlatformError> {
        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        let url = format!(
            "{}/repos/{}/{}/pulls/{}",
            base_url, owner, repo, pull_number
        );

        let client = Self::http_client();
        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3.diff")
            .header("User-Agent", "gitgrip")
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(PlatformError::ApiError(format!(
                "Failed to get diff: {}",
                response.status()
            )));
        }

        response
            .text()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))
    }

    fn parse_repo_url(&self, url: &str) -> Option<ParsedRepoInfo> {
        // SSH format: git@github.com:owner/repo.git
        if url.starts_with("git@github.com:") {
            let path = url.trim_start_matches("git@github.com:");
            let path = path.trim_end_matches(".git");
            let parts: Vec<&str> = path.split('/').collect();
            if parts.len() >= 2 {
                return Some(ParsedRepoInfo {
                    owner: parts[0].to_string(),
                    repo: parts[parts.len() - 1].to_string(),
                    project: None,
                    platform: Some(PlatformType::GitHub),
                });
            }
        }

        // HTTPS format: https://github.com/owner/repo.git
        if url.contains("github.com") {
            let url = url.trim_end_matches(".git");
            let parts: Vec<&str> = url.split('/').collect();
            if parts.len() >= 2 {
                let owner_idx = parts.iter().position(|&p| p == "github.com")? + 1;
                if owner_idx + 1 < parts.len() {
                    return Some(ParsedRepoInfo {
                        owner: parts[owner_idx].to_string(),
                        repo: parts[owner_idx + 1].to_string(),
                        project: None,
                        platform: Some(PlatformType::GitHub),
                    });
                }
            }
        }

        None
    }

    fn matches_url(&self, url: &str) -> bool {
        url.contains("github.com")
    }

    async fn create_repository(
        &self,
        owner: &str,
        name: &str,
        description: Option<&str>,
        private: bool,
    ) -> Result<String, PlatformError> {
        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        // Check if owner is the authenticated user or an org
        // First, get the authenticated user
        let http_client = Self::http_client();

        let user_response = http_client
            .get(format!("{}/user", base_url))
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        #[derive(serde::Deserialize)]
        struct User {
            login: String,
        }

        let current_user: User = user_response
            .json()
            .await
            .map_err(|e| PlatformError::ParseError(e.to_string()))?;

        // Determine the API endpoint based on whether owner is the user or an org
        let url = if owner.eq_ignore_ascii_case(&current_user.login) {
            format!("{}/user/repos", base_url)
        } else {
            format!("{}/orgs/{}/repos", base_url, owner)
        };

        #[derive(serde::Serialize)]
        struct CreateRepoRequest {
            name: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            description: Option<String>,
            private: bool,
            auto_init: bool,
        }

        let response = http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .json(&CreateRepoRequest {
                name: name.to_string(),
                description: description.map(|s| s.to_string()),
                private,
                auto_init: true, // Initialize with a README so there's a default branch
            })
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            return Err(PlatformError::ApiError(format!(
                "Failed to create repository ({}): {}",
                status, error_text
            )));
        }

        #[derive(serde::Deserialize)]
        struct RepoResponse {
            ssh_url: String,
        }

        let repo: RepoResponse = response
            .json()
            .await
            .map_err(|e| PlatformError::ParseError(e.to_string()))?;

        Ok(repo.ssh_url)
    }

    async fn delete_repository(&self, owner: &str, name: &str) -> Result<(), PlatformError> {
        let token = self.get_token().await?;
        let base_url = self.base_url.as_deref().unwrap_or("https://api.github.com");

        let http_client = Self::http_client();
        let url = format!("{}/repos/{}/{}", base_url, owner, name);

        let response = http_client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "gitgrip")
            .send()
            .await
            .map_err(|e| PlatformError::NetworkError(e.to_string()))?;

        if response.status() == 404 {
            return Err(PlatformError::NotFound(format!(
                "Repository {}/{} not found",
                owner, name
            )));
        }

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            return Err(PlatformError::ApiError(format!(
                "Failed to delete repository ({}): {}",
                status, error_text
            )));
        }

        Ok(())
    }

    fn generate_linked_pr_comment(&self, links: &[LinkedPRRef]) -> String {
        if links.is_empty() {
            return String::new();
        }

        let mut comment = String::from("<!-- gitgrip-linked-prs\n");
        for link in links {
            comment.push_str(&format!("{}:{}\n", link.repo_name, link.number));
        }
        comment.push_str("-->");
        comment
    }

    fn parse_linked_pr_comment(&self, body: &str) -> Vec<LinkedPRRef> {
        let start_marker = "<!-- gitgrip-linked-prs";
        let end_marker = "-->";

        let Some(start) = body.find(start_marker) else {
            return Vec::new();
        };

        let content_start = start + start_marker.len();
        let Some(end) = body[content_start..].find(end_marker) else {
            return Vec::new();
        };

        let content = &body[content_start..content_start + end];

        content
            .lines()
            .filter_map(|line| {
                let line = line.trim();
                if line.is_empty() {
                    return None;
                }

                let parts: Vec<&str> = line.splitn(2, ':').collect();
                if parts.len() != 2 {
                    return None;
                }

                let number = parts[1].parse().ok()?;
                Some(LinkedPRRef {
                    repo_name: parts[0].to_string(),
                    number,
                })
            })
            .collect()
    }
}

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

    #[test]
    fn test_parse_github_ssh_url() {
        let adapter = GitHubAdapter::new(None);

        let result = adapter.parse_repo_url("git@github.com:user/repo.git");
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.owner, "user");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_https_url() {
        let adapter = GitHubAdapter::new(None);

        let result = adapter.parse_repo_url("https://github.com/user/repo.git");
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.owner, "user");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_matches_url() {
        let adapter = GitHubAdapter::new(None);

        assert!(adapter.matches_url("git@github.com:user/repo.git"));
        assert!(adapter.matches_url("https://github.com/user/repo.git"));
        assert!(!adapter.matches_url("git@gitlab.com:user/repo.git"));
    }

    #[test]
    fn test_linked_pr_comment_roundtrip() {
        let adapter = GitHubAdapter::new(None);

        let links = vec![
            LinkedPRRef {
                repo_name: "frontend".to_string(),
                number: 42,
            },
            LinkedPRRef {
                repo_name: "backend".to_string(),
                number: 123,
            },
        ];

        let comment = adapter.generate_linked_pr_comment(&links);
        let parsed = adapter.parse_linked_pr_comment(&comment);

        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].repo_name, "frontend");
        assert_eq!(parsed[0].number, 42);
        assert_eq!(parsed[1].repo_name, "backend");
        assert_eq!(parsed[1].number, 123);
    }
}