Skip to main content

gitflow_gitlab/
error.rs

1//! GitLab CLI 错误解析。
2
3use gitflow_core::{PlatformCliError, platform::Platform};
4
5/// 解析 `glab` CLI 的 stderr 输出为统一的 [`PlatformCliError`]。
6///
7/// 优先尝试 JSON 格式解析(`glab` 在 API 错误时输出 JSON),
8/// 回退到纯文本模式。
9/// 用户可见消息为中文。
10#[must_use]
11pub fn parse_glab_error(stderr: &[u8]) -> PlatformCliError {
12    let text = String::from_utf8_lossy(stderr);
13
14    // 尝试解析 glab 的 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            _ => format!("GitLab 操作失败:{msg}"),
30        };
31
32        let hint = match code.as_deref() {
33            Some("RATE_LIMITED") => Some("等待几分钟后重试".into()),
34            Some("VALIDATION_FAILED") => Some("检查请求参数格式是否正确".into()),
35            Some("CONFLICT") => Some("运行 `git pull --rebase` 解决冲突后重试".into()),
36            _ => Some("运行 `glab auth status` 检查认证状态".into()),
37        };
38        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
39        err.hint = hint;
40        err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
41        err.code = code;
42        return err;
43    }
44
45    // 回退:纯文本解析
46    let user_message: String = if text.contains("not authenticated") || text.contains("auth") {
47        "未登录 GitLab".into()
48    } else {
49        "GitLab CLI 执行失败".into()
50    };
51
52    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
53    err.hint = Some("运行 `glab auth login` 完成登录".into());
54    err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
55    err
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_should_parse_glab_json_error_to_platform_cli_error() {
64        let json = br#"{"message": "404 Not Found", "code": "NOT_FOUND"}"#;
65        let err = parse_glab_error(json);
66        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
67        assert_eq!(err.platform, Platform::GitLab);
68        assert!(!err.user_message.is_empty());
69        assert!(!err.raw_stderr.is_empty());
70    }
71
72    #[test]
73    fn test_should_parse_glab_plain_text_error() {
74        let stderr = b"ERROR: not authenticated";
75        let err = parse_glab_error(stderr);
76        assert!(err.hint.is_some());
77        assert_eq!(err.platform, Platform::GitLab);
78        assert!(err.raw_stderr.contains("not authenticated"));
79    }
80
81    #[test]
82    fn test_should_not_leak_raw_stderr_in_display() {
83        let stderr = b"glab internal trace";
84        let err = parse_glab_error(stderr);
85        assert!(!err.to_string().contains("glab internal trace"));
86    }
87
88    #[test]
89    fn test_should_handle_empty_stderr() {
90        let err = parse_glab_error(b"");
91        assert!(!err.user_message.is_empty());
92        assert!(err.hint.is_some());
93    }
94
95    #[test]
96    fn test_should_parse_glab_forbidden_error() {
97        let json = br#"{"message": "Forbidden", "code": "FORBIDDEN"}"#;
98        let err = parse_glab_error(json);
99        assert_eq!(err.code.as_deref(), Some("FORBIDDEN"));
100        assert_eq!(err.platform, Platform::GitLab);
101        assert!(err.user_message.contains("权限"));
102    }
103
104    #[test]
105    fn test_should_parse_glab_json_error_without_code() {
106        let json = br#"{"message": "Internal error"}"#;
107        let err = parse_glab_error(json);
108        assert!(err.code.is_none());
109        assert!(err.user_message.contains("Internal error"));
110        assert_eq!(err.platform, Platform::GitLab);
111    }
112
113    #[test]
114    fn test_should_parse_glab_plain_text_auth_error() {
115        let stderr = b"ERROR: auth failed";
116        let err = parse_glab_error(stderr);
117        assert!(err.user_message.contains("登录"));
118        assert_eq!(err.platform, Platform::GitLab);
119    }
120
121    #[test]
122    fn test_should_parse_glab_rate_limited_error() {
123        let json = br#"{"message": "Rate limit exceeded", "code": "RATE_LIMITED"}"#;
124        let err = parse_glab_error(json);
125        assert_eq!(err.code.as_deref(), Some("RATE_LIMITED"));
126        assert!(err.user_message.contains("频率"));
127    }
128
129    #[test]
130    fn test_should_parse_glab_validation_failed_error() {
131        let json = br#"{"message": "Validation failed", "code": "VALIDATION_FAILED"}"#;
132        let err = parse_glab_error(json);
133        assert_eq!(err.code.as_deref(), Some("VALIDATION_FAILED"));
134        assert!(err.hint.is_some());
135    }
136
137    #[test]
138    fn test_should_parse_glab_conflict_error() {
139        let json = br#"{"message": "Conflict detected", "code": "CONFLICT"}"#;
140        let err = parse_glab_error(json);
141        assert_eq!(err.code.as_deref(), Some("CONFLICT"));
142        assert!(err.user_message.contains("冲突"));
143    }
144}