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    tracing::debug!(raw_stderr = %text, "glab command failed");
14
15    let is_auth_failure = |t: &str| {
16        let lower = t.to_ascii_lowercase();
17        lower.contains("not authenticated")
18            || lower.contains("unauthorized")
19            || lower.contains("401")
20            || lower.contains("token")
21    };
22
23    // 尝试解析 glab 的 JSON 错误格式
24    if let Ok(json) = serde_json::from_slice::<serde_json::Value>(stderr)
25        && let Some(msg) = json.get("message").and_then(serde_json::Value::as_str)
26    {
27        let code = json
28            .get("code")
29            .and_then(serde_json::Value::as_str)
30            .map(String::from);
31
32        let user_message: String = match code.as_deref() {
33            Some("NOT_FOUND") => "资源不存在".into(),
34            Some("FORBIDDEN") => "权限不足".into(),
35            Some("RATE_LIMITED") => "API 请求频率超限".into(),
36            Some("VALIDATION_FAILED") => "请求参数校验失败".into(),
37            Some("CONFLICT") => "存在冲突,请先合并最新变更".into(),
38            _ if is_auth_failure(&text) => "未登录 GitLab".into(),
39            _ => format!("GitLab 操作失败:{msg}"),
40        };
41
42        let hint = match code.as_deref() {
43            Some("UNAUTHORIZED") => Some("运行 `glab auth login` 完成登录".into()),
44            Some("RATE_LIMITED") => Some("等待几分钟后重试".into()),
45            Some("VALIDATION_FAILED") => Some("检查请求参数格式是否正确".into()),
46            Some("CONFLICT") => Some("运行 `git pull --rebase` 解决冲突后重试".into()),
47            Some("NOT_FOUND") => Some("检查资源编号或项目路径是否正确".into()),
48            Some("FORBIDDEN") => Some("检查当前账号对该资源的权限".into()),
49            _ if is_auth_failure(&text) => Some("运行 `glab auth login` 完成登录".into()),
50            _ => None,
51        };
52        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
53        err.hint = hint;
54        err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
55        err.code = code;
56        return err;
57    }
58
59    // 回退:纯文本解析
60    let is_auth = is_auth_failure(&text);
61    let user_message: String = if is_auth {
62        "未登录 GitLab".into()
63    } else {
64        "GitLab CLI 执行失败".into()
65    };
66
67    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
68    if is_auth {
69        err.hint = Some("运行 `glab auth login` 完成登录".into());
70    }
71    err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
72    err
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn test_should_parse_glab_json_error_to_platform_cli_error() {
81        let json = br#"{"message": "404 Not Found", "code": "NOT_FOUND"}"#;
82        let err = parse_glab_error(json);
83        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
84        assert_eq!(err.platform, Platform::GitLab);
85        assert!(!err.user_message.is_empty());
86        assert!(!err.raw_stderr.is_empty());
87    }
88
89    #[test]
90    fn test_should_parse_glab_plain_text_error() {
91        let stderr = b"ERROR: not authenticated";
92        let err = parse_glab_error(stderr);
93        assert!(err.hint.is_some());
94        assert_eq!(err.platform, Platform::GitLab);
95        assert!(err.raw_stderr.contains("not authenticated"));
96    }
97
98    #[test]
99    fn test_should_not_leak_raw_stderr_in_display() {
100        let stderr = b"glab internal trace";
101        let err = parse_glab_error(stderr);
102        assert!(!err.to_string().contains("glab internal trace"));
103    }
104
105    #[test]
106    fn test_should_handle_empty_stderr() {
107        let err = parse_glab_error(b"");
108        assert!(!err.user_message.is_empty());
109        assert_eq!(err.user_message, "GitLab CLI 执行失败");
110        assert!(err.hint.is_none());
111    }
112
113    #[test]
114    fn test_should_parse_glab_forbidden_error() {
115        let json = br#"{"message": "Forbidden", "code": "FORBIDDEN"}"#;
116        let err = parse_glab_error(json);
117        assert_eq!(err.code.as_deref(), Some("FORBIDDEN"));
118        assert_eq!(err.platform, Platform::GitLab);
119        assert!(err.user_message.contains("权限"));
120    }
121
122    #[test]
123    fn test_should_parse_glab_json_error_without_code() {
124        let json = br#"{"message": "Internal error"}"#;
125        let err = parse_glab_error(json);
126        assert!(err.code.is_none());
127        assert!(err.user_message.contains("Internal error"));
128        assert_eq!(err.platform, Platform::GitLab);
129    }
130
131    #[test]
132    fn test_should_parse_glab_plain_text_auth_error() {
133        let stderr = b"ERROR: not authenticated";
134        let err = parse_glab_error(stderr);
135        assert!(err.user_message.contains("登录"));
136        assert!(
137            err.hint
138                .as_deref()
139                .unwrap_or("")
140                .contains("glab auth login")
141        );
142        assert_eq!(err.platform, Platform::GitLab);
143    }
144
145    #[test]
146    fn test_should_parse_glab_rate_limited_error() {
147        let json = br#"{"message": "Rate limit exceeded", "code": "RATE_LIMITED"}"#;
148        let err = parse_glab_error(json);
149        assert_eq!(err.code.as_deref(), Some("RATE_LIMITED"));
150        assert!(err.user_message.contains("频率"));
151    }
152
153    #[test]
154    fn test_should_parse_glab_validation_failed_error() {
155        let json = br#"{"message": "Validation failed", "code": "VALIDATION_FAILED"}"#;
156        let err = parse_glab_error(json);
157        assert_eq!(err.code.as_deref(), Some("VALIDATION_FAILED"));
158        assert!(err.hint.is_some());
159    }
160
161    #[test]
162    fn test_should_parse_glab_conflict_error() {
163        let json = br#"{"message": "Conflict detected", "code": "CONFLICT"}"#;
164        let err = parse_glab_error(json);
165        assert_eq!(err.code.as_deref(), Some("CONFLICT"));
166        assert!(err.user_message.contains("冲突"));
167    }
168
169    #[test]
170    fn test_should_not_hint_auth_login_on_unknown_flag_error() {
171        let err = parse_glab_error(b"ERROR: Unknown flag: --output");
172        assert!(
173            !err.hint
174                .as_deref()
175                .unwrap_or("")
176                .contains("glab auth login")
177        );
178        assert!(err.user_message.contains("执行失败") || !err.user_message.contains("未登录"));
179    }
180
181    #[test]
182    fn test_should_hint_auth_login_on_not_authenticated_error() {
183        let err = parse_glab_error(b"ERROR: not authenticated");
184        assert!(
185            err.hint
186                .as_deref()
187                .unwrap_or("")
188                .contains("glab auth login")
189        );
190    }
191
192    #[test]
193    fn test_should_not_hint_auth_login_on_not_found_json_error() {
194        let err = parse_glab_error(br#"{"message": "404 Not Found", "code": "NOT_FOUND"}"#);
195        assert!(!err.hint.as_deref().unwrap_or("").contains("glab auth"));
196    }
197}