gitflow-github 2.1.0

gf 的 GitHub 适配器,基于 gh CLI 提供 Issue/PR/Release/Review 等能力。GitHub adapter for gf via gh CLI.
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
//! GitHub Label 和 Milestone 提供者实现。
//!
//! 通过 `gh label` 和 `gh api` CLI 命令实现 [`LabelProvider`] 和
//! [`MilestoneProvider`] trait,支持标签和里程碑的完整生命周期管理。

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use gitflow_core::{
    CoreError, DEFAULT_LIST_LIMIT, FetchStrategy, Paged, Result, fetch_capped,
    label::{
        CreateLabelArgs, CreateMilestoneArgs, LabelData, LabelProvider, MilestoneData,
        MilestoneProvider,
    },
    types::State,
};
use serde::Deserialize;
use tracing::debug;

use crate::{
    GITHUB_API_MAX_PER_PAGE,
    error::parse_gh_error,
    runner::{CommandRunner, RealCommandRunner},
};

/// GitHub Label 提供者,通过 `gh` CLI 管理仓库标签。
///
/// # Examples
///
/// ```no_run
/// use gitflow_github::GitHubLabelProvider;
///
/// let provider = GitHubLabelProvider::new("octocat/hello-world");
/// ```
#[derive(Debug, Clone)]
pub struct GitHubLabelProvider<R: CommandRunner = RealCommandRunner> {
    /// GitHub `owner/repo`。
    repo: String,
    /// 用于执行 `gh` CLI 命令的 runner。
    runner: R,
}

impl GitHubLabelProvider<RealCommandRunner> {
    /// 创建新的 GitHub Label 提供者。
    ///
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            runner: RealCommandRunner,
        }
    }

    /// Create a new provider from a shared [`Session`].
    ///
    /// This enables state reuse across multiple operations in workflow chains.
    #[must_use]
    pub fn with_session(session: &gitflow_core::Session) -> Self {
        Self {
            repo: session.repo.clone(),
            runner: RealCommandRunner,
        }
    }
}

impl<R: CommandRunner> GitHubLabelProvider<R> {
    /// 使用自定义 [`CommandRunner`] 创建提供者。
    ///
    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
        Self {
            repo: repo.into(),
            runner,
        }
    }
}

/// `gh label list/create` 请求的 JSON 字段列表。
const LABEL_FIELDS: &str = "name,color,description";

#[async_trait]
impl<R: CommandRunner + 'static> LabelProvider for GitHubLabelProvider<R> {
    async fn create(&self, args: CreateLabelArgs) -> Result<LabelData> {
        debug!(
            repo = %self.repo,
            name = %args.name,
            color = %args.color,
            "spawning `gh label create`"
        );

        let mut cmd_args: Vec<&str> = vec![
            "label",
            "create",
            &args.name,
            "--color",
            &args.color,
            "--repo",
            &self.repo,
        ];

        if let Some(ref desc) = args.description {
            cmd_args.push("--description");
            cmd_args.push(desc);
        }

        let output =
            self.runner.run("gh", &cmd_args).await.map_err(|e| {
                CoreError::Platform(format!("Failed to spawn gh label create: {e}"))
            })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        // gh label create doesn't return JSON, construct the response manually
        Ok(LabelData {
            name: args.name,
            color: Some(args.color),
            description: args.description,
        })
    }

    async fn list(&self, limit: Option<u32>) -> Result<Paged<LabelData>> {
        let cap = limit.unwrap_or(DEFAULT_LIST_LIMIT);
        let repo = &self.repo;
        let runner = &self.runner;

        debug!(repo = %self.repo, cap, "spawning `gh label list`");

        fetch_capped(FetchStrategy::SingleShot, cap, |_page, want| async move {
            let want_str = want.to_string();
            let output = runner
                .run(
                    "gh",
                    &[
                        "label",
                        "list",
                        "--repo",
                        repo,
                        "--json",
                        LABEL_FIELDS,
                        "--limit",
                        &want_str,
                    ],
                )
                .await
                .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label list: {e}")))?;

            if !output.status.success() {
                return Err(parse_gh_error(&output.stderr).into());
            }

            let labels: Vec<LabelData> =
                serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
            Ok(labels)
        })
        .await
    }

    async fn edit(&self, name: &str, args: CreateLabelArgs) -> Result<LabelData> {
        debug!(repo = %self.repo, name, "spawning `gh label edit`");

        let mut cmd_args: Vec<&str> = vec![
            "label",
            "edit",
            name,
            "--repo",
            &self.repo,
            "--color",
            &args.color,
        ];

        if let Some(ref desc) = args.description {
            cmd_args.push("--description");
            cmd_args.push(desc);
        }

        let output = self
            .runner
            .run("gh", &cmd_args)
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label edit: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        // gh label edit 不返回 JSON,重新 fetch 获取最新数据
        self.fetch_label(name).await
    }

    async fn delete(&self, name: &str) -> Result<()> {
        debug!(repo = %self.repo, name, "spawning `gh label delete`");

        let output = self
            .runner
            .run(
                "gh",
                &["label", "delete", name, "--yes", "--repo", &self.repo],
            )
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label delete: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        Ok(())
    }
}

