gitflow-cli 1.3.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
//! `gf issue` 子命令实现。
//!
//! 提供 Issue 的创建、列表、查看、关闭、重新打开、评论、标签管理等功能,
//! 支持通过 clap 解析参数后调用对应平台的 [`IssueProvider`] 实现。
//! Phase 1 仅支持 JSON 输出。

use clap::Subcommand;
use gitflow_core::{
    CliOutput,
    issue::{CreateIssueArgs, IssueProvider, ListIssueArgs},
    types::State,
};
use gitflow_gitcode::GitCodeIssueProvider;
use gitflow_github::GitHubIssueProvider;
use gitflow_gitlab::GitLabIssueProvider;

use crate::OutputFormat;

/// Issue 子命令集合。
///
/// 支持 `create`、`list`、`view`、`close`、`reopen`、`comment`、`comments`、
/// `add-label`、`remove-label` 操作,每种操作对应不同的 clap 参数。
#[derive(Debug, Subcommand)]
pub enum IssueCommand {
    /// 创建一个新的 Issue。
    Create {
        /// Issue 标题(必填)。
        #[arg(long)]
        title: String,

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

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

        /// 标签列表(可多次指定)。
        #[arg(long = "label")]
        label: Vec<String>,

        /// 指派人列表(可多次指定)。
        #[arg(long = "assignee")]
        assignee: Vec<String>,

        /// 目标仓库(可选,格式:owner/repo,覆盖从 remote 自动检测的值)。
        #[arg(long)]
        repo: Option<String>,
    },

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

        /// 搜索关键词。
        #[arg(long)]
        search: Option<String>,

        /// 按标签过滤(可多次指定)。
        #[arg(long = "label")]
        label: Vec<String>,

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

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

    /// 关闭 Issue。
    Close {
        /// Issue 编号。
        number: u64,
    },

    /// 重新打开 Issue。
    Reopen {
        /// Issue 编号。
        number: u64,
    },

    /// 评论 Issue。
    Comment {
        /// Issue 编号。
        number: u64,

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

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

    /// 列出 Issue 的所有评论。
    Comments {
        /// Issue 编号。
        number: u64,
    },

    /// 为 Issue 添加标签。
    AddLabel {
        /// Issue 编号。
        number: u64,

        /// 要添加的标签(至少一个)。
        #[arg(long = "label", num_args = 1.., required = true)]
        label: Vec<String>,
    },

    /// 从 Issue 移除标签。
    RemoveLabel {
        /// Issue 编号。
        number: u64,

        /// 要移除的标签名称。
        #[arg(long)]
        label: String,
    },
}

/// 处理 `gf issue` 子命令。
///
/// 根据 `platform` 选择对应的 Issue 提供者,然后执行具体命令并输出结果。
/// 支持 `github`、`gitlab`、`gitcode` 三个平台,Phase 1 仅支持 JSON 输出格式。
///
/// # Errors
///
/// 返回错误当:
/// - 平台暂不支持。
/// - 底层 provider 调用失败。
/// - `--body` 与 `--body-file` 同时提供。
/// - `--body-file` 文件读取失败。
/// - `comment` 命令未提供评论正文。
/// - JSON 序列化失败。
#[allow(
    clippy::too_many_lines,
    reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
    command: IssueCommand,
    platform: &str,
    repo: &str,
    output_format: OutputFormat,
) -> miette::Result<()> {
    // Allow `--repo` on Create to override the auto-detected repo.
    let effective_repo = match &command {
        IssueCommand::Create {
            repo: Some(override_repo),
            ..
        } => override_repo.as_str(),
        _ => repo,
    };

    let provider: Box<dyn IssueProvider> = match platform {
        "github" => Box::new(GitHubIssueProvider::new(effective_repo)),
        "gitlab" => Box::new(GitLabIssueProvider::new(effective_repo)),
        "gitcode" => Box::new(GitCodeIssueProvider::new(effective_repo)),
        other => {
            return Err(miette::miette!(
                "Platform '{other}' not yet supported for issue commands"
            ));
        }
    };

    match command {
        IssueCommand::Create {
            title,
            body,
            body_file,
            label,
            assignee,
            repo: _,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let args = CreateIssueArgs {
                title,
                body: resolved_body,
                labels: label,
                assignees: assignee,
            };
            let issue = provider
                .create(args)
                .await
                .map_err(|e| miette::miette!("Failed to create issue: {e}"))?;
            let output = CliOutput::success(issue, platform, "issue create");
            print_output(&output, &output_format)?;
        }
        IssueCommand::List {
            state,
            search,
            label,
            limit,
        } => {
            let parsed_state = state
                .as_deref()
                .map(|s| match s {
                    "open" => Ok(State::Open),
                    "closed" => Ok(State::Closed),
                    other => Err(miette::miette!(
                        "Invalid state '{other}'. Expected 'open' or 'closed'."
                    )),
                })
                .transpose()?;

            let args = ListIssueArgs {
                state: parsed_state,
                labels: label,
                assignee: None,
                search,
                limit,
            };
            let issues = provider
                .list(args)
                .await
                .map_err(|e| miette::miette!("Failed to list issues: {e}"))?;
            let output = CliOutput::success(issues, platform, "issue list");
            print_output(&output, &output_format)?;
        }
        IssueCommand::View { number } => {
            let issue = provider
                .view(number)
                .await
                .map_err(|e| miette::miette!("Failed to view issue #{number}: {e}"))?;
            let output = CliOutput::success(issue, platform, "issue view");
            print_output(&output, &output_format)?;
        }
        IssueCommand::Close { number } => {
            let issue = provider
                .close(number)
                .await
                .map_err(|e| miette::miette!("Failed to close issue #{number}: {e}"))?;
            let output = CliOutput::success(issue, platform, "issue close");
            print_output(&output, &output_format)?;
        }
        IssueCommand::Reopen { number } => {
            let issue = provider
                .reopen(number)
                .await
                .map_err(|e| miette::miette!("Failed to reopen issue #{number}: {e}"))?;
            let output = CliOutput::success(issue, platform, "issue reopen");
            print_output(&output, &output_format)?;
        }
        IssueCommand::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 issue #{number}: {e}"))?;
            let output = CliOutput::success(comment, platform, "issue comment");
            print_output(&output, &output_format)?;
        }
        IssueCommand::Comments { number } => {
            let comments = provider
                .list_comments(number)
                .await
                .map_err(|e| miette::miette!("Failed to list comments for issue #{number}: {e}"))?;
            let output = CliOutput::success(comments, platform, "issue comments");
            print_output(&output, &output_format)?;
        }
        IssueCommand::AddLabel { number, label } => {
            provider
                .add_labels(number, &label)
                .await
                .map_err(|e| miette::miette!("Failed to add labels to issue #{number}: {e}"))?;
            let result = serde_json::json!({
                "number": number,
                "labels_added": label,
            });
            let output = CliOutput::success(result, platform, "issue add-label");
            print_output(&output, &output_format)?;
        }
        IssueCommand::RemoveLabel { number, label } => {
            provider
                .remove_label(number, &label)
                .await
                .map_err(|e| miette::miette!("Failed to remove label from issue #{number}: {e}"))?;
            let result = serde_json::json!({
                "number": number,
                "label_removed": label,
            });
            let output = CliOutput::success(result, platform, "issue remove-label");
            print_output(&output, &output_format)?;
        }
    }

    Ok(())
}

