Skip to main content

gitflow_github/
error.rs

1//! GitHub CLI 错误解析。
2
3use gitflow_core::{PlatformCliError, platform::Platform};
4
5/// 解析 `gh` CLI 的 stderr 输出为统一的 [`PlatformCliError`]。
6///
7/// 优先尝试 JSON 格式解析(`gh` 在 API 错误时输出 JSON),
8/// 回退到纯文本模式(取前三行作为内部详情)。
9/// 用户可见消息为中文。
10#[must_use]
11pub fn parse_gh_error(stderr: &[u8]) -> PlatformCliError {
12    let text = String::from_utf8_lossy(stderr);
13
14    // 尝试解析 gh 的 JSON 错误格式
15    if let Ok(json) = serde_json::from_slice::<serde_json::Value>(stderr)
16        && let Some(msg) = json.get("message").and_then(serde_json::Value::as_str)
17    {
18        let code = json
19            .get("code")
20            .and_then(serde_json::Value::as_str)
21            .map(String::from);
22
23        let user_message: String = match code.as_deref() {
24            Some("NOT_FOUND") => "资源不存在".into(),
25            Some("FORBIDDEN") => "权限不足".into(),
26            _ => format!("GitHub 操作失败:{msg}"),
27        };
28
29        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
30        err.hint = Some("运行 `gh auth status` 检查认证状态".into());
31        err.doc_link = Some("https://cli.github.com/manual/".into());
32        err.code = code;
33        return err;
34    }
35
36    // 回退:纯文本解析
37    let user_message: String = if text.contains("Not logged in") || text.contains("auth") {
38        "未登录 GitHub".into()
39    } else {
40        "GitHub CLI 执行失败".into()
41    };
42
43    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
44    err.hint = Some("运行 `gh auth login` 完成登录".into());
45    err.doc_link = Some("https://cli.github.com/manual/".into());
46    err
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn test_should_parse_gh_json_error_to_platform_cli_error() {
55        let json = br#"{"message": "GraphQL: Could not resolve to a user with the login 'nobody'.", "code": "NOT_FOUND"}"#;
56        let err = parse_gh_error(json);
57        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
58        assert_eq!(err.platform, Platform::GitHub);
59        assert!(!err.user_message.is_empty());
60        assert!(!err.raw_stderr.is_empty());
61    }
62
63    #[test]
64    fn test_should_parse_gh_plain_text_error() {
65        let stderr = b"gh: Not logged in. Please run `gh auth login` to authenticate.";
66        let err = parse_gh_error(stderr);
67        assert!(err.user_message.contains("认证") || err.user_message.contains("登录"));
68        assert!(err.hint.is_some());
69        assert_eq!(err.platform, Platform::GitHub);
70        assert!(err.raw_stderr.contains("Not logged in"));
71    }
72
73    #[test]
74    fn test_should_not_leak_raw_stderr_in_display() {
75        let stderr = b"internal gh debug trace line";
76        let err = parse_gh_error(stderr);
77        let display = err.to_string();
78        assert!(!display.contains("internal gh debug trace"));
79    }
80
81    #[test]
82    fn test_should_handle_empty_stderr() {
83        let err = parse_gh_error(b"");
84        assert!(!err.user_message.is_empty());
85        assert!(err.hint.is_some());
86    }
87}