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
//! `gf commit` 子命令实现。
//!
//! 提供 Commit 的查看、Diff/Patch 获取、评论等功能,
//! 支持通过 clap 解析参数后调用对应平台的 [`CommitProvider`] 实现。
//! Phase 1 仅支持 JSON 输出。

use clap::Subcommand;
use gitflow_core::{CliOutput, commit::CommitProvider};
use gitflow_gitcode::GitCodeCommitProvider;
use gitflow_github::GitHubCommitProvider;
use gitflow_gitlab::GitLabCommitProvider;

use crate::OutputFormat;

/// Commit 查看和操作子命令集合。
///
/// 支持 `view`、`diff`、`patch`、`comment` 操作。
#[derive(Debug, Subcommand)]
pub enum CommitCommand {
    /// 查看 Commit 详情。
    View {
        /// Commit SHA 哈希值。
        sha: String,
    },

    /// 获取 Commit 的 unified diff 输出。
    Diff {
        /// Commit SHA 哈希值。
        sha: String,
    },

    /// 获取 Commit 的原始 patch 内容。
    Patch {
        /// Commit SHA 哈希值。
        sha: String,
    },

    /// 评论 Commit 中的特定文件行。
    Comment {
        /// Commit SHA 哈希值。
        sha: String,

        /// 评论内容(必填,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

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

        /// 文件路径(相对于仓库根目录,必填)。
        #[arg(long)]
        path: Option<String>,

        /// 评论的行号(1-based,必填)。
        #[arg(long)]
        line: Option<u64>,
    },
}

/// 处理 `gf commit` 子命令。
///
/// 根据 `platform` 选择对应的 Commit 提供者,然后执行具体命令并输出结果。
/// 支持 `github`、`gitlab`、`gitcode` 三个平台,Phase 1 仅支持 JSON 输出格式。
///
/// # Errors
///
/// 返回错误当:
/// - 平台暂不支持。
/// - 底层 provider 调用失败。
/// - `comment` 命令未提供评论内容或必需的 `--path`/`--line`。
/// - `--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: CommitCommand,
    platform: &str,
    repo: &str,
    output_format: OutputFormat,
) -> miette::Result<()> {
    let provider: Box<dyn CommitProvider> = match platform {
        "github" => Box::new(GitHubCommitProvider::new(repo)),
        "gitlab" => Box::new(GitLabCommitProvider::new(repo)),
        "gitcode" => Box::new(GitCodeCommitProvider::new(repo)),
        other => {
            return Err(miette::miette!(
                "Platform '{other}' not yet supported for commit commands"
            ));
        }
    };

    match command {
        CommitCommand::View { sha } => {
            let detail = provider
                .view(&sha)
                .await
                .map_err(|e| miette::miette!("Failed to view commit {sha}: {e}"))?;
            let output = CliOutput::success(detail, platform, "commit view");
            print_output(&output, &output_format)?;
        }
        CommitCommand::Diff { sha } => {
            let diff = provider
                .diff(&sha)
                .await
                .map_err(|e| miette::miette!("Failed to get diff for commit {sha}: {e}"))?;
            let output = CliOutput::success(
                serde_json::json!({ "sha": sha, "diff": diff }),
                platform,
                "commit diff",
            );
            print_output(&output, &output_format)?;
        }
        CommitCommand::Patch { sha } => {
            let patch = provider
                .patch(&sha)
                .await
                .map_err(|e| miette::miette!("Failed to get patch for commit {sha}: {e}"))?;
            let output = CliOutput::success(
                serde_json::json!({ "sha": sha, "patch": patch }),
                platform,
                "commit patch",
            );
            print_output(&output, &output_format)?;
        }
        CommitCommand::Comment {
            sha,
            body,
            body_file,
            path,
            line,
        } => {
            let resolved_body = resolve_comment_body(body, body_file)?;
            let path = path.ok_or_else(|| {
                miette::miette!("--path is required for commit comment. Specify the file path.")
            })?;
            let line = line.ok_or_else(|| {
                miette::miette!("--line is required for commit comment. Specify the line number.")
            })?;

            provider
                .comment(&sha, &resolved_body, &path, line)
                .await
                .map_err(|e| {
                    miette::miette!("Failed to comment on commit {sha} at {path}:{line}: {e}")
                })?;

            let result = serde_json::json!({
                "sha": sha,
                "path": path,
                "line": line,
                "commented": true,
            });
            let output = CliOutput::success(result, platform, "commit comment");
            print_output(&output, &output_format)?;
        }
    }

    Ok(())
}

