gitflow-cli 2.1.0

跨平台 Git 工程化工作流编排框架:统一封装 GitHub / GitLab / GitCode 三大平台,配合 AI Agent Skills,覆盖从需求到发布的完整工程循环。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
//! `gf pr` 子命令实现。
//!
//! 提供 Pull Request 的创建、列表、查看、关闭、重新打开、评论、
//! 合并、检出、标记就绪/草稿、同步等功能。
//! Phase 1 仅支持 JSON 输出。

use clap::Subcommand;
use gitflow_core::{
    CliOutput,
    pr::{CreatePrArgs, ListPrArgs, PrProvider},
    types::{MergeStrategy, State},
};
use gitflow_gitcode::GitCodePrProvider;
use gitflow_github::GitHubPrProvider;
use gitflow_gitlab::GitLabMrProvider;
use is_terminal::IsTerminal;

use crate::{
    OutputFormat,
    commands::{list_args::validate_limit, output::print_list_output},
};

/// PR 子命令集合。
///
/// 支持 `create`、`list`、`view`、`close`、`reopen`、`comment`、
/// `merge`、`checkout`、`ready`、`wip`、`sync`、`diff`、`patch` 操作。
#[derive(Debug, Subcommand)]
pub enum PrCommand {
    /// Compile and run a read-only typed PR query.
    Search(super::query_search::SearchArgs),
    /// 创建一条新的 Pull Request。
    Create {
        /// PR 标题(必填)。
        #[arg(long)]
        title: String,

        /// 来源分支(可选,默认为当前 git 分支)。
        #[arg(long)]
        head: Option<String>,

        /// 目标分支(可选,默认探测仓库配置的默认分支,探测失败时回退 `main`)。
        #[arg(long)]
        base: Option<String>,

        /// PR 正文(可选,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

        /// 从文件读取 PR 正文(可选)。
        #[arg(long = "body-file")]
        body_file: Option<String>,

        /// 是否以草稿方式创建。
        #[arg(long)]
        draft: bool,

        /// 目标仓库(`owner/name` 格式,可选,默认为当前仓库)。
        #[arg(long)]
        repo: Option<String>,

        /// 合并 PR 时自动关闭的 Issue 编号(可多次指定)。
        #[arg(long = "closes", alias = "fixes")]
        closes: Vec<u64>,

        /// 挂载的 milestone(编号或标题,可选)。
        #[arg(long)]
        milestone: Option<String>,
    },

    /// 列出 Pull Request。
    List {
        /// 按状态过滤(`open`、`closed` 或 `all`)。
        #[arg(long)]
        state: Option<String>,

        /// 返回数量上限。
        #[arg(long)]
        limit: Option<u32>,
    },

    /// 查看单个 Pull Request 详情。
    View {
        /// PR 编号。
        number: u64,
    },

    /// Read-only, optional semantic PR review precheck.
    Precheck {
        /// Reviewed PR JSON with bounded file patches, not the raw platform envelope.
        #[arg(long)]
        input: String,
        /// Saved typed decision response for offline replay.
        #[arg(long, conflicts_with = "live")]
        response: Option<String>,
        /// Explicitly call the configured Jev provider.
        #[arg(long)]
        live: bool,
        /// Permit live provider use for a private or unknown-visibility repository.
        #[arg(long, requires = "live")]
        allow_private: bool,
    },

    /// 关闭 Pull Request。
    Close {
        /// PR 编号。
        number: u64,
    },

    /// 重新打开 Pull Request。
    Reopen {
        /// PR 编号。
        number: u64,
    },

    /// 评论 Pull Request。
    Comment {
        /// PR 编号。
        number: u64,

        /// 评论正文(可选,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

        /// 从文件读取评论正文(可选)。
        #[arg(long = "body-file")]
        body_file: Option<String>,
    },

    /// 合并 Pull Request。
    Merge {
        /// PR 编号。
        number: u64,

        /// 合并策略(`merge`、`squash` 或 `rebase`,默认为 `merge`)。
        #[arg(long)]
        strategy: Option<String>,

        /// 排队合并:由平台在必需检查/pipeline 通过后自动合并,调用立即返回。
        /// GitHub 与 GitLab 支持;GitCode 不支持并报错。
        #[arg(long, default_value_t = false)]
        auto: bool,
    },

    /// 在本地检出 Pull Request 的分支。
    Checkout {
        /// PR 编号。
        number: u64,
    },

    /// 将草稿 PR 标记为可审查状态。
    Ready {
        /// PR 编号。
        number: u64,
    },

    /// 将 PR 标记为草稿状态。
    Wip {
        /// PR 编号。
        number: u64,
    },

