gitflow-cli 1.1.0

跨平台 Git 工程化工作流编排框架 CLI:统一封装 GitHub / GitLab / GitCode,配合 AI Agent Skills 覆盖需求到发布的完整工程循环。Cross-platform Git engineering workflow CLI.
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
//! `gf review` 子命令实现。
//!
//! 提供 PR Review 的评论、批准、要求修改、提交审查等功能,
//! 支持通过 clap 解析参数后调用对应平台的 [`ReviewProvider`] 实现。
//! Phase 1 仅支持 JSON 输出。

use clap::Subcommand;
use gitflow_core::{
    CliOutput,
    review::{ReviewProvider, ReviewState},
};
use gitflow_gitcode::GitCodeReviewProvider;
use gitflow_github::GitHubReviewProvider;
use gitflow_gitlab::GitLabReviewProvider;

use crate::OutputFormat;

/// Review 子命令集合。
///
/// 支持 `comment`、`approve`、`request-changes`、`submit` 操作,
/// 每种操作对应不同的 clap 参数。
#[derive(Debug, Subcommand)]
pub enum ReviewCommand {
    /// 在 PR 上发表评论。
    Comment {
        /// PR 编号。
        pr_number: u64,

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

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

    /// 批准 PR。
    Approve {
        /// PR 编号。
        pr_number: u64,

        /// 批准说明(可选,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

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

    /// 要求对 PR 进行修改。
    RequestChanges {
        /// PR 编号。
        pr_number: u64,

        /// 修改要求说明(可选,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

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

    /// 提交一次完整的 Review。
    Submit {
        /// PR 编号。
        pr_number: u64,

        /// Review 总结说明(可选,与 `--body-file` 二选一)。
        #[arg(long)]
        body: Option<String>,

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

        /// Review 结论(`approved`、`changes_requested`、`commented`)。
        #[arg(long)]
        event: ReviewEventArg,
    },
}

/// Review 事件结论参数。
///
/// 用作 `clap::ValueEnum`,映射到 [`ReviewState`]。
#[derive(Debug, Clone, clap::ValueEnum)]
pub(crate) enum ReviewEventArg {
    /// 审查通过,可以合并。
    #[value(name = "approved")]
    Approved,
    /// 要求修改后才能合并。
    #[value(name = "changes_requested")]
    ChangesRequested,
    /// 仅发表评论,不表态。
    #[value(name = "commented")]
    Commented,
}

impl From<ReviewEventArg> for ReviewState {
    fn from(arg: ReviewEventArg) -> Self {
        match arg {
            ReviewEventArg::Approved => ReviewState::Approved,
            ReviewEventArg::ChangesRequested => ReviewState::ChangesRequested,
            ReviewEventArg::Commented => ReviewState::Commented,
        }
    }
}

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

    match command {
        ReviewCommand::Comment {
            pr_number,
            body,
            body_file,
        } => {
            let resolved_body = resolve_comment_body(body, body_file)?;
            let review = provider
                .comment(pr_number, &resolved_body)
                .await
                .map_err(|e| miette::miette!("Failed to comment on PR #{pr_number}: {e}"))?;
            let output = CliOutput::success(review, platform, "review comment");
            print_output(&output, &output_format)?;
        }
        ReviewCommand::Approve {
            pr_number,
            body,
            body_file,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let review = provider
                .approve(pr_number, resolved_body.as_deref())
                .await
                .map_err(|e| miette::miette!("Failed to approve PR #{pr_number}: {e}"))?;
            let output = CliOutput::success(review, platform, "review approve");
            print_output(&output, &output_format)?;
        }
        ReviewCommand::RequestChanges {
            pr_number,
            body,
            body_file,
        } => {
            let resolved_body = resolve_comment_body(body, body_file)?;
            let review = provider
                .request_changes(pr_number, &resolved_body)
                .await
                .map_err(|e| {
                    miette::miette!("Failed to request changes on PR #{pr_number}: {e}")
                })?;
            let output = CliOutput::success(review, platform, "review request-changes");
            print_output(&output, &output_format)?;
        }
        ReviewCommand::Submit {
            pr_number,
            body,
            body_file,
            event,
        } => {
            let resolved_body = resolve_body(body, body_file)?;
            let state: ReviewState = event.into();
            let review = provider
                .submit_review(pr_number, state, resolved_body.as_deref())
                .await
                .map_err(|e| miette::miette!("Failed to submit review for PR #{pr_number}: {e}"))?;
            let output = CliOutput::success(review, platform, "review submit");
            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!("Review 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("looks good".into()), None);
        assert!(result.is_ok());
        assert_eq!(result.expect("already checked"), Some("looks good".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_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("Review body is required"));
    }

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

    #[test]
    fn test_should_print_json_output() {
        let value = serde_json::json!({"id": 1, "state": "approved"});
        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!({"id": 1, "state": "approved"});
        let result = print_output(&value, &OutputFormat::Toon);
        assert!(result.is_ok());
    }

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

    // --- ReviewCommand 解析测试 ---

    #[test]
    fn test_should_parse_review_comment() {
        use clap::Parser;
        let cli =
            crate::Cli::try_parse_from(["gitflow", "review", "comment", "42", "--body", "LGTM"])
                .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::Comment {
                pr_number,
                body,
                body_file,
            }) => {
                assert_eq!(pr_number, 42);
                assert_eq!(body, Some("LGTM".into()));
                assert!(body_file.is_none());
            }
            _ => panic!("Expected ReviewCommand::Comment"),
        }
    }

    #[test]
    fn test_should_parse_review_approve() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "review",
            "approve",
            "10",
            "--body",
            "Looks good to me",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::Approve {
                pr_number,
                body,
                body_file,
            }) => {
                assert_eq!(pr_number, 10);
                assert_eq!(body, Some("Looks good to me".into()));
                assert!(body_file.is_none());
            }
            _ => panic!("Expected ReviewCommand::Approve"),
        }
    }