/// 解析 `--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."))
}

/// 根据输出格式打印结果。
///
/// 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 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 dir = std::env::temp_dir();
        let path = dir.join("gitflow_test_body.md");
        std::fs::write(&path, "file content here").expect("write temp file");
        let result = resolve_body(None, Some(path.to_string_lossy().into_owned()));
        let _ = std::fs::remove_file(&path);
        assert!(result.is_ok());
        assert_eq!(
            result.expect("already checked"),
            Some("file content here".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("a comment".into()), None);
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), "a comment");
    }

    #[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());
    }

    // --- IssueCommand 解析测试 ---

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

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

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

    #[test]
    fn test_should_parse_issue_add_label() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "issue",
            "add-label",
            "5",
            "--label",
            "bug",
            "urgent",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::AddLabel { number, label }) => {
                assert_eq!(number, 5);
                assert_eq!(label, vec!["bug".to_string(), "urgent".to_string()]);
            }
            _ => panic!("Expected IssueCommand::AddLabel"),
        }
    }

    #[test]
    fn test_should_parse_issue_remove_label() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "issue",
            "remove-label",
            "3",
            "--label",
            "wontfix",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::RemoveLabel { number, label }) => {
                assert_eq!(number, 3);
                assert_eq!(label, "wontfix");
            }
            _ => panic!("Expected IssueCommand::RemoveLabel"),
        }
    }

    #[test]
    fn test_should_parse_issue_create_with_repo() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "issue",
            "create",
            "--title",
            "Bug report",
            "--repo",
            "owner/repo",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::Create { title, repo, .. }) => {
                assert_eq!(title, "Bug report");
                assert_eq!(repo, Some("owner/repo".to_string()));
            }
            _ => panic!("Expected IssueCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_issue_create_without_repo() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "issue", "create", "--title", "Bug report"])
                .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::Create { repo, .. }) => {
                assert!(repo.is_none());
            }
            _ => panic!("Expected IssueCommand::Create"),
        }
    }

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

    #[test]
    fn test_should_parse_issue_comments() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "issue", "comments", "10"]).expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::Comments { number }) => {
                assert_eq!(number, 10);
            }
            _ => panic!("Expected IssueCommand::Comments"),
        }
    }

    #[test]
    fn test_should_parse_issue_list_with_state() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow", "issue", "list", "--state", "open", "--label", "bug", "--search", "crash",
            "--limit", "10",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::List {
                state,
                search,
                label,
                limit,
            }) => {
                assert_eq!(state, Some("open".into()));
                assert_eq!(search, Some("crash".into()));
                assert_eq!(label, vec!["bug".to_string()]);
                assert_eq!(limit, Some(10));
            }
            _ => panic!("Expected IssueCommand::List"),
        }
    }

    #[test]
    fn test_should_parse_issue_create_full() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "issue",
            "create",
            "--title",
            "Full issue",
            "--body",
            "Description",
            "--label",
            "bug",
            "--label",
            "urgent",
            "--assignee",
            "user1",
            "--assignee",
            "user2",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Issue(IssueCommand::Create {
                title,
                body,
                label,
                assignee,
                ..
            }) => {
                assert_eq!(title, "Full issue");
                assert_eq!(body, Some("Description".into()));
                assert_eq!(label, vec!["bug".to_string(), "urgent".to_string()]);
                assert_eq!(assignee, vec!["user1".to_string(), "user2".to_string()]);
            }
            _ => panic!("Expected IssueCommand::Create"),
        }
    }

    #[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());
    }
}