impl<R: CommandRunner> GitHubLabelProvider<R> {
    /// 获取指定名称的标签数据(内部辅助方法)。
    ///
    /// 调用 `gh api` REST 端点 `repos/{owner}/{repo}/labels/{name}` 重新拉取。
    /// gh 2.97 没有 `label view` 子命令,故不能用 `gh label view --json`。
    async fn fetch_label(&self, name: &str) -> Result<LabelData> {
        let api_path = format!(
            "repos/{repo}/labels/{name}",
            repo = self.repo,
            name = encode_path_segment(name)
        );

        let output = self
            .runner
            .run("gh", &["api", &api_path])
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api label: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let label: LabelData =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(label)
    }
}

/// RFC 3986 路径段编码:仅保留 unreserved 字符,其余按字节百分号编码(大写十六进制)。
///
/// 用于在 `gh api repos/{owner}/{repo}/labels/{name}` 路径中编码标签名,
/// 标签名可能包含空格或特殊字符(如 `good first issue`)。
#[must_use]
fn encode_path_segment(value: &str) -> String {
    const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = String::with_capacity(value.len());
    for b in value.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(char::from(b));
            }
            _ => {
                out.push('%');
                out.push(char::from(HEX_DIGITS[usize::from(b >> 4)]));
                out.push(char::from(HEX_DIGITS[usize::from(b & 0x0F)]));
            }
        }
    }
    out
}

/// GitHub 里程碑提供者,通过 `gh api` 管理仓库里程碑。
///
/// # Examples
///
/// ```no_run
/// use gitflow_github::GitHubMilestoneProvider;
///
/// let provider = GitHubMilestoneProvider::new("octocat/hello-world");
/// ```
#[derive(Debug, Clone)]
pub struct GitHubMilestoneProvider<R: CommandRunner = RealCommandRunner> {
    /// GitHub `owner/repo`。
    repo: String,
    /// 用于执行 `gh` CLI 命令的 runner。
    runner: R,
}

impl GitHubMilestoneProvider<RealCommandRunner> {
    /// 创建新的 GitHub Milestone 提供者。
    ///
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            runner: RealCommandRunner,
        }
    }

    /// Create a new provider from a shared [`Session`].
    ///
    /// This enables state reuse across multiple operations in workflow chains.
    #[must_use]
    pub fn with_session(session: &gitflow_core::Session) -> Self {
        Self {
            repo: session.repo.clone(),
            runner: RealCommandRunner,
        }
    }
}

impl<R: CommandRunner> GitHubMilestoneProvider<R> {
    /// 使用自定义 [`CommandRunner`] 创建提供者。
    ///
    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
        Self {
            repo: repo.into(),
            runner,
        }
    }
}

/// `gh api milestones` 返回的 JSON 结构。
#[derive(Debug, Clone, Deserialize)]
struct MilestoneApiResponse {
    number: u64,
    title: String,
    #[serde(default)]
    description: Option<String>,
    state: String,
    #[serde(default)]
    due_on: Option<String>,
    #[serde(default)]
    closed_issues: u64,
    #[serde(default)]
    open_issues: u64,
}

