Skip to main content

gitflow_gitcode/
error.rs

1//! GitCode CLI 错误解析。
2
3use gitflow_core::{PlatformCliError, platform::Platform};
4
5/// 解析 `gitcode` CLI 的 stderr 输出为统一的 [`PlatformCliError`]。
6///
7/// 优先尝试 JSON 格式解析(`gitcode` 在 API 错误时输出 JSON),
8/// 回退到纯文本模式。
9/// 用户可见消息为中文。
10#[must_use]
11pub fn parse_gitcode_error(stderr: &[u8]) -> PlatformCliError {
12    let text = String::from_utf8_lossy(stderr);
13
14    // 尝试解析 gitcode 的 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("UNAUTHORIZED" | "FORBIDDEN") => "认证失败或权限不足".into(),
25            Some("NOT_FOUND") => "资源不存在".into(),
26            Some("PR_DISABLED") => "此仓库未启用拉取请求".into(),
27            Some("BRANCH_PROTECTED") => "目标分支受保护,无法直接推送".into(),
28            Some("RATE_LIMITED") => "API 请求频率超限".into(),
29            Some("VALIDATION_FAILED") => "请求参数校验失败".into(),
30            Some("CONFLICT") => "存在冲突,请先合并最新变更".into(),
31            _ => format!("GitCode 操作失败:{msg}"),
32        };
33
34        let hint = match code.as_deref() {
35            Some("PR_DISABLED") => Some("在仓库设置中启用拉取请求功能".into()),
36            Some("BRANCH_PROTECTED") => Some("检查分支保护规则,或使用有权限的分支".into()),
37            Some("RATE_LIMITED") => Some("等待几分钟后重试".into()),
38            Some("VALIDATION_FAILED") => Some("检查请求参数格式是否正确".into()),
39            Some("CONFLICT") => Some("运行 `git pull --rebase` 解决冲突后重试".into()),
40            _ => Some("运行 `gc auth status` 检查认证状态".into()),
41        };
42        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitCode);
43        err.hint = hint;
44        err.doc_link = Some("https://gitcode.com/gitcode-cli/cli/blob/main/README.md".into());
45        err.code = code;
46        return err;
47    }
48
49    // 回退:纯文本解析
50    let user_message: String = if text.contains("auth") || text.contains("login") {
51        "未登录 GitCode".into()
52    } else {
53        "GitCode CLI 执行失败".into()
54    };
55
56    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitCode);
57    err.hint = Some("运行 `gc auth login` 完成登录".into());
58    err.doc_link = Some("https://gitcode.com/gitcode-cli/cli/blob/main/README.md".into());
59    err
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_should_parse_gitcode_json_error() {
68        let json = br#"{"message": "Unauthorized", "code": "UNAUTHORIZED"}"#;
69        let err = parse_gitcode_error(json);
70        assert_eq!(err.code.as_deref(), Some("UNAUTHORIZED"));
71        assert_eq!(err.platform, Platform::GitCode);
72        assert!(err.user_message.contains("认证") || err.user_message.contains("权限"));
73    }
74
75    #[test]
76    fn test_should_parse_gitcode_plain_text_error() {
77        let stderr = b"Error: authentication required";
78        let err = parse_gitcode_error(stderr);
79        assert!(err.hint.is_some());
80        assert_eq!(err.platform, Platform::GitCode);
81    }
82
83    #[test]
84    fn test_should_not_leak_raw_stderr() {
85        let stderr = b"gitcode internal panic trace";
86        let err = parse_gitcode_error(stderr);
87        assert!(!err.to_string().contains("internal panic"));
88    }
89
90    #[test]
91    fn test_should_handle_empty_stderr() {
92        let err = parse_gitcode_error(b"");
93        assert!(!err.user_message.is_empty());
94        assert!(err.hint.is_some());
95    }
96
97    #[test]
98    fn test_should_parse_gitcode_not_found_error() {
99        let json = br#"{"message": "Resource not found", "code": "NOT_FOUND"}"#;
100        let err = parse_gitcode_error(json);
101        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
102        assert!(err.user_message.contains("资源不存在"));
103    }
104
105    #[test]
106    fn test_should_parse_gitcode_forbidden_error() {
107        let json = br#"{"message": "Forbidden", "code": "FORBIDDEN"}"#;
108        let err = parse_gitcode_error(json);
109        assert_eq!(err.code.as_deref(), Some("FORBIDDEN"));
110        assert!(err.user_message.contains("认证") || err.user_message.contains("权限"));
111    }
112
113    #[test]
114    fn test_should_parse_gitcode_plain_text_login_error() {
115        let stderr = b"Error: login required";
116        let err = parse_gitcode_error(stderr);
117        assert!(err.user_message.contains("登录"));
118        assert_eq!(err.platform, Platform::GitCode);
119    }
120
121    #[test]
122    fn test_should_parse_gitcode_json_error_without_code() {
123        let json = br#"{"message": "Internal server error"}"#;
124        let err = parse_gitcode_error(json);
125        assert!(err.code.is_none());
126        assert!(err.user_message.contains("Internal server error"));
127        assert_eq!(err.platform, Platform::GitCode);
128    }
129
130    #[test]
131    fn test_should_parse_gitcode_pr_disabled_error() {
132        let json = br#"{"message": "Pull requests are disabled", "code": "PR_DISABLED"}"#;
133        let err = parse_gitcode_error(json);
134        assert_eq!(err.code.as_deref(), Some("PR_DISABLED"));
135        assert!(err.user_message.contains("拉取请求"));
136        assert!(err.hint.is_some());
137    }
138
139    #[test]
140    fn test_should_parse_gitcode_branch_protected_error() {
141        let json = br#"{"message": "Branch is protected", "code": "BRANCH_PROTECTED"}"#;
142        let err = parse_gitcode_error(json);
143        assert_eq!(err.code.as_deref(), Some("BRANCH_PROTECTED"));
144        assert!(err.hint.is_some());
145    }
146
147    #[test]
148    fn test_should_parse_gitcode_rate_limited_error() {
149        let json = br#"{"message": "API rate limit exceeded", "code": "RATE_LIMITED"}"#;
150        let err = parse_gitcode_error(json);
151        assert_eq!(err.code.as_deref(), Some("RATE_LIMITED"));
152        assert!(
153            err.hint
154                .as_ref()
155                .is_some_and(|h| h.contains("等待") || h.contains("重试"))
156        );
157    }
158
159    #[test]
160    fn test_should_parse_gitcode_validation_error() {
161        let json = br#"{"message": "Validation failed", "code": "VALIDATION_FAILED"}"#;
162        let err = parse_gitcode_error(json);
163        assert_eq!(err.code.as_deref(), Some("VALIDATION_FAILED"));
164        assert!(err.hint.is_some());
165    }
166
167    #[test]
168    fn test_should_parse_gitcode_conflict_error() {
169        let json = br#"{"message": "Merge conflict", "code": "CONFLICT"}"#;
170        let err = parse_gitcode_error(json);
171        assert_eq!(err.code.as_deref(), Some("CONFLICT"));
172        assert!(err.user_message.contains("冲突"));
173        assert!(err.hint.is_some());
174    }
175}