    #[test]
    fn test_should_parse_review_request_changes() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "review",
            "request-changes",
            "5",
            "--body",
            "Please fix the error handling",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::RequestChanges {
                pr_number,
                body,
                body_file,
            }) => {
                assert_eq!(pr_number, 5);
                assert_eq!(body, Some("Please fix the error handling".into()));
                assert!(body_file.is_none());
            }
            _ => panic!("Expected ReviewCommand::RequestChanges"),
        }
    }

    #[test]
    fn test_should_parse_review_submit() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "review",
            "submit",
            "7",
            "--body",
            "Overall good",
            "--event",
            "approved",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::Submit {
                pr_number,
                body,
                body_file,
                event,
            }) => {
                assert_eq!(pr_number, 7);
                assert_eq!(body, Some("Overall good".into()));
                assert!(body_file.is_none());
                assert!(matches!(event, ReviewEventArg::Approved));
            }
            _ => panic!("Expected ReviewCommand::Submit"),
        }
    }

    #[test]
    fn test_should_parse_review_submit_changes_requested() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "review",
            "submit",
            "3",
            "--event",
            "changes_requested",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::Submit {
                pr_number, event, ..
            }) => {
                assert_eq!(pr_number, 3);
                assert!(matches!(event, ReviewEventArg::ChangesRequested));
            }
            _ => panic!("Expected ReviewCommand::Submit"),
        }
    }

    #[test]
    fn test_should_parse_review_submit_commented() {
        use clap::Parser;
        let cli = crate::Cli::try_parse_from([
            "gitflow",
            "review",
            "submit",
            "15",
            "--event",
            "commented",
        ])
        .expect("parse");
        match cli.command {
            crate::Commands::Review(ReviewCommand::Submit { event, .. }) => {
                assert!(matches!(event, ReviewEventArg::Commented));
            }
            _ => panic!("Expected ReviewCommand::Submit"),
        }
    }

    #[test]
    fn test_should_convert_review_event_arg() {
        assert!(matches!(
            ReviewState::from(ReviewEventArg::Approved),
            ReviewState::Approved
        ));
        assert!(matches!(
            ReviewState::from(ReviewEventArg::ChangesRequested),
            ReviewState::ChangesRequested
        ));
        assert!(matches!(
            ReviewState::from(ReviewEventArg::Commented),
            ReviewState::Commented
        ));
    }
}