gitflow-cli 2.0.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
//! `gf release` 子命令实现。
//!
//! 提供 Release 的创建、列表、查看、编辑、上传/下载资源、删除等功能,
//! 支持通过 clap 解析参数后调用对应平台的 [`ReleaseProvider`] 实现。
//! Phase 1 仅支持 JSON 输出。

use clap::Subcommand;
use gitflow_core::{
    CliOutput,
    release::{CreateReleaseArgs, ReleaseProvider},
};
use gitflow_gitcode::GitCodeReleaseProvider;
use gitflow_github::GitHubReleaseProvider;
use gitflow_gitlab::GitLabReleaseProvider;

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

/// Release 子命令集合。
///
/// 支持 `create`、`list`、`view`、`edit`、`upload`、
/// `download`、`delete` 操作,每种操作对应不同的 clap 参数。
#[derive(Debug, Subcommand)]
pub enum ReleaseCommand {
    /// 创建一个新的 Release。
    Create {
        /// Git tag 名称(必填)。
        #[arg(long)]
        tag_name: String,

        /// Release 标题(可选)。
        #[arg(long)]
        name: Option<String>,

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

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

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

        /// 以预发布方式创建。
        #[arg(long, default_value_t = false)]
        prerelease: bool,

        /// 目标 commitish(可选,默认为当前分支 HEAD)。
        #[arg(long)]
        target_commitish: Option<String>,
    },

    /// 列出 Release。
    List {
        /// 返回数量上限(可选)。
        #[arg(long)]
        limit: Option<u32>,
    },

    /// 查看指定 tag 的 Release 详情。
    View {
        /// Git tag 名称。
        tag: String,
    },

