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            Some("RATE_LIMITED") => "API 请求频率超限".into(),
27            Some("VALIDATION_FAILED") => "请求参数校验失败".into(),
28            Some("CONFLICT") => "存在冲突,请先合并最新变更".into(),
29            Some("GONE") => "资源已被删除或迁移".into(),
30            _ => format!("GitHub 操作失败:{msg}"),
31        };
32
33        let hint = match code.as_deref() {
34            Some("RATE_LIMITED") => Some("等待几分钟后重试".into()),
35            Some("VALIDATION_FAILED") => Some("检查请求参数格式是否正确".into()),
36            Some("CONFLICT") => Some("运行 `git pull --rebase` 解决冲突后重试".into()),
37            Some("GONE") => Some("确认资源是否存在,可能已被删除或重命名".into()),
38            _ => Some("运行 `gh auth status` 检查认证状态".into()),
39        };
40        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
41        err.hint = hint;
42        err.doc_link = Some("https://cli.github.com/manual/".into());
43        err.code = code;
44        return err;
45    }
46
47    // 回退:纯文本解析
48    let user_message: String = if text.contains("Not logged in") || text.contains("auth") {
49        "未登录 GitHub".into()
50    } else {
51        "GitHub CLI 执行失败".into()
52    };
53
54    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
55    err.hint = Some("运行 `gh auth login` 完成登录".into());
56    err.doc_link = Some("https://cli.github.com/manual/".into());
57    err
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_should_parse_gh_json_error_to_platform_cli_error() {
66        let json = br#"{"message": "GraphQL: Could not resolve to a user with the login 'nobody'.", "code": "NOT_FOUND"}"#;
67        let err = parse_gh_error(json);
68        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
69        assert_eq!(err.platform, Platform::GitHub);
70        assert!(!err.user_message.is_empty());
71        assert!(!err.raw_stderr.is_empty());
72    }
73
74    #[test]
75    fn test_should_parse_gh_plain_text_error() {
76        let stderr = b"gh: Not logged in. Please run `gh auth login` to authenticate.";
77        let err = parse_gh_error(stderr);
78        assert!(err.user_message.contains("认证") || err.user_message.contains("登录"));
79        assert!(err.hint.is_some());
80        assert_eq!(err.platform, Platform::GitHub);
81        assert!(err.raw_stderr.contains("Not logged in"));
82    }
83
84    #[test]
85    fn test_should_not_leak_raw_stderr_in_display() {
86        let stderr = b"internal gh debug trace line";
87        let err = parse_gh_error(stderr);
88        let display = err.to_string();
89        assert!(!display.contains("internal gh debug trace"));
90    }
91
92    #[test]
93    fn test_should_handle_empty_stderr() {
94        let err = parse_gh_error(b"");
95        assert!(!err.user_message.is_empty());
96        assert!(err.hint.is_some());
97    }
98
99    #[test]
100    fn test_should_parse_gh_forbidden_error() {
101        let json = br#"{"message": "Resource not accessible by integration", "code": "FORBIDDEN"}"#;
102        let err = parse_gh_error(json);
103        assert_eq!(err.code.as_deref(), Some("FORBIDDEN"));
104        assert_eq!(err.platform, Platform::GitHub);
105        assert!(err.user_message.contains("权限"));
106    }
107
108    #[test]
109    fn test_should_parse_gh_json_error_without_code() {
110        let json = br#"{"message": "Something went wrong"}"#;
111        let err = parse_gh_error(json);
112        assert!(err.code.is_none());
113        assert!(err.user_message.contains("Something went wrong"));
114        assert_eq!(err.platform, Platform::GitHub);
115    }
116
117    #[test]
118    fn test_should_parse_gh_rate_limited_error() {
119        let json = br#"{"message": "API rate limit exceeded", "code": "RATE_LIMITED"}"#;
120        let err = parse_gh_error(json);
121        assert_eq!(err.code.as_deref(), Some("RATE_LIMITED"));
122        assert!(err.user_message.contains("频率"));
123        assert!(
124            err.hint
125                .as_ref()
126                .is_some_and(|h| h.contains("等待") || h.contains("重试"))
127        );
128    }
129
130    #[test]
131    fn test_should_parse_gh_validation_failed_error() {
132        let json = br#"{"message": "Validation failed", "code": "VALIDATION_FAILED"}"#;
133        let err = parse_gh_error(json);
134        assert_eq!(err.code.as_deref(), Some("VALIDATION_FAILED"));
135        assert!(err.hint.is_some());
136    }
137
138    #[test]
139    fn test_should_parse_gh_conflict_error() {
140        let json = br#"{"message": "Merge conflict", "code": "CONFLICT"}"#;
141        let err = parse_gh_error(json);
142        assert_eq!(err.code.as_deref(), Some("CONFLICT"));
143        assert!(err.user_message.contains("冲突"));
144    }
145
146    #[test]
147    fn test_should_parse_gh_gone_error() {
148        let json = br#"{"message": "Resource gone", "code": "GONE"}"#;
149        let err = parse_gh_error(json);
150        assert_eq!(err.code.as_deref(), Some("GONE"));
151        assert!(err.user_message.contains("删除") || err.user_message.contains("迁移"));
152    }
153}