    /// 同步 PR 的分支(将 base 分支的最新变更合入 head 分支)。
    Sync {
        /// PR 编号。
        number: u64,
    },

    /// 获取 Pull Request 的差异(unified diff 格式)。
    Diff {
        /// PR 编号。
        number: u64,
    },

    /// 获取 Pull Request 的 patch(含邮件头信息)。
    Patch {
        /// PR 编号。
        number: u64,
    },

    /// 清理已合并 PR 的分支和 worktree。
    Cleanup {
        /// PR 编号列表(可多个)。
        #[arg(required = false)]
        numbers: Vec<u64>,

        /// 移除指定的 worktree 路径。
        #[arg(long)]
        worktree: Option<String>,

        /// 删除远程分支(默认:true)。
        #[arg(long, default_value = "true")]
        remote: bool,

        /// 删除本地分支(默认:true)。
        #[arg(long, default_value = "true")]
        local: bool,

        /// 强制删除未合并的分支。
        #[arg(long)]
        force: bool,

        /// 仅显示将执行的操作,不实际删除。
        #[arg(long)]
        dry_run: bool,

        /// 跳过 --merged/--closed 批量清理的确认提示(显式指定 PR 编号时本就不确认)。
        #[arg(long, short = 'y')]
        yes: bool,

        /// 清理所有已合并的 PR。
        #[arg(long, conflicts_with = "numbers")]
        merged: bool,

        /// 清理所有已关闭的 PR。
        #[arg(long, conflicts_with = "numbers")]
        closed: bool,
    },
}

