Skip to main content

gitflow_core/
output.rs

1//! CLI output types for uniform JSON serialization.
2//!
3//! All commands return a [`CliOutput`] that serializes to a consistent
4//! JSON envelope with `success`, optional `data`, optional `error`,
5//! and metadata fields.
6
7use serde::Serialize;
8
9/// CLI error information.
10///
11/// Returned as part of [`CliOutput`] when a command fails.
12#[derive(Debug, Clone, Serialize)]
13pub struct CliError {
14    /// Machine-readable error code (e.g. `"AUTH_FAILED"`).
15    pub code: String,
16    /// Human-readable error message.
17    pub message: String,
18    /// Optional hint for the user on how to resolve the error.
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub hint: Option<String>,
21}
22
23impl CliError {
24    /// Create a new error with a code and message.
25    #[must_use]
26    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
27        Self {
28            code: code.into(),
29            message: message.into(),
30            hint: None,
31        }
32    }
33
34    /// Attach a hint to the error.
35    #[must_use]
36    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
37        self.hint = Some(hint.into());
38        self
39    }
40}
41
42/// Unified CLI JSON output envelope.
43///
44/// On success, `data` is populated and `error` is `None`.
45/// On failure, `error` is populated and `data` is `None`.
46/// Fields with `None` values are omitted from serialized output.
47#[derive(Debug, Clone, Serialize)]
48pub struct CliOutput<T: Serialize> {
49    /// Whether the command succeeded.
50    pub success: bool,
51    /// The payload data, present only on success.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub data: Option<T>,
54    /// Error details, present only on failure.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub error: Option<CliError>,
57    /// The detected platform (e.g. `"github"`).
58    pub platform: String,
59    /// The command that was executed (e.g. `"issue create"`).
60    pub command: String,
61}
62
63impl<T: Serialize> CliOutput<T> {
64    /// Create a successful output with the given data.
65    #[must_use]
66    pub fn success(data: T, platform: &str, command: &str) -> Self {
67        Self {
68            success: true,
69            data: Some(data),
70            error: None,
71            platform: platform.into(),
72            command: command.into(),
73        }
74    }
75
76    /// Create a failed output with the given error.
77    #[must_use]
78    pub fn failure(error: CliError, platform: &str) -> Self {
79        Self {
80            success: false,
81            data: None,
82            error: Some(error),
83            platform: platform.into(),
84            command: String::new(),
85        }
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[derive(Debug, Clone, Serialize)]
94    struct SampleData {
95        url: String,
96        number: u64,
97    }
98
99    #[test]
100    fn test_success_output_serializes_with_data_no_error() {
101        let data = SampleData {
102            url: "https://github.com/user/repo/issues/1".into(),
103            number: 1,
104        };
105        let output = CliOutput::success(data, "github", "issue create");
106        let json = serde_json::to_string(&output).expect("failed to serialize");
107
108        assert!(json.contains(r#""success":true"#));
109        assert!(json.contains(r#""url""#));
110        assert!(json.contains(r#""number":1"#));
111        assert!(json.contains(r#""platform":"github""#));
112        assert!(json.contains(r#""command":"issue create""#));
113        assert!(!json.contains(r#""error""#));
114        assert!(!json.contains(r#""data":null"#));
115    }
116
117    #[test]
118    fn test_failure_output_serializes_with_error_no_data() {
119        let error = CliError::new("AUTH_FAILED", "Authentication failed");
120        let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "github");
121        let json = serde_json::to_string(&output).expect("failed to serialize");
122
123        assert!(json.contains(r#""success":false"#));
124        assert!(json.contains(r#""code":"AUTH_FAILED""#));
125        assert!(json.contains(r#""message":"Authentication failed""#));
126        assert!(json.contains(r#""platform":"github""#));
127        assert!(!json.contains(r#""data""#));
128    }
129
130    #[test]
131    fn test_hint_omitted_when_none() {
132        let error = CliError::new("NOT_FOUND", "Resource not found");
133        let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "gitlab");
134        let json = serde_json::to_string(&output).expect("failed to serialize");
135
136        assert!(!json.contains(r#""hint""#));
137    }
138
139    #[test]
140    fn test_with_hint_adds_hint() {
141        let error =
142            CliError::new("AUTH_FAILED", "Authentication failed").with_hint("Run 'gf auth login'");
143        let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "github");
144        let json = serde_json::to_string(&output).expect("failed to serialize");
145
146        assert!(json.contains(r#""hint":"Run 'gf auth login'"#));
147    }
148
149    #[test]
150    fn test_cli_error_new_and_with_hint() {
151        let error = CliError::new("TEST_ERROR", "test message").with_hint("test hint");
152
153        assert_eq!(error.code, "TEST_ERROR");
154        assert_eq!(error.message, "test message");
155        assert_eq!(error.hint, Some("test hint".into()));
156    }
157}