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    let is_auth_failure = |t: &str| {
15        let lower = t.to_ascii_lowercase();
16        lower.contains("not authenticated")
17            || lower.contains("unauthorized")
18            || lower.contains("not logged in")
19            || lower.contains("401")
20            || lower.contains("token")
21    };
22
23    // 尝试解析 gh 的 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            Some("GONE") => "资源已被删除或迁移".into(),
39            _ => format!("GitHub 操作失败:{msg}"),
40        };
41
42        let hint = match code.as_deref() {
43            Some("UNAUTHORIZED") => Some("运行 `gh auth status` 检查认证状态".into()),
44            Some("RATE_LIMITED") => Some("等待几分钟后重试".into()),
45            Some("VALIDATION_FAILED") => Some("检查请求参数格式是否正确".into()),
46            Some("CONFLICT") => Some("运行 `git pull --rebase` 解决冲突后重试".into()),
47            Some("GONE") => Some("确认资源是否存在,可能已被删除或重命名".into()),
48            Some("NOT_FOUND") => Some("检查资源名称或编号是否正确".into()),
49            Some("FORBIDDEN") => Some("检查当前账号对该资源的权限".into()),
50            _ if is_auth_failure(&text) => Some("运行 `gh auth login` 完成登录".into()),
51            _ => None,
52        };
53        let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
54        err.hint = hint;
55        err.doc_link = Some("https://cli.github.com/manual/".into());
56        err.code = code;
57        return err;
58    }
59
60    // 回退:纯文本解析
61    let is_auth = is_auth_failure(&text);
62    let user_message: String = if is_auth {
63        "未登录 GitHub".into()
64    } else {
65        "GitHub CLI 执行失败".into()
66    };
67
68    let mut err = PlatformCliError::new(user_message, text.into_owned(), Platform::GitHub);
69    if is_auth {
70        err.hint = Some("运行 `gh auth login` 完成登录".into());
71    }
72    err.doc_link = Some("https://cli.github.com/manual/".into());
73    err
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_should_parse_gh_json_error_to_platform_cli_error() {
82        let json = br#"{"message": "GraphQL: Could not resolve to a user with the login 'nobody'.", "code": "NOT_FOUND"}"#;
83        let err = parse_gh_error(json);
84        assert_eq!(err.code.as_deref(), Some("NOT_FOUND"));
85        assert_eq!(err.platform, Platform::GitHub);
86        assert!(!err.user_message.is_empty());
87        assert!(!err.raw_stderr.is_empty());
88    }
89
90    #[test]
91    fn test_should_parse_gh_plain_text_error() {
92        let stderr = b"gh: Not logged in. Please run `gh auth login` to authenticate.";
93        let err = parse_gh_error(stderr);
94        assert!(err.user_message.contains("认证") || err.user_message.contains("登录"));
95        assert!(err.hint.is_some());
96        assert_eq!(err.platform, Platform::GitHub);
97        assert!(err.raw_stderr.contains("Not logged in"));
98    }
99
100    #[test]
101    fn test_should_not_leak_raw_stderr_in_display() {
102        let stderr = b"internal gh debug trace line";
103        let err = parse_gh_error(stderr);
104        let display = err.to_string();
105        assert!(!display.contains("internal gh debug trace"));
106    }
107
108    #[test]
109    fn test_should_handle_empty_stderr() {
110        let err = parse_gh_error(b"");
111        assert!(!err.user_message.is_empty());
112        assert!(err.hint.is_none());
113    }
114
115    #[test]
116    fn test_should_not_hint_auth_login_on_unknown_flag_error() {
117        let err = parse_gh_error(b"unknown flag: --json\nUsage: gh label <command> [flags]");
118        assert!(!err.user_message.contains("未登录"));
119        assert!(err.hint.is_none());
120    }
121
122    #[test]
123    fn test_should_hint_auth_login_on_not_authenticated_error() {
124        let err = parse_gh_error(b"gh: Not logged in. Please run `gh auth login` to authenticate.");
125        assert!(err.user_message.contains("登录"));
126        assert!(
127            err.hint
128                .as_deref()
129                .is_some_and(|h| h.contains("gh auth login"))
130        );
131    }
132
133    #[test]
134    fn test_should_not_hint_auth_login_on_generic_json_error() {
135        let err = parse_gh_error(br#"{"message": "Something went wrong"}"#);
136        assert!(err.hint.is_none());
137    }
138
139    #[test]
140    fn test_should_parse_gh_forbidden_error() {
141        let json = br#"{"message": "Resource not accessible by integration", "code": "FORBIDDEN"}"#;
142        let err = parse_gh_error(json);
143        assert_eq!(err.code.as_deref(), Some("FORBIDDEN"));
144        assert_eq!(err.platform, Platform::GitHub);
145        assert!(err.user_message.contains("权限"));
146    }
147
148    #[test]
149    fn test_should_parse_gh_json_error_without_code() {
150        let json = br#"{"message": "Something went wrong"}"#;
151        let err = parse_gh_error(json);
152        assert!(err.code.is_none());
153        assert!(err.user_message.contains("Something went wrong"));
154        assert_eq!(err.platform, Platform::GitHub);
155    }
156
157    #[test]
158    fn test_should_parse_gh_rate_limited_error() {
159        let json = br#"{"message": "API rate limit exceeded", "code": "RATE_LIMITED"}"#;
160        let err = parse_gh_error(json);
161        assert_eq!(err.code.as_deref(), Some("RATE_LIMITED"));
162        assert!(err.user_message.contains("频率"));
163        assert!(
164            err.hint
165                .as_ref()
166                .is_some_and(|h| h.contains("等待") || h.contains("重试"))
167        );
168    }
169
170    #[test]
171    fn test_should_parse_gh_validation_failed_error() {
172        let json = br#"{"message": "Validation failed", "code": "VALIDATION_FAILED"}"#;
173        let err = parse_gh_error(json);
174        assert_eq!(err.code.as_deref(), Some("VALIDATION_FAILED"));
175        assert!(err.hint.is_some());
176    }
177
178    #[test]
179    fn test_should_parse_gh_conflict_error() {
180        let json = br#"{"message": "Merge conflict", "code": "CONFLICT"}"#;
181        let err = parse_gh_error(json);
182        assert_eq!(err.code.as_deref(), Some("CONFLICT"));
183        assert!(err.user_message.contains("冲突"));
184    }
185
186    #[test]
187    fn test_should_parse_gh_gone_error() {
188        let json = br#"{"message": "Resource gone", "code": "GONE"}"#;
189        let err = parse_gh_error(json);
190        assert_eq!(err.code.as_deref(), Some("GONE"));
191        assert!(err.user_message.contains("删除") || err.user_message.contains("迁移"));
192    }
193}