/// 解析评论正文,要求必须提供 `--body` 或 `--body-file` 之一。
///
/// # Errors
///
/// - 当两者都未提供时返回错误。
/// - 当同时提供两者时返回错误。
/// - 当文件读取失败时返回错误。
#[allow(
    clippy::disallowed_methods,
    reason = "Sync file read; called from async handler but file body input is small and local"
)]
fn resolve_comment_body(body: Option<String>, body_file: Option<String>) -> miette::Result<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(content);
    }
    body.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::*;

    // --- resolve_comment_body 测试 ---

    #[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_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_reject_both_body_and_body_file() {
        let result = resolve_comment_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_resolve_comment_body_from_file() {
        let file = tempfile::NamedTempFile::new().expect("create temp file");
        std::fs::write(file.path(), "commit comment from file").expect("write temp file");
        let result = resolve_comment_body(None, Some(file.path().to_string_lossy().into_owned()));
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), "commit comment from file");
    }

    #[test]
    fn test_should_error_on_missing_body_file() {
        let result = resolve_comment_body(None, Some("/nonexistent/path/comment.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_comment_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_comment_body(None, Some("/tmp/x\0y".into()));
        assert!(result.is_err());
    }

    // --- print_output 测试 ---

    #[test]
    fn test_should_print_json_output() {
        let value = serde_json::json!({"sha": "abc123", "message": "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());
    }

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

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

    // --- CommitCommand 解析测试 ---

    #[test]
    fn test_should_parse_commit_view() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "commit", "view", "abc123def"]).expect("parse");
        match cli.command {
            crate::Commands::Commit(CommitCommand::View { sha }) => {
                assert_eq!(sha, "abc123def");
            }
            _ => panic!("Expected CommitCommand::View"),
        }
    }

    #[test]
    fn test_should_parse_commit_diff() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "commit", "diff", "deadbeef"]).expect("parse");
        match cli.command {
            crate::Commands::Commit(CommitCommand::Diff { sha }) => {
                assert_eq!(sha, "deadbeef");
            }
            _ => panic!("Expected CommitCommand::Diff"),
        }
    }

    #[test]
    fn test_should_parse_commit_patch() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "commit", "patch", "f00ba42"]).expect("parse");
        match cli.command {
            crate::Commands::Commit(CommitCommand::Patch { sha }) => {
                assert_eq!(sha, "f00ba42");
            }
            _ => panic!("Expected CommitCommand::Patch"),
        }
    }

    #[test]
    fn test_should_parse_commit_comment() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "commit",
            "comment",
            "abc123",
            "--body",
            "This looks suspicious",
            "--path",
            "src/auth.rs",
            "--line",
            "42",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Commit(CommitCommand::Comment {
                sha,
                body,
                body_file,
                path,
                line,
            }) => {
                assert_eq!(sha, "abc123");
                assert_eq!(body, Some("This looks suspicious".into()));
                assert!(body_file.is_none());
                assert_eq!(path, Some("src/auth.rs".into()));
                assert_eq!(line, Some(42));
            }
            _ => panic!("Expected CommitCommand::Comment"),
        }
    }

    #[test]
    fn test_should_parse_commit_comment_with_body_file() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "commit",
            "comment",
            "abc123",
            "--body-file",
            "/tmp/comment.md",
            "--path",
            "lib.rs",
            "--line",
            "10",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Commit(CommitCommand::Comment {
                sha,
                body,
                body_file,
                path,
                line,
            }) => {
                assert_eq!(sha, "abc123");
                assert!(body.is_none());
                assert_eq!(body_file, Some("/tmp/comment.md".into()));
                assert_eq!(path, Some("lib.rs".into()));
                assert_eq!(line, Some(10));
            }
            _ => panic!("Expected CommitCommand::Comment"),
        }
    }
}