1use gitflow_core::{PlatformCliError, platform::Platform};
4
5#[must_use]
11pub fn parse_glab_error(stderr: &[u8]) -> PlatformCliError {
12 let text = String::from_utf8_lossy(stderr);
13
14 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!("GitLab 操作失败:{msg}"),
27 };
28
29 let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
30 err.hint = Some("运行 `glab auth status` 检查认证状态".into());
31 err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
32 err.code = code;
33 return err;
34 }
35
36 let user_message: String = if text.contains("not authenticated") || text.contains("auth") {
38 "未登录 GitLab".into()
39 } else {
40 "GitLab CLI 执行失败".into()
41 };
42
43 let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitLab);
44 err.hint = Some("运行 `glab auth login` 完成登录".into());
45 err.doc_link = Some("https://gitlab.com/gitlab-org/cli/-/blob/main/docs/".into());
46 err
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_should_parse_glab_json_error_to_platform_cli_error() {
55 let json = br#"{"message": "404 Not Found", "code": "NOT_FOUND"}"#;
56 let err = parse_glab_error(json);
57 assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
58 assert_eq!(err.platform, Platform::GitLab);
59 assert!(!err.user_message.is_empty());
60 assert!(!err.raw_stderr.is_empty());
61 }
62
63 #[test]
64 fn test_should_parse_glab_plain_text_error() {
65 let stderr = b"ERROR: not authenticated";
66 let err = parse_glab_error(stderr);
67 assert!(err.hint.is_some());
68 assert_eq!(err.platform, Platform::GitLab);
69 assert!(err.raw_stderr.contains("not authenticated"));
70 }
71
72 #[test]
73 fn test_should_not_leak_raw_stderr_in_display() {
74 let stderr = b"glab internal trace";
75 let err = parse_glab_error(stderr);
76 assert!(!err.to_string().contains("glab internal trace"));
77 }
78
79 #[test]
80 fn test_should_handle_empty_stderr() {
81 let err = parse_glab_error(b"");
82 assert!(!err.user_message.is_empty());
83 assert!(err.hint.is_some());
84 }
85}