/// 处理 `gf pr` 子命令。
///
/// 根据 `platform` 选择对应的 PR 提供者,然后执行具体命令并输出结果。
/// 支持 `github`、`gitlab`、`gitcode` 三个平台,Phase 1 仅支持 JSON 输出格式。
///
/// # Errors
///
/// 返回错误当:
/// - 平台暂不支持。
/// - 底层 provider 调用失败。
/// - `--body` 与 `--body-file` 同时提供。
/// - `--body-file` 文件读取失败。
/// - `comment` 命令未提供评论正文。
/// - `merge` 的 `--strategy` 值非法。
/// - `--head` 未提供且无法检测到当前 git 分支。
/// - JSON 序列化失败。
#[allow(
    clippy::too_many_lines,
    reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
    command: PrCommand,
    platform: &str,
    repo: &str,
    remote_url: &str,
    output_format: OutputFormat,
) -> miette::Result<()> {
    if let PrCommand::Search(args) = &command {
        return super::query_search::handle(
            gitflow_core::query_filter::Target::Pr,
            args.clone(),
            platform,
            repo,
            remote_url,
        )
        .await;
    }
    if let PrCommand::Precheck {
        input,
        response,
        live,
        allow_private,
    } = &command
    {
        let report =
            super::pr_precheck::handle(input.clone(), response.clone(), *live, *allow_private)
                .await?;
        let output = CliOutput::success(report, "local", "pr precheck");
        return print_output(&output, &output_format);
    }
    let provider: Box<dyn PrProvider> = match platform {
        "github" => Box::new(GitHubPrProvider::new(repo)),
        "gitlab" => {
            if remote_url.is_empty() {
                Box::new(GitLabMrProvider::new(repo))
            } else {
                Box::new(GitLabMrProvider::with_remote_url(repo, remote_url))
            }
        }
        "gitcode" => Box::new(GitCodePrProvider::new(repo)),
        other => {
            return Err(miette::miette!(
                "Platform '{other}' not yet supported for pr commands"
            ));
        }
    };

    match command {
        PrCommand::Search(_) => return Err(miette::miette!("invalid search dispatch")),
        PrCommand::Precheck { .. } => return Err(miette::miette!("invalid precheck dispatch")),
        PrCommand::Create {
            title,
            head,
            base,
            body,
            body_file,
            draft,
            repo: target_repo,
            closes,
            milestone,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let resolved_head = resolve_head(head)?;
            let resolved_base = match base {
                Some(b) => b,
                None => resolve_default_branch(provider.default_branch().await),
            };

            let args = CreatePrArgs {
                title,
                body: resolved_body,
                head: resolved_head,
                base: resolved_base,
                draft,
                repo: target_repo,
                closes_issues: closes,
                milestone,
            };
            let pr = provider
                .create(args)
                .await
                .map_err(|e| miette::miette!("Failed to create pr: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr create");
            print_output(&output, &output_format)?;
        }
        PrCommand::List { state, limit } => {
            let parsed_state = state
                .as_deref()
                .map(|s| match s {
                    "open" => Ok(State::Open),
                    "closed" => Ok(State::Closed),
                    "all" => Ok(State::All),
                    other => Err(crate::errors::UserInputError::new(format!(
                        "Invalid state '{other}'. Expected 'open', 'closed', or 'all'."
                    ))),
                })
                .transpose()?;
            let limit = validate_limit(limit)?;

            let args = ListPrArgs {
                state: parsed_state,
                limit,
            };
            let paged = provider
                .list(args)
                .await
                .map_err(|e| miette::miette!("Failed to list prs: {e}"))?;
            let (items, meta) = paged.into_parts();
            print_list_output(items, meta, platform, "pr list", &output_format)?;
        }
        PrCommand::View { number } => {
            let pr = provider
                .view(number)
                .await
                .map_err(|e| miette::miette!("Failed to view pr #{number}: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr view");
            print_output(&output, &output_format)?;
        }
        PrCommand::Close { number } => {
            let pr = provider
                .close(number)
                .await
                .map_err(|e| miette::miette!("Failed to close pr #{number}: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr close");
            print_output(&output, &output_format)?;
        }
        PrCommand::Reopen { number } => {
            let pr = provider
                .reopen(number)
                .await
                .map_err(|e| miette::miette!("Failed to reopen pr #{number}: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr reopen");
            print_output(&output, &output_format)?;
        }
        PrCommand::Comment {
            number,
            body,
            body_file,
        } => {
            let resolved_body = resolve_comment_body(body, body_file)?;
            let comment = provider
                .comment(number, &resolved_body)
                .await
                .map_err(|e| miette::miette!("Failed to comment on pr #{number}: {e}"))?;
            let output = CliOutput::success(comment, platform, "pr comment");
            print_output(&output, &output_format)?;
        }
        PrCommand::Merge {
            number,
            strategy,
            auto,
        } => {
            let parsed_strategy = match strategy.as_deref() {
                Some("merge") => Some(MergeStrategy::Merge),
                Some("squash") => Some(MergeStrategy::Squash),
                Some("rebase") => Some(MergeStrategy::Rebase),
                None => None,
                Some(other) => {
                    return Err(miette::miette!(
                        "Invalid merge strategy '{other}'. Expected 'merge', 'squash', or \
                         'rebase'."
                    ));
                }
            };
            let result = provider
                .merge(number, parsed_strategy, auto)
                .await
                .map_err(|e| miette::miette!("Failed to merge pr #{number}: {e}"))?;
            let output = CliOutput::success(result, platform, "pr merge");
            print_output(&output, &output_format)?;
        }
        PrCommand::Checkout { number } => {
            provider
                .checkout(number)
                .await
                .map_err(|e| miette::miette!("Failed to checkout pr #{number}: {e}"))?;
            let result = serde_json::json!({
                "number": number,
                "checked_out": true,
            });
            let output = CliOutput::success(result, platform, "pr checkout");
            print_output(&output, &output_format)?;
        }
        PrCommand::Ready { number } => {
            let pr = provider
                .mark_ready(number)
                .await
                .map_err(|e| miette::miette!("Failed to mark pr #{number} as ready: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr ready");
            print_output(&output, &output_format)?;
        }
        PrCommand::Wip { number } => {
            let pr = provider
                .mark_wip(number)
                .await
                .map_err(|e| miette::miette!("Failed to mark pr #{number} as draft: {e}"))?;
            let output = CliOutput::success(pr, platform, "pr wip");
            print_output(&output, &output_format)?;
        }
        PrCommand::Sync { number } => {
            provider
                .sync_branch(number)
                .await
                .map_err(|e| miette::miette!("Failed to sync pr #{number} branch: {e}"))?;
            let result = serde_json::json!({
                "number": number,
                "synced": true,
            });
            let output = CliOutput::success(result, platform, "pr sync");
            print_output(&output, &output_format)?;
        }
        PrCommand::Diff { number } => {
            let diff = provider
                .diff(number)
                .await
                .map_err(|e| miette::miette!("Failed to get diff for pr #{number}: {e}"))?;
            let output = CliOutput::success(
                serde_json::json!({ "number": number, "diff": diff }),
                platform,
                "pr diff",
            );
            print_output(&output, &output_format)?;
        }
        PrCommand::Patch { number } => {
            let patch = provider
                .patch(number)
                .await
                .map_err(|e| miette::miette!("Failed to get patch for pr #{number}: {e}"))?;
            let output = CliOutput::success(
                serde_json::json!({ "number": number, "patch": patch }),
                platform,
                "pr patch",
            );
            print_output(&output, &output_format)?;
        }
        PrCommand::Cleanup {
            numbers,
            worktree,
            remote,
            local,
            force,
            dry_run,
            yes,
            merged,
            closed,
        } => {
            let args = gitflow_core::cleanup::CleanupArgs {
                numbers,
                merged,
                closed,
                worktree,
                remote,
                local,
                force,
                dry_run,
                yes,
            };

            if args.merged || args.closed {
                let plan = if args.merged {
                    gitflow_core::cleanup::CleanupService::plan_merged(&*provider)
                        .await
                        .map_err(|e| miette::miette!("Failed to plan merged PR cleanup: {e}"))?
                } else {
                    gitflow_core::cleanup::CleanupService::plan_closed(&*provider)
                        .await
                        .map_err(|e| miette::miette!("Failed to plan closed PR cleanup: {e}"))?
                };

                if plan.truncated {
                    eprintln!(
                        "警告:仓库中还有更多符合条件的 PR 未被纳入本次计划(已达到分页上限)。"
                    );
                }

                if !args.yes
                    && !args.dry_run
                    && !confirm_cleanup(plan.targets.len(), plan.truncated)?
                {
                    eprintln!("已取消,未删除任何内容。");
                    return Ok(());
                }

                let truncated = plan.truncated;
                let limit = plan.limit;
                let results =
                    gitflow_core::cleanup::CleanupService::execute_plan(&*provider, &args, &plan)
                        .await
                        .map_err(|e| miette::miette!("Failed to execute PR cleanup plan: {e}"))?;

                // `truncated`/`limit` below describe the underlying closed-PR
                // listing that produced `plan`, NOT `results`/`data`: `data` is
                // already filtered down from that listing (e.g. to the merged
                // subset for `--merged`), so its length can differ from
                // `limit` even when `truncated` is `false`. Do not read this
                // pagination block as a claim about `data.len()`.
                let meta = cleanup_pagination_meta(truncated, limit, results.len());
                let output =
                    gitflow_core::CliOutput::success_paged(results, meta, platform, "pr cleanup");
                print_output(&output, &output_format)?;
            } else {
                let results = gitflow_core::cleanup::CleanupService::cleanup(&*provider, &args)
                    .await
                    .map_err(|e| miette::miette!("Failed to cleanup PRs: {e}"))?;

                let output = CliOutput::success(results, platform, "pr cleanup");
                print_output(&output, &output_format)?;
            }
        }
    }

    Ok(())
}

/// 为批量清理(`--merged`/`--closed`)的 JSON 输出构造 [`gitflow_core::PaginationMeta`]。
///
/// `truncated` 与 `limit` 描述的是产生 [`gitflow_core::cleanup::CleanupPlan`] 的那次
/// 底层已关闭 PR 列表查询,**不是** `data`(即 `returned`):`data` 已经从该列表里
/// 按 `--merged`/`--closed` 过滤出一个子集,其长度可以小于 `limit`,即便
/// `truncated` 为 `false`。调用方不得把这个分页块读成对 `data.len()` 的断言。
#[must_use]
pub fn cleanup_pagination_meta(
    truncated: bool,
    limit: u32,
    returned: usize,
) -> gitflow_core::PaginationMeta {
    gitflow_core::PaginationMeta {
        truncated,
        returned,
        limit,
    }
}

/// 构造批量清理(`--merged`/`--closed`)的确认提示文案。
///
/// `count` 为计划清理的 PR 数量;`truncated` 为真时说明底层列表已触顶分页上限,
/// 仓库中还有更多符合条件的 PR 未被纳入本次计划。
#[must_use]
pub fn cleanup_confirmation_prompt(count: usize, truncated: bool) -> String {
    let mut prompt = format!("即将清理 {count} 个 PR 的远程分支、本地分支与 worktree,是否继续?");
    if truncated {
        prompt.push_str(" 注意:仓库中还有更多符合条件的 PR 未被纳入本次计划(已达到分页上限)。");
    }
    prompt
}

/// 在删除任何东西之前,为批量清理(`--merged`/`--closed`)请求用户确认。
///
/// 要求 stdin 与 stderr **都**是 TTY:提示写到 stderr,答案从 stdin 读取,
/// 只检查其中一个会被 `yes | gf pr cleanup --merged` 这类管道绕过。
/// 任一端不是 TTY 时直接返回错误,不挂起等待输入,也不默认放行。
///
/// # Errors
///
/// - stdin 或 stderr 不是 TTY 时返回错误,提示改用 `--yes`。
/// - 读取 stdin 失败时返回错误。
fn confirm_cleanup(count: usize, truncated: bool) -> miette::Result<bool> {
    if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
        return Err(miette::miette!(
            "Refusing to prompt for confirmation in a non-interactive session; re-run with --yes \
             to skip confirmation."
        ));
    }

    let prompt = cleanup_confirmation_prompt(count, truncated);
    eprint!("{prompt} [y/N] ");
    let _ = std::io::Write::flush(&mut std::io::stderr());

    let stdin = std::io::stdin();
    let mut reader = stdin.lock();
    confirm_cleanup_with_reader(&mut reader)
}

/// Testable core of [`confirm_cleanup`] — reads one line from any `BufRead`
/// source and decides yes/no. Contains no TTY logic, so it can be exercised
/// directly by tests without a real terminal.
///
/// Empty input (bare Enter) and EOF both resolve to `false`: this is a
/// `[y/N]` prompt guarding an irreversible bulk deletion, so the default must
/// stay "no".
///
/// # Errors
///
/// Returns an error if reading from `reader` fails.
fn confirm_cleanup_with_reader(reader: &mut impl std::io::BufRead) -> miette::Result<bool> {
    let mut line = String::new();
    reader
        .read_line(&mut line)
        .map_err(|e| miette::miette!("Failed to read confirmation: {e}"))?;
    Ok(cleanup_confirm_answer(&line))
}

/// Parse one line of user input into a yes/no answer for the cleanup prompt.
///
/// Accepts `y`/`yes` (case-insensitive, surrounding whitespace ignored) as
/// `true`; everything else — including an empty line — is `false`.
#[must_use]
fn cleanup_confirm_answer(line: &str) -> bool {
    matches!(line.trim().to_lowercase().as_str(), "y" | "yes")
}

/// 解析 `--body` 与 `--body-file` 参数。
///
/// 当提供 `--body-file` 时从文件读取内容。
///
/// # Errors
///
/// - 当同时提供 `--body` 与 `--body-file` 时返回错误。
/// - 当文件读取失败时返回错误。
#[allow(
    clippy::disallowed_methods,
    reason = "Sync file read; called from async handler but file body input is small and local"
)]
fn resolve_body(body: Option<String>, body_file: Option<String>) -> miette::Result<Option<String>> {
    if body.is_some() && body_file.is_some() {
        return Err(miette::miette!(
            "Cannot specify both --body and --body-file"
        ));
    }
    if let Some(path) = body_file {
        let content = std::fs::read_to_string(&path)
            .map_err(|e| miette::miette!("Failed to read body file '{path}': {e}"))?;
        return Ok(Some(content));
    }
    Ok(body)
}

/// 解析评论正文,要求必须提供 `--body` 或 `--body-file` 之一。
///
/// # Errors
///
/// - 当两者都未提供时返回错误。
/// - 当同时提供两者时返回错误。
/// - 当文件读取失败时返回错误。
fn resolve_comment_body(body: Option<String>, body_file: Option<String>) -> miette::Result<String> {
    let resolved = resolve_body(body, body_file)?;
    resolved.ok_or_else(|| miette::miette!("Comment body is required. Use --body or --body-file."))
}

/// 解析 `--head` 参数。
///
/// 当未提供时,通过 `git branch --show-current` 检测当前分支。
///
/// # Errors
///
/// - 当 `--head` 未提供且无法通过 git 检测到当前分支时返回错误。
#[allow(
    clippy::disallowed_types,
    reason = "Quick sync `git` call; converting to async adds overhead disproportionate to the \
              work"
)]
fn resolve_head(head: Option<String>) -> miette::Result<String> {
    if let Some(branch) = head {
        return Ok(branch);
    }

    let output = std::process::Command::new("git")
        .args(["branch", "--show-current"])
        .output()
        .map_err(|e| miette::miette!("Failed to detect current git branch: {e}"))?;

    if !output.status.success() {
        return Err(miette::miette!(
            "Could not detect current branch. Use --head to specify explicitly."
        ));
    }

    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if branch.is_empty() {
        return Err(miette::miette!(
            "Current git HEAD is detached. Use --head to specify the source branch explicitly."
        ));
    }

    Ok(branch)
}