    /// 编辑指定 Release 的元数据。
    Edit {
        /// Git tag 名称。
        tag: String,

        /// Release 标题(可选)。
        #[arg(long)]
        name: Option<String>,

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

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

    /// 上传资源文件到 Release。
    Upload {
        /// Git tag 名称。
        tag: String,

        /// 本地文件路径。
        #[arg(long)]
        file: String,
    },

    /// 下载 Release 的资源文件。
    Download {
        /// Git tag 名称。
        tag: String,

        /// 文件名匹配模式(可选)。
        #[arg(long)]
        pattern: Option<String>,

        /// 下载目录(可选)。
        #[arg(long)]
        dir: Option<String>,
    },

    /// 删除指定 Release。
    Delete {
        /// Git tag 名称。
        tag: String,

        /// 跳过确认提示。
        #[arg(long, short, default_value_t = false)]
        yes: bool,
    },
}

/// 处理 `gf release` 子命令。
///
/// 根据 `platform` 选择对应的 Release 提供者,然后执行具体命令并输出结果。
/// 支持 `github`、`gitlab`、`gitcode` 三个平台,Phase 1 仅支持 JSON 输出格式。
///
/// # Errors
///
/// 返回错误当:
/// - 平台暂不支持。
/// - 底层 provider 调用失败。
/// - `--body` 与 `--body-file` 同时提供。
/// - `--body-file` 文件读取失败。
/// - JSON 序列化失败。
#[allow(
    clippy::too_many_lines,
    reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
    command: ReleaseCommand,
    platform: &str,
    repo: &str,
    remote_url: &str,
    output_format: OutputFormat,
) -> miette::Result<()> {
    let provider: Box<dyn ReleaseProvider> = match platform {
        "github" => Box::new(GitHubReleaseProvider::new(repo)),
        "gitlab" => {
            if remote_url.is_empty() {
                Box::new(GitLabReleaseProvider::new(repo))
            } else {
                Box::new(GitLabReleaseProvider::with_remote_url(repo, remote_url))
            }
        }
        "gitcode" => Box::new(GitCodeReleaseProvider::new(repo)),
        other => {
            return Err(miette::miette!(
                "Platform '{other}' not yet supported for release commands"
            ));
        }
    };

    match command {
        ReleaseCommand::Create {
            tag_name,
            name,
            body,
            body_file,
            draft,
            prerelease,
            target_commitish,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let args = CreateReleaseArgs {
                tag_name,
                name,
                body: resolved_body,
                draft,
                prerelease,
                target_commitish,
            };
            let release = provider
                .create(args)
                .await
                .map_err(|e| miette::miette!("Failed to create release: {e}"))?;
            let output = CliOutput::success(release, platform, "release create");
            print_output(&output, &output_format)?;
        }
        ReleaseCommand::List { limit } => {
            let limit = validate_limit(limit)?;
            let paged = provider
                .list(limit)
                .await
                .map_err(|e| miette::miette!("Failed to list releases: {e}"))?;
            let (items, meta) = paged.into_parts();
            print_list_output(items, meta, platform, "release list", &output_format)?;
        }
        ReleaseCommand::View { tag } => {
            let release = provider
                .view(&tag)
                .await
                .map_err(|e| miette::miette!("Failed to view release '{tag}': {e}"))?;
            let output = CliOutput::success(release, platform, "release view");
            print_output(&output, &output_format)?;
        }
        ReleaseCommand::Edit {
            tag,
            name,
            body,
            body_file,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let args = CreateReleaseArgs {
                tag_name: tag.clone(),
                name,
                body: resolved_body,
                draft: false,
                prerelease: false,
                target_commitish: None,
            };
            let release = provider
                .edit(&tag, args)
                .await
                .map_err(|e| miette::miette!("Failed to edit release '{tag}': {e}"))?;
            let output = CliOutput::success(release, platform, "release edit");
            print_output(&output, &output_format)?;
        }
        ReleaseCommand::Upload { tag, file } => {
            let file = validate_asset_file(&file)?;
            let asset_name = std::path::Path::new(&file)
                .file_name()
                .map_or_else(|| file.clone(), |n| n.to_string_lossy().to_string());
            provider
                .upload_asset(&tag, &file, &asset_name)
                .await
                .map_err(|e| miette::miette!("Failed to upload asset to release '{tag}': {e}"))?;
            let result = serde_json::json!({
                "tag_name": tag,
                "asset_file": asset_name,
            });
            let output = CliOutput::success(result, platform, "release upload");
            print_output(&output, &output_format)?;
        }
        ReleaseCommand::Download { tag, pattern, dir } => {
            let asset_name = pattern.unwrap_or_else(|| "*".into());
            let dest = validate_download_dir(&dir.unwrap_or_else(|| ".".into()))?;
            provider
                .download_asset(&tag, &asset_name, &dest)
                .await
                .map_err(|e| {
                    miette::miette!("Failed to download asset from release '{tag}': {e}")
                })?;
            let result = serde_json::json!({
                "tag_name": tag,
                "pattern": asset_name,
                "dest": dest,
            });
            let output = CliOutput::success(result, platform, "release download");
            print_output(&output, &output_format)?;
        }
        ReleaseCommand::Delete { tag, .. } => {
            provider
                .delete(&tag)
                .await
                .map_err(|e| miette::miette!("Failed to delete release '{tag}': {e}"))?;
            let result = serde_json::json!({
                "tag_name": tag,
                "deleted": true,
            });
            let output = CliOutput::success(result, platform, "release delete");
            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 safe = gitflow_core::SafePath::new_allow_absolute(&path)
            .map_err(|e| miette::miette!("无效的 --body-file 参数: {e}"))?;
        let content = std::fs::read_to_string(safe.as_path())
            .map_err(|e| miette::miette!("Failed to read body file '{path}': {e}"))?;
        return Ok(Some(content));
    }
    Ok(body)
}

/// 校验 `--file`(上传资源的本地文件路径),允许绝对路径。
///
/// # Errors
///
/// 当路径包含 `..`、NUL 字节或其他 [`SafePath`] 拒绝的输入时返回错误。
///
/// [`SafePath`]: gitflow_core::SafePath
fn validate_asset_file(file: &str) -> miette::Result<String> {
    let safe = gitflow_core::SafePath::new_allow_absolute(file)
        .map_err(|e| miette::miette!("无效的 --file 参数: {e}"))?;
    Ok(safe.as_path().to_string_lossy().into_owned())
}

/// 校验 `--dir`(下载资源的目标目录),允许绝对路径。
///
/// # Errors
///
/// 当路径包含 `..`、NUL 字节或其他 [`SafePath`] 拒绝的输入时返回错误。
///
/// [`SafePath`]: gitflow_core::SafePath
fn validate_download_dir(dir: &str) -> miette::Result<String> {
    let safe = gitflow_core::SafePath::new_allow_absolute(dir)
        .map_err(|e| miette::miette!("无效的 --dir 参数: {e}"))?;
    Ok(safe.as_path().to_string_lossy().into_owned())
}

/// 根据输出格式打印结果。
///
/// 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("release notes".into()), None);
        assert!(result.is_ok());
        assert_eq!(
            result.expect("already checked"),
            Some("release notes".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(), "release body content").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("release body content".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_body_file_with_parent_dir_traversal() {
        let result = resolve_body(None, Some("/tmp/../etc/passwd".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_body_file_with_null_byte() {
        let result = resolve_body(None, Some("/tmp/x\0y".into()));
        assert!(result.is_err());
    }

    #[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_validate_asset_file_accepts_absolute() {
        let result = validate_asset_file("/tmp/asset.tar.gz");
        assert_eq!(result.expect("valid path"), "/tmp/asset.tar.gz");
    }

    #[test]
    fn test_should_validate_asset_file_rejects_parent_dir_traversal() {
        let result = validate_asset_file("/tmp/../etc/passwd");
        assert!(result.is_err());
    }

    #[test]
    fn test_should_validate_asset_file_rejects_null_byte() {
        let result = validate_asset_file("/tmp/x\0y");
        assert!(result.is_err());
    }

    #[test]
    fn test_should_validate_download_dir_accepts_absolute() {
        let result = validate_download_dir("/tmp/downloads");
        assert_eq!(result.expect("valid path"), "/tmp/downloads");
    }

    #[test]
    fn test_should_validate_download_dir_rejects_parent_dir_traversal() {
        let result = validate_download_dir("/tmp/../etc");
        assert!(result.is_err());
    }

    #[test]
    fn test_should_validate_download_dir_rejects_null_byte() {
        let result = validate_download_dir("/tmp/x\0y");
        assert!(result.is_err());
    }

    #[test]
    fn test_should_print_json_output() {
        let value = serde_json::json!({"tag_name": "v1.0.0", "name": "v1.0.0"});
        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());
    }

    // --- ReleaseCommand 解析测试 ---

    #[test]
    fn test_should_parse_release_create() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "release",
            "create",
            "--tag-name",
            "v1.0.0",
            "--name",
            "v1.0.0",
            "--body",
            "Initial release",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Create {
                tag_name,
                name,
                body,
                body_file,
                draft,
                prerelease,
                target_commitish,
            }) => {
                assert_eq!(tag_name, "v1.0.0");
                assert_eq!(name, Some("v1.0.0".into()));
                assert_eq!(body, Some("Initial release".into()));
                assert!(body_file.is_none());
                assert!(!draft);
                assert!(!prerelease);
                assert!(target_commitish.is_none());
            }
            _ => panic!("Expected ReleaseCommand::Create"),
        }
    }

    #[test]
    fn test_should_parse_release_list() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "release", "list", "--limit", "10"])
            .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::List { limit }) => {
                assert_eq!(limit, Some(10));
            }
            _ => panic!("Expected ReleaseCommand::List"),
        }
    }

    #[test]
    fn test_should_parse_release_view() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "release", "view", "v1.0.0"]).expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::View { tag }) => {
                assert_eq!(tag, "v1.0.0");
            }
            _ => panic!("Expected ReleaseCommand::View"),
        }
    }

    #[test]
    fn test_should_parse_release_edit() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "release",
            "edit",
            "v1.0.0",
            "--name",
            "v1.0.1",
            "--body",
            "Updated notes",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Edit {
                tag,
                name,
                body,
                body_file,
            }) => {
                assert_eq!(tag, "v1.0.0");
                assert_eq!(name, Some("v1.0.1".into()));
                assert_eq!(body, Some("Updated notes".into()));
                assert!(body_file.is_none());
            }
            _ => panic!("Expected ReleaseCommand::Edit"),
        }
    }

    #[test]
    fn test_should_parse_release_upload() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "release",
            "upload",
            "v1.0.0",
            "--file",
            "./artifact.tar.gz",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Upload { tag, file }) => {
                assert_eq!(tag, "v1.0.0");
                assert_eq!(file, "./artifact.tar.gz");
            }
            _ => panic!("Expected ReleaseCommand::Upload"),
        }
    }

    #[test]
    fn test_should_parse_release_download() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "release",
            "download",
            "v1.0.0",
            "--pattern",
            "*.tar.gz",
            "--dir",
            "./downloads",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Download { tag, pattern, dir }) => {
                assert_eq!(tag, "v1.0.0");
                assert_eq!(pattern, Some("*.tar.gz".into()));
                assert_eq!(dir, Some("./downloads".into()));
            }
            _ => panic!("Expected ReleaseCommand::Download"),
        }
    }

    #[test]
    fn test_should_parse_release_delete() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "release", "delete", "v1.0.0", "--yes"])
            .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Delete { tag, yes }) => {
                assert_eq!(tag, "v1.0.0");
                assert!(yes);
            }
            _ => panic!("Expected ReleaseCommand::Delete"),
        }
    }

    #[test]
    fn test_should_parse_release_create_with_draft_and_prerelease() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "release",
            "create",
            "--tag-name",
            "v2.0.0-beta",
            "--draft",
            "--prerelease",
            "--target-commitish",
            "abc123",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Create {
                tag_name,
                draft,
                prerelease,
                target_commitish,
                ..
            }) => {
                assert_eq!(tag_name, "v2.0.0-beta");
                assert!(draft);
                assert!(prerelease);
                assert_eq!(target_commitish, Some("abc123".into()));
            }
            _ => panic!("Expected ReleaseCommand::Create"),
        }
    }

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

    #[test]
    fn test_should_parse_release_download_without_pattern() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from(["gitflow", "release", "download", "v1.0.0"])
            .expect("parse");
        match cli.command {
            crate::Commands::Release(ReleaseCommand::Download { tag, pattern, dir }) => {
                assert_eq!(tag, "v1.0.0");
                assert!(pattern.is_none());
                assert!(dir.is_none());
            }
            _ => panic!("Expected ReleaseCommand::Download"),
        }
    }

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

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