1use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, Serialize)]
13pub struct CliError {
14 pub code: String,
16 pub message: String,
18 #[serde(skip_serializing_if = "Option::is_none")]
20 pub hint: Option<String>,
21}
22
23impl CliError {
24 #[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 #[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#[derive(Debug, Clone, Serialize)]
48pub struct CliOutput<T: Serialize> {
49 pub success: bool,
51 #[serde(skip_serializing_if = "Option::is_none")]
53 pub data: Option<T>,
54 #[serde(skip_serializing_if = "Option::is_none")]
56 pub error: Option<CliError>,
57 #[serde(skip_serializing_if = "Option::is_none")]
61 pub pagination: Option<PaginationMeta>,
62 pub platform: String,
64 pub command: String,
66}
67
68impl<T: Serialize> CliOutput<T> {
69 #[must_use]
71 pub fn success(data: T, platform: &str, command: &str) -> Self {
72 Self {
73 success: true,
74 data: Some(data),
75 error: None,
76 pagination: None,
77 platform: platform.into(),
78 command: command.into(),
79 }
80 }
81
82 #[must_use]
84 pub fn failure(error: CliError, platform: &str) -> Self {
85 Self {
86 success: false,
87 data: None,
88 error: Some(error),
89 pagination: None,
90 platform: platform.into(),
91 command: String::new(),
92 }
93 }
94
95 #[must_use]
97 pub fn success_paged(
98 data: T,
99 pagination: PaginationMeta,
100 platform: &str,
101 command: &str,
102 ) -> Self {
103 Self {
104 success: true,
105 data: Some(data),
106 error: None,
107 pagination: Some(pagination),
108 platform: platform.into(),
109 command: command.into(),
110 }
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct PaginationMeta {
121 pub truncated: bool,
123 pub returned: usize,
125 pub limit: u32,
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[derive(Debug, Clone, Serialize)]
134 struct SampleData {
135 url: String,
136 number: u64,
137 }
138
139 #[test]
140 fn test_success_output_serializes_with_data_no_error() {
141 let data = SampleData {
142 url: "https://github.com/user/repo/issues/1".into(),
143 number: 1,
144 };
145 let output = CliOutput::success(data, "github", "issue create");
146 let json = serde_json::to_string(&output).expect("failed to serialize");
147
148 assert!(json.contains(r#""success":true"#));
149 assert!(json.contains(r#""url""#));
150 assert!(json.contains(r#""number":1"#));
151 assert!(json.contains(r#""platform":"github""#));
152 assert!(json.contains(r#""command":"issue create""#));
153 assert!(!json.contains(r#""error""#));
154 assert!(!json.contains(r#""data":null"#));
155 }
156
157 #[test]
158 fn test_failure_output_serializes_with_error_no_data() {
159 let error = CliError::new("AUTH_FAILED", "Authentication failed");
160 let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "github");
161 let json = serde_json::to_string(&output).expect("failed to serialize");
162
163 assert!(json.contains(r#""success":false"#));
164 assert!(json.contains(r#""code":"AUTH_FAILED""#));
165 assert!(json.contains(r#""message":"Authentication failed""#));
166 assert!(json.contains(r#""platform":"github""#));
167 assert!(!json.contains(r#""data""#));
168 }
169
170 #[test]
171 fn test_hint_omitted_when_none() {
172 let error = CliError::new("NOT_FOUND", "Resource not found");
173 let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "gitlab");
174 let json = serde_json::to_string(&output).expect("failed to serialize");
175
176 assert!(!json.contains(r#""hint""#));
177 }
178
179 #[test]
180 fn test_with_hint_adds_hint() {
181 let error =
182 CliError::new("AUTH_FAILED", "Authentication failed").with_hint("Run 'gf auth login'");
183 let output: CliOutput<serde_json::Value> = CliOutput::failure(error, "github");
184 let json = serde_json::to_string(&output).expect("failed to serialize");
185
186 assert!(json.contains(r#""hint":"Run 'gf auth login'"#));
187 }
188
189 #[test]
190 fn test_cli_error_new_and_with_hint() {
191 let error = CliError::new("TEST_ERROR", "test message").with_hint("test hint");
192
193 assert_eq!(error.code, "TEST_ERROR");
194 assert_eq!(error.message, "test message");
195 assert_eq!(error.hint, Some("test hint".into()));
196 }
197
198 #[test]
199 fn test_should_omit_pagination_key_for_non_list_output() {
200 let output = CliOutput::success("payload", "github", "issue view");
201 let json = serde_json::to_value(&output).expect("serialize");
202 assert!(
203 json.get("pagination").is_none(),
204 "非列表命令的输出必须与改动前逐字节相同,不得出现 pagination 键"
205 );
206 }
207
208 #[test]
209 fn test_should_keep_data_as_array_for_paged_output() {
210 let paged = crate::paging::Paged {
211 items: vec![1_u32, 2, 3],
212 truncated: false,
213 limit: 1000,
214 };
215 let (items, meta) = paged.into_parts();
216 let output = CliOutput::success_paged(items, meta, "github", "issue list");
217 let json = serde_json::to_value(&output).expect("serialize");
218 assert!(
219 json["data"].is_array(),
220 "data 必须仍是数组,不得被包装成 {{items: [..]}}"
221 );
222 assert_eq!(json["data"].as_array().map(Vec::len), Some(3));
223 }
224
225 #[test]
226 fn test_should_emit_pagination_meta_in_camel_case() {
227 let paged = crate::paging::Paged {
228 items: vec![1_u32],
229 truncated: true,
230 limit: 1,
231 };
232 let (items, meta) = paged.into_parts();
233 let output = CliOutput::success_paged(items, meta, "github", "issue list");
234 let json = serde_json::to_value(&output).expect("serialize");
235 assert_eq!(json["pagination"]["truncated"], serde_json::json!(true));
236 assert_eq!(json["pagination"]["returned"], serde_json::json!(1));
237 assert_eq!(json["pagination"]["limit"], serde_json::json!(1));
238 }
239
240 #[test]
241 fn test_should_derive_returned_from_item_count() {
242 let paged = crate::paging::Paged {
243 items: vec!["a", "b"],
244 truncated: false,
245 limit: 1000,
246 };
247 let (_, meta) = paged.into_parts();
248 assert_eq!(meta.returned, 2);
249 assert!(!meta.truncated);
250 assert_eq!(meta.limit, 1000);
251 }
252}