/// 将 provider 查询到的默认分支结果落地为最终使用的 base 分支名。
///
/// 查询失败(含平台不支持,如 GitCode)时回退 `"main"`,不中断 `pr create` 流程。
fn resolve_default_branch(detected: gitflow_core::Result<String>) -> String {
    detected.unwrap_or_else(|e| {
        tracing::debug!(error = %e, "default_branch query failed, falling back to \"main\"");
        "main".to_string()
    })
}

/// 根据输出格式打印结果。
///
/// Phase 1 仅支持 JSON(pretty-printed)。Text 格式暂未实现,返回错误。
///
/// # Errors
///
/// 返回错误当:
/// - JSON 序列化失败。
/// - 输出格式为 `Text`(Phase 1 不支持)。
fn print_output<T: serde::Serialize>(value: &T, format: &OutputFormat) -> miette::Result<()> {
    crate::commands::output::print_output(value, format)
}

#[cfg(test)]
#[allow(
    clippy::panic,
    reason = "Test code: panic is acceptable for assertion failures"
)]
mod tests {
    use clap::Parser;

    use super::*;

    #[test]
    fn test_should_resolve_body_with_body_only() {
        let result = resolve_body(Some("hello".into()), None);
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), Some("hello".into()));
    }

    #[test]
    fn test_should_resolve_body_with_none() {
        let result = resolve_body(None, None);
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), None);
    }

    #[test]
    fn test_should_resolve_body_from_file() {
        let file = tempfile::NamedTempFile::new().expect("create temp file");
        std::fs::write(file.path(), "pr body from file").expect("write temp file");
        let result = resolve_body(None, Some(file.path().to_string_lossy().into_owned()));
        assert!(result.is_ok());
        assert_eq!(
            result.expect("already checked"),
            Some("pr body from file".into())
        );
    }

    #[test]
    fn test_should_error_on_missing_body_file() {
        let result = resolve_body(None, Some("/nonexistent/path/body.md".into()));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to read body file"));
    }

    #[test]
    fn test_should_reject_both_body_and_body_file() {
        let result = resolve_body(Some("hello".into()), Some("/tmp/body.md".into()));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Cannot specify both"));
    }

    #[test]
    fn test_should_require_comment_body() {
        let result = resolve_comment_body(None, None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Comment body is required"));
    }

    #[test]
    fn test_should_resolve_comment_body_with_body() {
        let result = resolve_comment_body(Some("LGTM".into()), None);
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), "LGTM");
    }

    #[test]
    fn test_should_resolve_head_with_explicit_value() {
        let result = resolve_head(Some("feature/my-branch".into()));
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), "feature/my-branch");
    }

    #[test]
    fn test_should_use_detected_branch_on_success() {
        let result = resolve_default_branch(Ok("dev".to_string()));
        assert_eq!(result, "dev");
    }

    #[test]
    fn test_should_fallback_to_main_on_detection_failure() {
        let result = resolve_default_branch(Err(gitflow_core::CoreError::Platform(
            "unsupported".to_string(),
        )));
        assert_eq!(result, "main");
    }

    #[test]
    fn test_should_print_json_output() {
        let value = serde_json::json!({"number": 1, "title": "test"});
        let result = print_output(&value, &OutputFormat::Json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_accept_text_output() {
        let value = serde_json::json!({"number": 1});
        let result = print_output(&value, &OutputFormat::Text);
        assert!(result.is_ok());
    }

    // --- PrCommand 解析测试 ---

    #[test]
    fn test_should_parse_read_only_pr_precheck() {
        let cli = crate::Cli::try_parse_from([
            "gf",
            "pr",
            "precheck",
            "--input",
            "/tmp/pr.json",
            "--live",
            "--allow-private",
        ])
        .expect("parse");
        assert!(matches!(
            cli.command,
            crate::Commands::Pr(PrCommand::Precheck {
                live: true,
                allow_private: true,
                ..
            })
        ));
    }

    #[test]
    fn test_should_parse_pr_close() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "close", "42"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Close { number }) => {
                assert_eq!(number, 42);
            }
            _ => panic!("Expected PrCommand::Close"),
        }
    }

    #[test]
    fn test_should_parse_pr_reopen() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "reopen", "7"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Reopen { number }) => {
                assert_eq!(number, 7);
            }
            _ => panic!("Expected PrCommand::Reopen"),
        }
    }

    #[test]
    fn test_should_parse_pr_comment_with_body() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "comment", "10", "--body", "LGTM"])
            .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Comment {
                number,
                body,
                body_file,
            }) => {
                assert_eq!(number, 10);
                assert_eq!(body, Some("LGTM".into()));
                assert!(body_file.is_none());
            }
            _ => panic!("Expected PrCommand::Comment"),
        }
    }

    #[test]
    fn test_should_parse_pr_merge_with_strategy() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "pr", "merge", "5", "--strategy", "squash"])
                .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Merge {
                number,
                strategy,
                auto,
            }) => {
                assert_eq!(number, 5);
                assert_eq!(strategy, Some("squash".into()));
                assert!(!auto, "auto must default to false");
            }
            _ => panic!("Expected PrCommand::Merge"),
        }
    }

    #[test]
    fn test_should_parse_pr_merge_without_strategy() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "merge", "3"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Merge {
                number,
                strategy,
                auto,
            }) => {
                assert_eq!(number, 3);
                assert!(strategy.is_none());
                assert!(!auto, "auto must default to false");
            }
            _ => panic!("Expected PrCommand::Merge"),
        }
    }

    #[test]
    fn test_should_parse_pr_merge_with_auto() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "pr", "merge", "7", "--auto"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Merge { auto, number, .. }) => {
                assert_eq!(number, 7);
                assert!(auto, "--auto must set auto to true");
            }
            _ => panic!("Expected PrCommand::Merge"),
        }
    }

    #[test]
    fn test_should_parse_pr_checkout() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "checkout", "15"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Checkout { number }) => {
                assert_eq!(number, 15);
            }
            _ => panic!("Expected PrCommand::Checkout"),
        }
    }

    #[test]
    fn test_should_parse_pr_ready() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "ready", "8"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Ready { number }) => {
                assert_eq!(number, 8);
            }
            _ => panic!("Expected PrCommand::Ready"),
        }
    }

    #[test]
    fn test_should_parse_pr_wip() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "wip", "12"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Wip { number }) => {
                assert_eq!(number, 12);
            }
            _ => panic!("Expected PrCommand::Wip"),
        }
    }

    #[test]
    fn test_should_parse_pr_sync() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "sync", "20"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Sync { number }) => {
                assert_eq!(number, 20);
            }
            _ => panic!("Expected PrCommand::Sync"),
        }
    }

    #[test]
    fn test_should_parse_pr_diff() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "diff", "42"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Diff { number }) => {
                assert_eq!(number, 42);
            }
            _ => panic!("Expected PrCommand::Diff"),
        }
    }

    #[test]
    fn test_should_parse_pr_patch() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "patch", "17"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Patch { number }) => {
                assert_eq!(number, 17);
            }
            _ => panic!("Expected PrCommand::Patch"),
        }
    }

    #[test]
    fn test_should_parse_pr_view() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "view", "42"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::View { number }) => {
                assert_eq!(number, 42);
            }
            _ => panic!("Expected PrCommand::View"),
        }
    }

    #[test]
    fn test_should_parse_pr_list_with_state() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow", "pr", "list", "--state", "open", "--limit", "20",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::List { state, limit }) => {
                assert_eq!(state, Some("open".into()));
                assert_eq!(limit, Some(20));
            }
            _ => panic!("Expected PrCommand::List"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_with_repo_and_head() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "pr",
            "create",
            "--title",
            "Feature PR",
            "--head",
            "feature/my-branch",
            "--base",
            "develop",
            "--repo",
            "org/repo",
            "--draft",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create {
                title,
                head,
                base,
                repo,
                draft,
                ..
            }) => {
                assert_eq!(title, "Feature PR");
                assert_eq!(head, Some("feature/my-branch".into()));
                assert_eq!(base, Some("develop".into()));
                assert_eq!(repo, Some("org/repo".into()));
                assert!(draft);
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_minimal() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Minimal PR"])
            .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create {
                title,
                head,
                base,
                draft,
                repo,
                ..
            }) => {
                assert_eq!(title, "Minimal PR");
                assert!(head.is_none());
                assert!(base.is_none());
                assert!(!draft);
                assert!(repo.is_none());
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_with_milestone() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "pr",
            "create",
            "--title",
            "Feature PR",
            "--milestone",
            "v1.0",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { milestone, .. }) => {
                assert_eq!(milestone, Some("v1.0".to_string()));
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_without_milestone() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Feature PR"])
            .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { milestone, .. }) => {
                assert!(milestone.is_none());
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_list_without_args() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "list"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::List { state, limit }) => {
                assert!(state.is_none());
                assert!(limit.is_none());
            }
            _ => panic!("Expected PrCommand::List"),
        }
    }

    #[test]
    fn test_should_accept_state_all_for_pr_list() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gf", "pr", "list", "--state", "all"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_should_print_toon_output() {
        let value = serde_json::json!({"number": 1, "title": "test"});
        let result = print_output(&value, &OutputFormat::Toon);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_print_auto_output() {
        let value = serde_json::json!({"number": 1, "title": "test"});
        let result = print_output(&value, &OutputFormat::Auto);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_parse_pr_cleanup_single() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "172"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Cleanup { numbers, .. }) => {
                assert_eq!(numbers, vec![172]);
            }
            _ => panic!("Expected PrCommand::Cleanup"),
        }
    }

    #[test]
    fn test_should_parse_pr_cleanup_multiple() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "172", "173", "174"])
            .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Cleanup { numbers, .. }) => {
                assert_eq!(numbers, vec![172, 173, 174]);
            }
            _ => panic!("Expected PrCommand::Cleanup"),
        }
    }

    #[test]
    fn test_should_parse_pr_cleanup_with_worktree() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "pr",
            "cleanup",
            "172",
            "--worktree",
            ".claude/worktrees/feat-172",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Cleanup {
                numbers, worktree, ..
            }) => {
                assert_eq!(numbers, vec![172]);
                assert_eq!(worktree, Some(".claude/worktrees/feat-172".to_string()));
            }
            _ => panic!("Expected PrCommand::Cleanup"),
        }
    }

    #[test]
    fn test_should_parse_pr_cleanup_merged() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "--merged"]).expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Cleanup { merged, .. }) => {
                assert!(merged);
            }
            _ => panic!("Expected PrCommand::Cleanup"),
        }
    }

    // --- closes/issues argument parsing tests ---

    #[test]
    fn test_should_parse_pr_create_with_single_closes() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow", "pr", "create", "--title", "Feature", "--closes", "24",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
                assert_eq!(closes, vec![24]);
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_with_multiple_closes() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow", "pr", "create", "--title", "Feature", "--closes", "24", "--closes", "23",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
                assert_eq!(closes, vec![24, 23]);
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_with_fixes_alias() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow", "pr", "create", "--title", "Feature", "--fixes", "42",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
                assert_eq!(closes, vec![42]);
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_pr_create_without_closes() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Feature"])
            .expect("parse");
        match cli.command {
            crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
                assert!(closes.is_empty());
            }
            _ => panic!("Expected PrCommand::Create"),
        }
    }

    #[test]
    fn test_should_mention_count_in_cleanup_confirmation_prompt() {
        let prompt = cleanup_confirmation_prompt(7, false);
        assert!(prompt.contains('7'));
    }

    #[test]
    fn test_should_warn_about_more_prs_when_plan_truncated() {
        let truncated_prompt = cleanup_confirmation_prompt(1000, true);
        assert!(truncated_prompt.contains("更多"));

        let complete_prompt = cleanup_confirmation_prompt(3, false);
        assert!(!complete_prompt.contains("更多"));
    }

    #[test]
    fn test_should_surface_truncated_flag_in_cleanup_pagination_meta() {
        // Mirrors the shape of `pr cleanup`'s underlying closed-PR listing
        // hitting the cap: the plan says truncated, but `data` (returned) is
        // whatever survived the merged/closed filter — smaller than `limit`.
        let meta = cleanup_pagination_meta(true, 1000, 3);
        assert!(meta.truncated);
        assert_eq!(meta.limit, 1000);
        assert_eq!(meta.returned, 3);
    }

    #[test]
    fn test_should_not_report_truncated_when_plan_was_not_truncated() {
        let meta = cleanup_pagination_meta(false, 1000, 3);
        assert!(!meta.truncated);
    }

    #[test]
    fn test_should_emit_pagination_truncated_in_cleanup_json_output_when_plan_truncated() {
        // Reproduces F-3: `gf pr cleanup --output json` must carry an in-band
        // truncation signal, not just the stderr warning.
        let meta = cleanup_pagination_meta(true, 1000, 3);
        let results: Vec<gitflow_core::cleanup::CleanupResult> = Vec::new();
        let output = gitflow_core::CliOutput::success_paged(results, meta, "github", "pr cleanup");
        let json = serde_json::to_value(&output).expect("serialize cleanup output");
        assert_eq!(json["pagination"]["truncated"], serde_json::json!(true));
        assert_eq!(json["success"], serde_json::json!(true));
    }

    #[test]
    fn test_should_accept_lowercase_y_as_yes() {
        assert!(cleanup_confirm_answer("y\n"));
    }

    #[test]
    fn test_should_accept_uppercase_y_as_yes() {
        assert!(cleanup_confirm_answer("Y\n"));
    }

    #[test]
    fn test_should_accept_lowercase_yes_as_yes() {
        assert!(cleanup_confirm_answer("yes\n"));
    }

    #[test]
    fn test_should_accept_uppercase_yes_as_yes() {
        assert!(cleanup_confirm_answer("YES\n"));
    }

    #[test]
    fn test_should_accept_y_with_surrounding_whitespace_as_yes() {
        assert!(cleanup_confirm_answer(" y \n"));
    }

    #[test]
    fn test_should_treat_n_as_no() {
        assert!(!cleanup_confirm_answer("n\n"));
    }

    #[test]
    fn test_should_treat_empty_line_as_no() {
        // Bare Enter at the prompt: `read_line` returns "\n".
        assert!(!cleanup_confirm_answer("\n"));
    }

    #[test]
    fn test_should_treat_eof_as_no() {
        // `read_line` on EOF (no more input) leaves the buffer empty.
        assert!(!cleanup_confirm_answer(""));
    }

    #[test]
    fn test_should_treat_eof_as_no_through_reader() {
        let mut reader: &[u8] = b"";
        let answer = confirm_cleanup_with_reader(&mut reader).expect("EOF read should not error");
        assert!(!answer);
    }

    #[test]
    fn test_should_accept_yes_through_reader() {
        let mut reader: &[u8] = b"yes\n";
        let answer = confirm_cleanup_with_reader(&mut reader).expect("read should not error");
        assert!(answer);
    }
}