gitflow_core/
cli_error.rs1use std::fmt;
4
5use crate::platform::Platform;
6
7#[derive(Debug, Clone)]
15#[non_exhaustive]
16pub struct PlatformCliError {
17 pub user_message: String,
19 pub raw_stderr: String,
21 pub hint: Option<String>,
23 pub doc_link: Option<String>,
25 pub code: Option<String>,
27 pub platform: Platform,
29}
30
31impl PlatformCliError {
32 #[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 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}