Skip to main content

wekan_cli/
output.rs

1mod attachments;
2mod auth;
3mod boards;
4mod cards;
5mod checklist_items;
6mod checklists;
7mod comments;
8mod custom_field_items;
9mod custom_fields;
10mod dependencies;
11mod formatting;
12mod lists;
13mod profiles;
14mod raw;
15mod swimlanes;
16mod users;
17
18use auth::{render_auth_status, render_auth_success, render_logout};
19use boards::{
20    render_board_count, render_board_created, render_board_deleted, render_board_detail,
21    render_board_list, render_board_renamed,
22};
23use cards::{
24    render_card_archived, render_card_collection, render_card_created, render_card_deleted,
25    render_card_detail, render_card_restored, render_card_updated,
26};
27use checklist_items::{
28    render_checklist_item_created, render_checklist_item_deleted, render_checklist_item_detail,
29    render_checklist_item_updated,
30};
31use checklists::{
32    render_checklist_collection, render_checklist_created, render_checklist_deleted,
33    render_checklist_detail,
34};
35use comments::{
36    render_comment_collection, render_comment_created, render_comment_deleted,
37    render_comment_detail,
38};
39use lists::{
40    render_list_collection, render_list_created, render_list_deleted, render_list_detail,
41    render_list_updated,
42};
43use profiles::{render_profile_item, render_profile_list, render_profile_removed};
44use swimlanes::{
45    render_swimlane_collection, render_swimlane_created, render_swimlane_deleted,
46    render_swimlane_detail, render_swimlane_updated,
47};
48use users::{
49    render_user_boards, render_user_cards, render_user_created, render_user_deleted,
50    render_user_detail, render_user_list, render_user_login_change, render_user_ownership,
51};
52
53use std::{ffi::OsString, io::Write, process::ExitCode};
54
55use clap::ValueEnum;
56use serde::Serialize;
57
58use crate::command_result::CommandSuccess;
59use crate::{
60    error::{AppError, ErrorCode},
61    exit_code::StableExitCode,
62};
63
64pub(crate) use raw::render_human_response as render_api_response_human;
65#[cfg(test)]
66pub(crate) use raw::structured_api_response;
67
68#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
69#[value(rename_all = "lower")]
70pub enum OutputFormat {
71    #[default]
72    Human,
73    Json,
74    Raw,
75}
76
77impl OutputFormat {
78    pub fn detect_from_args(args: &[OsString]) -> Self {
79        let mut iter = args.iter().filter_map(|arg| arg.to_str());
80        while let Some(arg) = iter.next() {
81            if arg == "--output" {
82                return match iter.next() {
83                    Some("json") => Self::Json,
84                    Some("raw") => Self::Raw,
85                    _ => Self::Human,
86                };
87            }
88            if arg == "--output=json" {
89                return Self::Json;
90            }
91            if arg == "--output=raw" {
92                return Self::Raw;
93            }
94        }
95        Self::Human
96    }
97}
98
99#[derive(Serialize)]
100struct SuccessEnvelope<'a, T> {
101    ok: bool,
102    data: &'a T,
103}
104
105#[derive(Serialize)]
106struct ErrorEnvelope<'a> {
107    ok: bool,
108    error: ErrorBody<'a>,
109}
110
111#[derive(Serialize)]
112struct ErrorBody<'a> {
113    code: &'static str,
114    message: &'a str,
115    details: &'a crate::error::ErrorDetails,
116}
117
118pub fn render_success(format: OutputFormat, success: &CommandSuccess) -> String {
119    match (format, success) {
120        (OutputFormat::Human, CommandSuccess::BoardMembers(data)) => {
121            boards::render_membership(data)
122        }
123        (OutputFormat::Json, CommandSuccess::BoardMembers(data)) => render_json_success(data),
124        (OutputFormat::Human, CommandSuccess::BoardMemberChanged(data)) => {
125            boards::render_membership(data)
126        }
127        (OutputFormat::Json, CommandSuccess::BoardMemberChanged(data)) => render_json_success(data),
128        (OutputFormat::Human, CommandSuccess::BoardMemberUpdated(data)) => {
129            boards::render_membership(data)
130        }
131        (OutputFormat::Json, CommandSuccess::BoardMemberUpdated(data)) => render_json_success(data),
132        (OutputFormat::Human, CommandSuccess::CardMembers(data)) => cards::render_membership(data),
133        (OutputFormat::Json, CommandSuccess::CardMembers(data)) => render_json_success(data),
134        (OutputFormat::Human, CommandSuccess::CardAssignees(data)) => {
135            cards::render_membership(data)
136        }
137        (OutputFormat::Json, CommandSuccess::CardAssignees(data)) => render_json_success(data),
138        (OutputFormat::Human, CommandSuccess::CardMembershipChanged(data)) => {
139            cards::render_membership(data)
140        }
141        (OutputFormat::Json, CommandSuccess::CardMembershipChanged(data)) => {
142            render_json_success(data)
143        }
144        (OutputFormat::Human, CommandSuccess::CardDependencies(data)) => {
145            dependencies::card_collection(data)
146        }
147        (OutputFormat::Json, CommandSuccess::CardDependencies(data)) => render_json_success(data),
148        (OutputFormat::Human, CommandSuccess::BoardDependencies(data)) => {
149            dependencies::board_collection(data)
150        }
151        (OutputFormat::Json, CommandSuccess::BoardDependencies(data)) => render_json_success(data),
152        (OutputFormat::Human, CommandSuccess::DependencyCreated(data)) => {
153            dependencies::created(data)
154        }
155        (OutputFormat::Json, CommandSuccess::DependencyCreated(data)) => render_json_success(data),
156        (OutputFormat::Human, CommandSuccess::DependencyUpdated(data)) => {
157            dependencies::updated(data)
158        }
159        (OutputFormat::Json, CommandSuccess::DependencyUpdated(data)) => render_json_success(data),
160        (OutputFormat::Human, CommandSuccess::DependencyDeleted(data)) => {
161            dependencies::deleted(data)
162        }
163        (OutputFormat::Json, CommandSuccess::DependencyDeleted(data)) => render_json_success(data),
164        (OutputFormat::Human, CommandSuccess::AttachmentList(data)) => attachments::list(data),
165        (OutputFormat::Json, CommandSuccess::AttachmentList(data)) => render_json_success(data),
166        (OutputFormat::Human, CommandSuccess::AttachmentShown(data)) => attachments::detail(data),
167        (OutputFormat::Json, CommandSuccess::AttachmentShown(data)) => render_json_success(data),
168        (OutputFormat::Human, CommandSuccess::AttachmentUploaded(data)) => {
169            attachments::detail(data)
170        }
171        (OutputFormat::Json, CommandSuccess::AttachmentUploaded(data)) => render_json_success(data),
172        (OutputFormat::Human, CommandSuccess::BackgroundUploaded(data)) => {
173            attachments::detail(data)
174        }
175        (OutputFormat::Json, CommandSuccess::BackgroundUploaded(data)) => render_json_success(data),
176        (OutputFormat::Human, CommandSuccess::AttachmentCopied(data)) => attachments::detail(data),
177        (OutputFormat::Json, CommandSuccess::AttachmentCopied(data)) => render_json_success(data),
178        (OutputFormat::Human, CommandSuccess::AttachmentMoved(data)) => attachments::detail(data),
179        (OutputFormat::Json, CommandSuccess::AttachmentMoved(data)) => render_json_success(data),
180        (OutputFormat::Human, CommandSuccess::AttachmentDeleted(data)) => attachments::detail(data),
181        (OutputFormat::Json, CommandSuccess::AttachmentDeleted(data)) => render_json_success(data),
182        (OutputFormat::Human, CommandSuccess::AttachmentDownloaded(data)) => {
183            attachments::detail(data)
184        }
185        (OutputFormat::Json, CommandSuccess::AttachmentDownloaded(data)) => {
186            render_json_success(data)
187        }
188        (_, CommandSuccess::ApiResponse(_)) => {
189            panic!("streaming API responses must be consumed by output::write_success")
190        }
191        (OutputFormat::Raw, CommandSuccess::Cancelled(_)) => String::new(),
192        (OutputFormat::Raw, _) => panic!("raw results must be consumed by output::write_success"),
193        (OutputFormat::Human, CommandSuccess::Cancelled(_)) => {
194            "Cancelled; no changes made.".to_owned()
195        }
196        (OutputFormat::Json, CommandSuccess::Cancelled(data)) => render_json_success(data),
197        (OutputFormat::Human, CommandSuccess::Registration(data)) => {
198            render_auth_success("Registered user", data)
199        }
200        (OutputFormat::Json, CommandSuccess::Registration(data)) => render_json_success(data),
201        (OutputFormat::Human, CommandSuccess::Login(data)) => {
202            render_auth_success("Logged in user", data)
203        }
204        (OutputFormat::Json, CommandSuccess::Login(data)) => render_json_success(data),
205        (OutputFormat::Human, CommandSuccess::Logout(data)) => render_logout(data),
206        (OutputFormat::Json, CommandSuccess::Logout(data)) => render_json_success(data),
207        (OutputFormat::Human, CommandSuccess::AuthStatus(data)) => render_auth_status(data),
208        (OutputFormat::Json, CommandSuccess::AuthStatus(data)) => render_json_success(data),
209        (OutputFormat::Human, CommandSuccess::UserCurrent(data))
210        | (OutputFormat::Human, CommandSuccess::UserShown(data))
211        | (OutputFormat::Human, CommandSuccess::UserUpdated(data)) => render_user_detail(data),
212        (OutputFormat::Json, CommandSuccess::UserCurrent(data))
213        | (OutputFormat::Json, CommandSuccess::UserShown(data))
214        | (OutputFormat::Json, CommandSuccess::UserUpdated(data)) => render_json_success(data),
215        (OutputFormat::Human, CommandSuccess::UserList(data)) => render_user_list(data),
216        (OutputFormat::Json, CommandSuccess::UserList(data)) => render_json_success(data),
217        (OutputFormat::Human, CommandSuccess::UserCards(data)) => render_user_cards(data),
218        (OutputFormat::Json, CommandSuccess::UserCards(data)) => render_json_success(data),
219        (OutputFormat::Human, CommandSuccess::UserCreated(data)) => render_user_created(data),
220        (OutputFormat::Json, CommandSuccess::UserCreated(data)) => render_json_success(data),
221        (OutputFormat::Human, CommandSuccess::UserBoards(data)) => render_user_boards(data),
222        (OutputFormat::Json, CommandSuccess::UserBoards(data)) => render_json_success(data),
223        (OutputFormat::Human, CommandSuccess::UserOwnershipTaken(data)) => {
224            render_user_ownership(data)
225        }
226        (OutputFormat::Json, CommandSuccess::UserOwnershipTaken(data)) => render_json_success(data),
227        (OutputFormat::Human, CommandSuccess::UserLoginChanged(data)) => {
228            render_user_login_change(data)
229        }
230        (OutputFormat::Json, CommandSuccess::UserLoginChanged(data)) => render_json_success(data),
231        (OutputFormat::Human, CommandSuccess::UserDeleted(data)) => render_user_deleted(data),
232        (OutputFormat::Json, CommandSuccess::UserDeleted(data)) => render_json_success(data),
233        (OutputFormat::Human, CommandSuccess::BoardList(data)) => render_board_list(data),
234        (OutputFormat::Json, CommandSuccess::BoardList(data)) => render_json_success(data),
235        (OutputFormat::Human, CommandSuccess::BoardCount(data)) => render_board_count(data),
236        (OutputFormat::Json, CommandSuccess::BoardCount(data)) => render_json_success(data),
237        (OutputFormat::Human, CommandSuccess::BoardShown(data)) => render_board_detail(data),
238        (OutputFormat::Json, CommandSuccess::BoardShown(data)) => render_json_success(data),
239        (OutputFormat::Human, CommandSuccess::BoardCreated(data)) => render_board_created(data),
240        (OutputFormat::Json, CommandSuccess::BoardCreated(data)) => render_json_success(data),
241        (OutputFormat::Human, CommandSuccess::BoardRenamed(data)) => render_board_renamed(data),
242        (OutputFormat::Json, CommandSuccess::BoardRenamed(data)) => render_json_success(data),
243        (OutputFormat::Human, CommandSuccess::BoardDeleted(data)) => render_board_deleted(data),
244        (OutputFormat::Json, CommandSuccess::BoardDeleted(data)) => render_json_success(data),
245        (OutputFormat::Human, CommandSuccess::ListCollection(data)) => render_list_collection(data),
246        (OutputFormat::Json, CommandSuccess::ListCollection(data)) => render_json_success(data),
247        (OutputFormat::Human, CommandSuccess::ListShown(data)) => render_list_detail(data),
248        (OutputFormat::Json, CommandSuccess::ListShown(data)) => render_json_success(data),
249        (OutputFormat::Human, CommandSuccess::ListCreated(data)) => render_list_created(data),
250        (OutputFormat::Json, CommandSuccess::ListCreated(data)) => render_json_success(data),
251        (OutputFormat::Human, CommandSuccess::ListUpdated(data)) => render_list_updated(data),
252        (OutputFormat::Json, CommandSuccess::ListUpdated(data)) => render_json_success(data),
253        (OutputFormat::Human, CommandSuccess::ListDeleted(data)) => render_list_deleted(data),
254        (OutputFormat::Json, CommandSuccess::ListDeleted(data)) => render_json_success(data),
255        (OutputFormat::Human, CommandSuccess::CardCollection(data)) => render_card_collection(data),
256        (OutputFormat::Json, CommandSuccess::CardCollection(data)) => render_json_success(data),
257        (OutputFormat::Human, CommandSuccess::CardShown(data)) => render_card_detail(data),
258        (OutputFormat::Json, CommandSuccess::CardShown(data)) => render_json_success(data),
259        (OutputFormat::Human, CommandSuccess::CardCreated(data)) => render_card_created(data),
260        (OutputFormat::Json, CommandSuccess::CardCreated(data)) => render_json_success(data),
261        (OutputFormat::Human, CommandSuccess::CardUpdated(data)) => render_card_updated(data),
262        (OutputFormat::Json, CommandSuccess::CardUpdated(data)) => render_json_success(data),
263        (OutputFormat::Human, CommandSuccess::CardArchived(data)) => render_card_archived(data),
264        (OutputFormat::Json, CommandSuccess::CardArchived(data)) => render_json_success(data),
265        (OutputFormat::Human, CommandSuccess::CardRestored(data)) => render_card_restored(data),
266        (OutputFormat::Json, CommandSuccess::CardRestored(data)) => render_json_success(data),
267        (OutputFormat::Human, CommandSuccess::CardDeleted(data)) => render_card_deleted(data),
268        (OutputFormat::Json, CommandSuccess::CardDeleted(data)) => render_json_success(data),
269        (OutputFormat::Human, CommandSuccess::ChecklistCollection(data)) => {
270            render_checklist_collection(data)
271        }
272        (OutputFormat::Json, CommandSuccess::ChecklistCollection(data)) => {
273            render_json_success(data)
274        }
275        (OutputFormat::Human, CommandSuccess::ChecklistShown(data)) => {
276            render_checklist_detail(data)
277        }
278        (OutputFormat::Json, CommandSuccess::ChecklistShown(data)) => render_json_success(data),
279        (OutputFormat::Human, CommandSuccess::ChecklistCreated(data)) => {
280            render_checklist_created(data)
281        }
282        (OutputFormat::Json, CommandSuccess::ChecklistCreated(data)) => render_json_success(data),
283        (OutputFormat::Human, CommandSuccess::ChecklistDeleted(data)) => {
284            render_checklist_deleted(data)
285        }
286        (OutputFormat::Json, CommandSuccess::ChecklistDeleted(data)) => render_json_success(data),
287        (OutputFormat::Human, CommandSuccess::ChecklistItemShown(data)) => {
288            render_checklist_item_detail(data)
289        }
290        (OutputFormat::Json, CommandSuccess::ChecklistItemShown(data)) => render_json_success(data),
291        (OutputFormat::Human, CommandSuccess::ChecklistItemCreated(data)) => {
292            render_checklist_item_created(data)
293        }
294        (OutputFormat::Json, CommandSuccess::ChecklistItemCreated(data)) => {
295            render_json_success(data)
296        }
297        (OutputFormat::Human, CommandSuccess::ChecklistItemUpdated(data)) => {
298            render_checklist_item_updated(data)
299        }
300        (OutputFormat::Json, CommandSuccess::ChecklistItemUpdated(data)) => {
301            render_json_success(data)
302        }
303        (OutputFormat::Human, CommandSuccess::ChecklistItemDeleted(data)) => {
304            render_checklist_item_deleted(data)
305        }
306        (OutputFormat::Json, CommandSuccess::ChecklistItemDeleted(data)) => {
307            render_json_success(data)
308        }
309        (OutputFormat::Human, CommandSuccess::CustomFieldCollection(data)) => {
310            custom_fields::collection(data)
311        }
312        (OutputFormat::Json, CommandSuccess::CustomFieldCollection(data)) => {
313            render_json_success(data)
314        }
315        (OutputFormat::Human, CommandSuccess::CustomFieldShown(data)) => {
316            custom_fields::detail(data)
317        }
318        (OutputFormat::Json, CommandSuccess::CustomFieldShown(data)) => render_json_success(data),
319        (OutputFormat::Human, CommandSuccess::CustomFieldCreated(data)) => {
320            custom_fields::created(data)
321        }
322        (OutputFormat::Json, CommandSuccess::CustomFieldCreated(data)) => render_json_success(data),
323        (OutputFormat::Human, CommandSuccess::CustomFieldUpdated(data)) => {
324            custom_fields::updated(data)
325        }
326        (OutputFormat::Json, CommandSuccess::CustomFieldUpdated(data)) => render_json_success(data),
327        (OutputFormat::Human, CommandSuccess::CustomFieldDeleted(data)) => {
328            custom_fields::deleted(data)
329        }
330        (OutputFormat::Json, CommandSuccess::CustomFieldDeleted(data)) => render_json_success(data),
331        (OutputFormat::Human, CommandSuccess::CustomFieldItemsCreated(data)) => {
332            custom_field_items::created(data)
333        }
334        (OutputFormat::Json, CommandSuccess::CustomFieldItemsCreated(data)) => {
335            render_json_success(data)
336        }
337        (OutputFormat::Human, CommandSuccess::CustomFieldItemUpdated(data)) => {
338            custom_field_items::updated(data)
339        }
340        (OutputFormat::Json, CommandSuccess::CustomFieldItemUpdated(data)) => {
341            render_json_success(data)
342        }
343        (OutputFormat::Human, CommandSuccess::CustomFieldItemDeleted(data)) => {
344            custom_field_items::deleted(data)
345        }
346        (OutputFormat::Json, CommandSuccess::CustomFieldItemDeleted(data)) => {
347            render_json_success(data)
348        }
349        (OutputFormat::Human, CommandSuccess::CardCustomFieldSet(data)) => {
350            cards::render_card_custom_field_set(data)
351        }
352        (OutputFormat::Json, CommandSuccess::CardCustomFieldSet(data)) => render_json_success(data),
353        (OutputFormat::Human, CommandSuccess::CardCustomFieldQuery(data)) => {
354            cards::render_card_custom_field_query(data)
355        }
356        (OutputFormat::Json, CommandSuccess::CardCustomFieldQuery(data)) => {
357            render_json_success(data)
358        }
359        (OutputFormat::Human, CommandSuccess::CommentCollection(data)) => {
360            render_comment_collection(data)
361        }
362        (OutputFormat::Json, CommandSuccess::CommentCollection(data)) => render_json_success(data),
363        (OutputFormat::Human, CommandSuccess::CommentShown(data)) => render_comment_detail(data),
364        (OutputFormat::Json, CommandSuccess::CommentShown(data)) => render_json_success(data),
365        (OutputFormat::Human, CommandSuccess::CommentCreated(data)) => render_comment_created(data),
366        (OutputFormat::Json, CommandSuccess::CommentCreated(data)) => render_json_success(data),
367        (OutputFormat::Human, CommandSuccess::CommentDeleted(data)) => render_comment_deleted(data),
368        (OutputFormat::Json, CommandSuccess::CommentDeleted(data)) => render_json_success(data),
369        (OutputFormat::Human, CommandSuccess::SwimlaneCollection(data)) => {
370            render_swimlane_collection(data)
371        }
372        (OutputFormat::Json, CommandSuccess::SwimlaneCollection(data)) => render_json_success(data),
373        (OutputFormat::Human, CommandSuccess::SwimlaneShown(data)) => render_swimlane_detail(data),
374        (OutputFormat::Json, CommandSuccess::SwimlaneShown(data)) => render_json_success(data),
375        (OutputFormat::Human, CommandSuccess::SwimlaneCreated(data)) => {
376            render_swimlane_created(data)
377        }
378        (OutputFormat::Json, CommandSuccess::SwimlaneCreated(data)) => render_json_success(data),
379        (OutputFormat::Human, CommandSuccess::SwimlaneUpdated(data)) => {
380            render_swimlane_updated(data)
381        }
382        (OutputFormat::Json, CommandSuccess::SwimlaneUpdated(data)) => render_json_success(data),
383        (OutputFormat::Human, CommandSuccess::SwimlaneDeleted(data)) => {
384            render_swimlane_deleted(data)
385        }
386        (OutputFormat::Json, CommandSuccess::SwimlaneDeleted(data)) => render_json_success(data),
387        (OutputFormat::Human, CommandSuccess::ProfileAdded(data)) => {
388            render_profile_item("Added profile", data)
389        }
390        (OutputFormat::Json, CommandSuccess::ProfileAdded(data))
391        | (OutputFormat::Json, CommandSuccess::ProfileShown(data))
392        | (OutputFormat::Json, CommandSuccess::ProfileUsed(data))
393        | (OutputFormat::Json, CommandSuccess::ProfileUpdated(data)) => {
394            serde_json::to_string(&SuccessEnvelope { ok: true, data })
395                .expect("profile success is always serializable")
396        }
397        (OutputFormat::Human, CommandSuccess::ProfileList(data)) => render_profile_list(data),
398        (OutputFormat::Json, CommandSuccess::ProfileList(data)) => {
399            serde_json::to_string(&SuccessEnvelope { ok: true, data })
400                .expect("profile list success is always serializable")
401        }
402        (OutputFormat::Human, CommandSuccess::ProfileShown(data)) => {
403            render_profile_item("Profile", data)
404        }
405        (OutputFormat::Human, CommandSuccess::ProfileUsed(data)) => {
406            render_profile_item("Using profile", data)
407        }
408        (OutputFormat::Human, CommandSuccess::ProfileUpdated(data)) => {
409            render_profile_item("Updated profile", data)
410        }
411        (OutputFormat::Human, CommandSuccess::ProfileRemoved(data)) => render_profile_removed(data),
412        (OutputFormat::Json, CommandSuccess::ProfileRemoved(data)) => {
413            serde_json::to_string(&SuccessEnvelope { ok: true, data })
414                .expect("profile removal success is always serializable")
415        }
416    }
417}
418
419pub async fn write_success(
420    format: OutputFormat,
421    success: CommandSuccess,
422    stdout: &mut dyn Write,
423    stderr: &mut dyn Write,
424) -> Result<ExitCode, AppError> {
425    if let CommandSuccess::ApiResponse(response) = success {
426        return raw::write_response(format, response, stdout, stderr).await;
427    }
428    if format == OutputFormat::Raw {
429        if let CommandSuccess::AttachmentDownloaded(data) = &success {
430            let bytes = data.bytes.as_deref().ok_or_else(|| {
431                AppError::invalid_input("raw attachment output requires --destination -")
432            })?;
433            stdout
434                .write_all(bytes)
435                .and_then(|()| stdout.flush())
436                .map_err(output_write_error)?;
437            return Ok(ExitCode::SUCCESS);
438        }
439    }
440    let rendered = render_success(format, &success);
441    if !rendered.is_empty() {
442        let written = writeln!(stdout, "{rendered}").and_then(|()| {
443            if matches!(&success, CommandSuccess::AttachmentDownloaded(data) if data.file_saved) {
444                stdout.flush()
445            } else {
446                Ok(())
447            }
448        });
449        written.map_err(|e| {
450            let error = output_write_error(e);
451            if let CommandSuccess::AttachmentDownloaded(data) = &success {
452                if data.file_saved {
453                    return error.with_details(crate::error::ErrorDetails {
454                        file_saved: Some(true),
455                        destination: Some(data.destination.clone()),
456                        ..crate::error::ErrorDetails::default()
457                    });
458                }
459            }
460            error
461        })?;
462    }
463    Ok(ExitCode::SUCCESS)
464}
465pub(crate) fn output_write_error(error: std::io::Error) -> AppError {
466    AppError::new(
467        ErrorCode::InternalError,
468        format!("could not write command output: {error}"),
469        StableExitCode::Transport,
470    )
471}
472
473pub(crate) fn render_json_success<T: Serialize>(data: &T) -> String {
474    serde_json::to_string(&SuccessEnvelope { ok: true, data })
475        .expect("command success is always serializable")
476}
477
478pub fn render_error(format: OutputFormat, error: &AppError) -> String {
479    match format {
480        OutputFormat::Human => {
481            let mut rendered = format!(
482                "Error [{}]: {}",
483                error.code().as_str(),
484                error.message().trim()
485            );
486            if let Some(response) = &error.details().response {
487                rendered.push('\n');
488                rendered.push_str(&render_api_response_human(response));
489            }
490            if error.details().file_saved == Some(true) {
491                if let Some(destination) = &error.details().destination {
492                    rendered.push_str(&format!(
493                        "\nDownload saved to `{}`; completion output failed.",
494                        formatting::escape_terminal_controls(destination)
495                    ));
496                }
497            }
498            rendered
499        }
500        OutputFormat::Json => serde_json::to_string(&ErrorEnvelope {
501            ok: false,
502            error: ErrorBody {
503                code: error.code().as_str(),
504                message: error.message(),
505                details: error.details(),
506            },
507        })
508        .expect("application errors are always serializable"),
509        OutputFormat::Raw => format!(
510            "Error [{}]: {}",
511            error.code().as_str(),
512            error.message().trim()
513        ),
514    }
515}
516
517#[cfg(test)]
518mod tests;