impl From<MilestoneApiResponse> for MilestoneData {
    fn from(api: MilestoneApiResponse) -> Self {
        Self {
            number: api.number,
            title: api.title,
            description: api.description,
            state: if api.state == "closed" {
                State::Closed
            } else {
                State::Open
            },
            due_on: api.due_on.and_then(|s| {
                DateTime::parse_from_rfc3339(&s).map_or(None, |dt| Some(dt.with_timezone(&Utc)))
            }),
            closed_issues: api.closed_issues,
            open_issues: api.open_issues,
        }
    }
}

#[async_trait]
impl<R: CommandRunner + 'static> MilestoneProvider for GitHubMilestoneProvider<R> {
    async fn create(&self, args: CreateMilestoneArgs) -> Result<MilestoneData> {
        debug!(repo = %self.repo, title = %args.title, "spawning `gh api milestones POST`");

        let api_path = format!("repos/{repo}/milestones", repo = self.repo);

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["api", &api_path, "-X", "POST"])
            .arg("-f")
            .arg(format!("title={}", args.title));

        if let Some(ref desc) = args.description {
            cmd.arg("-f").arg(format!("description={desc}"));
        }

        if let Some(ref due) = args.due_on {
            cmd.arg("-f").arg(format!("due_on={}", due.to_rfc3339()));
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api milestones: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn list(&self, limit: Option<u32>) -> Result<Paged<MilestoneData>> {
        let cap = limit.unwrap_or(DEFAULT_LIST_LIMIT);
        let repo = &self.repo;
        let runner = &self.runner;

        debug!(repo = %self.repo, cap, "spawning `gh api` GET milestones");

        fetch_capped(
            FetchStrategy::Paged {
                per_page: cap.saturating_add(1).min(GITHUB_API_MAX_PER_PAGE),
            },
            cap,
            |page, per_page| async move {
                // gh api 直接接受 per_page / page 查询参数(已实测),
                // 因此无需 --paginate,且截断可被探测。
                let api_path = format!("repos/{repo}/milestones?per_page={per_page}&page={page}");

                let output = runner.run("gh", &["api", &api_path]).await.map_err(|e| {
                    CoreError::Platform(format!("Failed to spawn gh api milestones: {e}"))
                })?;

                if !output.status.success() {
                    return Err(parse_gh_error(&output.stderr).into());
                }

                let milestones: Vec<MilestoneApiResponse> =
                    serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
                Ok(milestones.into_iter().map(MilestoneData::from).collect())
            },
        )
        .await
    }

    async fn edit(&self, number: u64, args: CreateMilestoneArgs) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones PATCH`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["api", &api_path, "-X", "PATCH"]);

        cmd.arg("-f").arg(format!("title={}", args.title));

        if let Some(ref desc) = args.description {
            cmd.arg("-f").arg(format!("description={desc}"));
        }

        if let Some(ref due) = args.due_on {
            cmd.arg("-f").arg(format!("due_on={}", due.to_rfc3339()));
        }

        let output = cmd.output().await.map_err(|e| {
            CoreError::Platform(format!("Failed to spawn gh api milestone edit: {e}"))
        })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn close(&self, number: u64) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones close`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let output = tokio::process::Command::new("gh")
            .args(["api", &api_path, "-X", "PATCH", "-f", "state=closed"])
            .output()
            .await
            .map_err(|e| {
                CoreError::Platform(format!("Failed to spawn gh api milestone close: {e}"))
            })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn reopen(&self, number: u64) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones reopen`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let output = tokio::process::Command::new("gh")
            .args(["api", &api_path, "-X", "PATCH", "-f", "state=open"])
            .output()
            .await
            .map_err(|e| {
                CoreError::Platform(format!("Failed to spawn gh api milestone reopen: {e}"))
            })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runner::{MockCommandRunner, SequencedMockCommandRunner};

    // --- GitHubLabelProvider tests ---

    #[test]
    fn test_should_construct_github_label_provider() {
        let provider = GitHubLabelProvider::new("octocat/hello-world");
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_construct_github_label_provider_from_string() {
        let repo = String::from("octocat/hello-world");
        let provider = GitHubLabelProvider::new(repo);
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_debug_format_label_provider() {
        let provider = GitHubLabelProvider::new("owner/repo");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitHubLabelProvider"));
        assert!(debug.contains("owner/repo"));
    }

    #[test]
    fn test_should_clone_github_label_provider() {
        let original = GitHubLabelProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    #[tokio::test]
    async fn test_should_fetch_label_via_gh_api() {
        let runner = MockCommandRunner::success(
            r#"{"name":"bug","color":"d73a4a","description":"Something isn't working"}"#,
        );
        let provider = GitHubLabelProvider::with_runner("octocat/hello-world", runner.clone());

        let label = provider.fetch_label("bug").await.expect("should fetch");

        assert_eq!(label.name, "bug");
        assert_eq!(label.color.as_deref(), Some("d73a4a"));
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec!["api", "repos/octocat/hello-world/labels/bug"]
        );
    }

    #[tokio::test]
    async fn test_should_encode_label_name_in_api_path() {
        let runner = MockCommandRunner::success(r#"{"name":"good first issue","color":"7057ff"}"#);
        let provider = GitHubLabelProvider::with_runner("octocat/hello-world", runner.clone());

        let label = provider
            .fetch_label("good first issue")
            .await
            .expect("should fetch");

        assert_eq!(label.name, "good first issue");
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec![
                "api",
                "repos/octocat/hello-world/labels/good%20first%20issue"
            ]
        );
    }

    #[tokio::test]
    async fn test_should_edit_label_and_refetch_via_gh_api() {
        let runner =
            MockCommandRunner::success(r#"{"name":"bug","color":"3344ff","description":"probe2"}"#);
        let provider = GitHubLabelProvider::with_runner("byx-darwin/gitflow-cli", runner.clone());

        let args = CreateLabelArgs {
            name: "bug".to_string(),
            color: "3344ff".to_string(),
            description: Some("probe2".to_string()),
        };
        let label = provider.edit("bug", args).await.expect("should edit");

        assert_eq!(label.color.as_deref(), Some("3344ff"));
        let calls = runner.recorded_calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(
            calls[0].1,
            vec![
                "label",
                "edit",
                "bug",
                "--repo",
                "byx-darwin/gitflow-cli",
                "--color",
                "3344ff",
                "--description",
                "probe2"
            ]
        );
        // P1 regression: second call must be `gh api`, NEVER `gh label view`.
        assert_eq!(
            calls[1].1,
            vec!["api", "repos/byx-darwin/gitflow-cli/labels/bug"]
        );
        assert!(
            calls
                .iter()
                .all(|(_, args)| args.first().is_some_and(|a| a != "view")),
            "no `gh label view` call may remain"
        );
    }

    #[tokio::test]
    async fn test_should_fail_when_fetch_label_api_fails() {
        let runner = MockCommandRunner::failure("HTTP 404", 1);
        let provider = GitHubLabelProvider::with_runner("owner/repo", runner);

        let err = provider
            .fetch_label("missing")
            .await
            .expect_err("should fail");
        assert!(err.to_string().contains("GitHub") || err.to_string().contains("执行失败"));
    }

    #[tokio::test]
    async fn test_should_list_labels_with_limit_flag() {
        let runner = MockCommandRunner::success("[]");
        let provider = GitHubLabelProvider::with_runner("owner/repo", runner.clone());

        let paged = provider.list(None).await.expect("should list");

        assert!(paged.items.is_empty());
        assert_eq!(runner.recorded_calls()[0].0, "gh");
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec![
                "label",
                "list",
                "--repo",
                "owner/repo",
                "--json",
                "name,color,description",
                "--limit",
                "1001"
            ]
        );
    }

    #[tokio::test]
    async fn test_should_create_label_via_runner() {
        let runner = MockCommandRunner::success("");
        let provider = GitHubLabelProvider::with_runner("owner/repo", runner.clone());

        let args = CreateLabelArgs {
            name: "bug".to_string(),
            color: "d73a4a".to_string(),
            description: None,
        };
        let label = provider.create(args).await.expect("should create");

        assert_eq!(label.name, "bug");
        assert_eq!(label.color.as_deref(), Some("d73a4a"));
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec![
                "label",
                "create",
                "bug",
                "--color",
                "d73a4a",
                "--repo",
                "owner/repo"
            ]
        );
    }

    #[tokio::test]
    async fn test_should_delete_label_via_runner() {
        let runner = MockCommandRunner::success("");
        let provider = GitHubLabelProvider::with_runner("owner/repo", runner.clone());

        provider.delete("bug").await.expect("should delete");

        assert_eq!(
            runner.recorded_calls()[0].1,
            vec!["label", "delete", "bug", "--yes", "--repo", "owner/repo"]
        );
    }

    #[tokio::test]
    async fn test_should_route_milestone_list_through_runner() {
        let runner = MockCommandRunner::success("[]");
        let provider = GitHubMilestoneProvider::with_runner("owner/repo", runner.clone());

        let paged = provider.list(None).await.expect("should list");

        assert!(paged.items.is_empty());
        let calls = runner.recorded_calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, "gh");
        assert_eq!(calls[0].1[0], "api");
        assert!(calls[0].1[1].contains("per_page=100"));
        assert!(calls[0].1[1].contains("page=1"));
    }

    #[tokio::test]
    async fn test_should_produce_complete_argv_for_milestone_list_with_default_limit() {
        let runner = MockCommandRunner::success("[]");
        let provider = GitHubMilestoneProvider::with_runner("owner/repo", runner.clone());

        let paged = provider.list(None).await.expect("should list");

        assert!(paged.items.is_empty());
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec!["api", "repos/owner/repo/milestones?per_page=100&page=1"]
        );
    }

    /// 证明分页确实会递增页码,而不仅仅是原语层面的假设。
    ///
    /// 之前所有 argv 测试都用 `MockCommandRunner::success("[]")`,空数组
    /// 在第 1 页就短页,从未真正观察到 `page=2` 出现在 argv 里。这里用
    /// `cap=150` 强制 `per_page` 封顶在 100(`GITHUB_API_MAX_PER_PAGE`),
    /// 第一页给满 100 条(不短页、也不够 N+1 探测所需的 151 条),逼出
    /// 第二页请求;第二页给 51 条(短页)以终止循环。
    #[tokio::test]
    async fn test_should_increment_page_across_calls_for_milestone_list() {
        let full_page: Vec<String> = (0..100)
            .map(|i| {
                format!(
                    r#"{{"number":{i},"title":"v{i}","state":"open","closed_issues":0,"open_issues":0}}"#
                )
            })
            .collect();
        let full_page_json = format!("[{}]", full_page.join(","));

        let short_page: Vec<String> = (100..151)
            .map(|i| {
                format!(
                    r#"{{"number":{i},"title":"v{i}","state":"open","closed_issues":0,"open_issues":0}}"#
                )
            })
            .collect();
        let short_page_json = format!("[{}]", short_page.join(","));

        let runner = SequencedMockCommandRunner::from_results(&[
            (true, &full_page_json),
            (true, &short_page_json),
        ]);
        let provider = GitHubMilestoneProvider::with_runner("owner/repo", runner.clone());

        let paged = provider
            .list(Some(150))
            .await
            .expect("should list across two pages");

        assert_eq!(paged.items.len(), 150);
        assert!(
            paged.truncated,
            "100 + 51 = 151 条超出 cap=150,N+1 探测必须报告截断"
        );

        let calls = runner.recorded_calls();
        assert_eq!(calls.len(), 2, "必须恰好翻两页");
        assert_eq!(calls[0].0, "gh");
        assert_eq!(calls[1].0, "gh");
        assert!(
            calls[0].1[1].contains("page=1"),
            "第一次调用必须请求 page=1,实际: {:?}",
            calls[0].1
        );
        assert!(
            calls[1].1[1].contains("page=2"),
            "第二次调用必须请求 page=2,实际: {:?}",
            calls[1].1
        );
    }

    // --- GitHubMilestoneProvider tests ---

    #[test]
    fn test_should_construct_github_milestone_provider() {
        let provider = GitHubMilestoneProvider::new("octocat/hello-world");
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_debug_format_milestone_provider() {
        let provider = GitHubMilestoneProvider::new("owner/repo");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitHubMilestoneProvider"));
        assert!(debug.contains("owner/repo"));
    }

    #[test]
    fn test_should_clone_github_milestone_provider() {
        let original = GitHubMilestoneProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    // --- LabelData deserialization tests ---

    #[test]
    fn test_should_deserialize_label_data_from_gh_output() {
        let json = br#"[
            {"name": "bug", "color": "d73a4a", "description": "Something isn't working"},
            {"name": "enhancement", "color": "a2eeef", "description": null}
        ]"#;

        let labels: Vec<LabelData> = serde_json::from_slice(json).expect("valid LabelData list");
        assert_eq!(labels.len(), 2);
        assert_eq!(labels[0].name, "bug");
        assert_eq!(labels[0].color.as_deref(), Some("d73a4a"));
        assert_eq!(labels[1].description, None);
    }

    #[test]
    fn test_should_deserialize_single_label_from_gh_output() {
        let json = br#"{"name": "wip", "color": "ffff00", "description": "Work in progress"}"#;

        let label: LabelData = serde_json::from_slice(json).expect("valid LabelData");
        assert_eq!(label.name, "wip");
        assert_eq!(label.color.as_deref(), Some("ffff00"));
        assert_eq!(label.description.as_deref(), Some("Work in progress"));
    }

    #[test]
    fn test_should_deserialize_empty_label_list() {
        let json = b"[]";
        let labels: Vec<LabelData> =
            serde_json::from_slice(json).expect("valid empty LabelData list");
        assert!(labels.is_empty());
    }

    // --- MilestoneData deserialization tests ---

    #[test]
    fn test_should_deserialize_milestone_api_response() {
        let json = br#"{
            "number": 1,
            "title": "v1.0 Release",
            "description": "First stable release",
            "state": "open",
            "due_on": "2026-06-01T00:00:00Z",
            "closed_issues": 10,
            "open_issues": 5
        }"#;

        let api: MilestoneApiResponse =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse");
        let data: MilestoneData = api.into();

        assert_eq!(data.number, 1);
        assert_eq!(data.title, "v1.0 Release");
        assert_eq!(data.description, Some("First stable release".into()));
        assert_eq!(data.state, State::Open);
        assert!(data.due_on.is_some());
        assert_eq!(data.closed_issues, 10);
        assert_eq!(data.open_issues, 5);
    }

    #[test]
    fn test_should_deserialize_closed_milestone() {
        let json = br#"{
            "number": 2,
            "title": "v0.9 Beta",
            "description": null,
            "state": "closed",
            "due_on": null,
            "closed_issues": 20,
            "open_issues": 0
        }"#;

        let api: MilestoneApiResponse =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse");
        let data: MilestoneData = api.into();

        assert_eq!(data.state, State::Closed);
        assert!(data.description.is_none());
        assert!(data.due_on.is_none());
    }

    #[test]
    fn test_should_deserialize_milestone_list() {
        let json = br#"[
            {"number": 1, "title": "v1.0", "description": null, "state": "open", "due_on": null, "closed_issues": 0, "open_issues": 3},
            {"number": 2, "title": "v0.9", "description": "Beta", "state": "closed", "due_on": "2026-01-01T00:00:00Z", "closed_issues": 15, "open_issues": 0}
        ]"#;

        let milestones: Vec<MilestoneApiResponse> =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse list");
        assert_eq!(milestones.len(), 2);
        assert_eq!(milestones[0].title, "v1.0");
        assert_eq!(milestones[1].title, "v0.9");
    }

    #[test]
    fn test_should_convert_milestone_api_to_data() {
        let api = MilestoneApiResponse {
            number: 42,
            title: "Test Milestone".into(),
            description: Some("A test".into()),
            state: "open".into(),
            due_on: Some("2026-12-01T00:00:00Z".into()),
            closed_issues: 5,
            open_issues: 10,
        };

        let data: MilestoneData = api.clone().into();
        assert_eq!(data.number, api.number);
        assert_eq!(data.title, api.title);
    }
}