Skip to main content

gitflow_core/
cli_error.rs

1//! 统一的底层平台 CLI 错误类型。
2
3use std::fmt;
4
5use crate::platform::Platform;
6
7/// 统一的底层平台 CLI 错误。
8///
9/// 各平台 crate 的 `parse_*_error()` 函数返回此类型,
10/// 替代原先各自定义的 `GhError`、`GlabError`、`GitcodeError`。
11///
12/// 用户可见信息(`user_message`、`hint`)为中文主导;
13/// `raw_stderr` 仅用于 `tracing::debug!`,不展示给用户。
14#[derive(Debug, Clone)]
15#[non_exhaustive]
16pub struct PlatformCliError {
17    /// 用户可见的错误消息(中文主导)。
18    pub user_message: String,
19    /// 底层 CLI 原始 stderr(仅用于调试日志,不展示给用户)。
20    pub raw_stderr: String,
21    /// 修复建议(中文)。
22    pub hint: Option<String>,
23    /// 相关文档链接。
24    pub doc_link: Option<String>,
25    /// 平台错误代码(如 `NOT_FOUND`)。
26    pub code: Option<String>,
27    /// 来源平台。
28    pub platform: Platform,
29}
30
31impl PlatformCliError {
32    /// 创建一个新的平台 CLI 错误。
33    ///
34    /// `hint`、`doc_link`、`code` 默认为 `None`,可通过公开字段直接设置。
35    #[must_use]
36    pub fn new(
37        user_message: impl Into<String>,
38        raw_stderr: impl Into<String>,
39        platform: Platform,
40    ) -> Self {
41        Self {
42            user_message: user_message.into(),
43            raw_stderr: raw_stderr.into(),
44            hint: None,
45            doc_link: None,
46            code: None,
47            platform,
48        }
49    }
50}
51
52impl fmt::Display for PlatformCliError {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(f, "{}", self.user_message)?;
55        if let Some(ref hint) = self.hint {
56            write!(f, "\n\n🔧 修复建议:{hint}")?;
57        }
58        if let Some(ref link) = self.doc_link {
59            write!(f, "\n📖 文档:{link}")?;
60        }
61        Ok(())
62    }
63}
64
65impl std::error::Error for PlatformCliError {}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn test_should_display_user_message_only_when_no_hint_no_link() {
73        let err = PlatformCliError {
74            user_message: "资源不存在".into(),
75            raw_stderr: "gh: NOT_FOUND".into(),
76            hint: None,
77            doc_link: None,
78            code: Some("NOT_FOUND".into()),
79            platform: Platform::GitHub,
80        };
81        assert_eq!(err.to_string(), "资源不存在");
82    }
83
84    #[test]
85    fn test_should_display_with_hint_and_doc_link() {
86        let err = PlatformCliError {
87            user_message: "认证失败".into(),
88            raw_stderr: "raw error".into(),
89            hint: Some("运行 `gh auth login` 重新认证".into()),
90            doc_link: Some("https://cli.github.com/manual/".into()),
91            code: None,
92            platform: Platform::GitHub,
93        };
94        let display = err.to_string();
95        assert!(display.contains("认证失败"));
96        assert!(display.contains("🔧 修复建议:运行 `gh auth login` 重新认证"));
97        assert!(display.contains("📖 文档:https://cli.github.com/manual/"));
98        // raw_stderr must NOT appear in Display
99        assert!(!display.contains("raw error"));
100    }
101
102    #[test]
103    fn test_should_include_raw_stderr_in_debug() {
104        let err = PlatformCliError {
105            user_message: "错误".into(),
106            raw_stderr: "secret debug info".into(),
107            hint: None,
108            doc_link: None,
109            code: None,
110            platform: Platform::GitLab,
111        };
112        let debug = format!("{err:?}");
113        assert!(debug.contains("secret debug info"));
114    }
115}