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::CardDependencies(data)) => {
121            dependencies::card_collection(data)
122        }
123        (OutputFormat::Json, CommandSuccess::CardDependencies(data)) => render_json_success(data),
124        (OutputFormat::Human, CommandSuccess::BoardDependencies(data)) => {
125            dependencies::board_collection(data)
126        }
127        (OutputFormat::Json, CommandSuccess::BoardDependencies(data)) => render_json_success(data),
128        (OutputFormat::Human, CommandSuccess::DependencyCreated(data)) => {
129            dependencies::created(data)
130        }
131        (OutputFormat::Json, CommandSuccess::DependencyCreated(data)) => render_json_success(data),
132        (OutputFormat::Human, CommandSuccess::DependencyUpdated(data)) => {
133            dependencies::updated(data)
134        }
135        (OutputFormat::Json, CommandSuccess::DependencyUpdated(data)) => render_json_success(data),
136        (OutputFormat::Human, CommandSuccess::DependencyDeleted(data)) => {
137            dependencies::deleted(data)
138        }
139        (OutputFormat::Json, CommandSuccess::DependencyDeleted(data)) => render_json_success(data),
140        (OutputFormat::Human, CommandSuccess::AttachmentList(data)) => attachments::list(data),
141        (OutputFormat::Json, CommandSuccess::AttachmentList(data)) => render_json_success(data),
142        (OutputFormat::Human, CommandSuccess::AttachmentShown(data)) => attachments::detail(data),
143        (OutputFormat::Json, CommandSuccess::AttachmentShown(data)) => render_json_success(data),
144        (OutputFormat::Human, CommandSuccess::AttachmentUploaded(data)) => {
145            attachments::detail(data)
146        }
147        (OutputFormat::Json, CommandSuccess::AttachmentUploaded(data)) => render_json_success(data),
148        (OutputFormat::Human, CommandSuccess::BackgroundUploaded(data)) => {
149            attachments::detail(data)
150        }
151        (OutputFormat::Json, CommandSuccess::BackgroundUploaded(data)) => render_json_success(data),
152        (OutputFormat::Human, CommandSuccess::AttachmentCopied(data)) => attachments::detail(data),
153        (OutputFormat::Json, CommandSuccess::AttachmentCopied(data)) => render_json_success(data),
154        (OutputFormat::Human, CommandSuccess::AttachmentMoved(data)) => attachments::detail(data),
155        (OutputFormat::Json, CommandSuccess::AttachmentMoved(data)) => render_json_success(data),
156        (OutputFormat::Human, CommandSuccess::AttachmentDeleted(data)) => attachments::detail(data),
157        (OutputFormat::Json, CommandSuccess::AttachmentDeleted(data)) => render_json_success(data),
158        (OutputFormat::Human, CommandSuccess::AttachmentDownloaded(data)) => {
159            attachments::detail(data)
160        }
161        (OutputFormat::Json, CommandSuccess::AttachmentDownloaded(data)) => {
162            render_json_success(data)
163        }
164        (_, CommandSuccess::ApiResponse(_)) => {
165            panic!("streaming API responses must be consumed by output::write_success")
166        }
167        (OutputFormat::Raw, CommandSuccess::Cancelled(_)) => String::new(),
168        (OutputFormat::Raw, _) => panic!("raw results must be consumed by output::write_success"),
169        (OutputFormat::Human, CommandSuccess::Cancelled(_)) => {
170            "Cancelled; no changes made.".to_owned()
171        }
172        (OutputFormat::Json, CommandSuccess::Cancelled(data)) => render_json_success(data),
173        (OutputFormat::Human, CommandSuccess::Registration(data)) => {
174            render_auth_success("Registered user", data)
175        }
176        (OutputFormat::Json, CommandSuccess::Registration(data)) => render_json_success(data),
177        (OutputFormat::Human, CommandSuccess::Login(data)) => {
178            render_auth_success("Logged in user", data)
179        }
180        (OutputFormat::Json, CommandSuccess::Login(data)) => render_json_success(data),
181        (OutputFormat::Human, CommandSuccess::Logout(data)) => render_logout(data),
182        (OutputFormat::Json, CommandSuccess::Logout(data)) => render_json_success(data),
183        (OutputFormat::Human, CommandSuccess::AuthStatus(data)) => render_auth_status(data),
184        (OutputFormat::Json, CommandSuccess::AuthStatus(data)) => render_json_success(data),
185        (OutputFormat::Human, CommandSuccess::UserCurrent(data))
186        | (OutputFormat::Human, CommandSuccess::UserShown(data))
187        | (OutputFormat::Human, CommandSuccess::UserUpdated(data)) => render_user_detail(data),
188        (OutputFormat::Json, CommandSuccess::UserCurrent(data))
189        | (OutputFormat::Json, CommandSuccess::UserShown(data))
190        | (OutputFormat::Json, CommandSuccess::UserUpdated(data)) => render_json_success(data),
191        (OutputFormat::Human, CommandSuccess::UserList(data)) => render_user_list(data),
192        (OutputFormat::Json, CommandSuccess::UserList(data)) => render_json_success(data),
193        (OutputFormat::Human, CommandSuccess::UserCards(data)) => render_user_cards(data),
194        (OutputFormat::Json, CommandSuccess::UserCards(data)) => render_json_success(data),
195        (OutputFormat::Human, CommandSuccess::UserCreated(data)) => render_user_created(data),
196        (OutputFormat::Json, CommandSuccess::UserCreated(data)) => render_json_success(data),
197        (OutputFormat::Human, CommandSuccess::UserBoards(data)) => render_user_boards(data),
198        (OutputFormat::Json, CommandSuccess::UserBoards(data)) => render_json_success(data),
199        (OutputFormat::Human, CommandSuccess::UserOwnershipTaken(data)) => {
200            render_user_ownership(data)
201        }
202        (OutputFormat::Json, CommandSuccess::UserOwnershipTaken(data)) => render_json_success(data),
203        (OutputFormat::Human, CommandSuccess::UserLoginChanged(data)) => {
204            render_user_login_change(data)
205        }
206        (OutputFormat::Json, CommandSuccess::UserLoginChanged(data)) => render_json_success(data),
207        (OutputFormat::Human, CommandSuccess::UserDeleted(data)) => render_user_deleted(data),
208        (OutputFormat::Json, CommandSuccess::UserDeleted(data)) => render_json_success(data),
209        (OutputFormat::Human, CommandSuccess::BoardList(data)) => render_board_list(data),
210        (OutputFormat::Json, CommandSuccess::BoardList(data)) => render_json_success(data),
211        (OutputFormat::Human, CommandSuccess::BoardCount(data)) => render_board_count(data),
212        (OutputFormat::Json, CommandSuccess::BoardCount(data)) => render_json_success(data),
213        (OutputFormat::Human, CommandSuccess::BoardShown(data)) => render_board_detail(data),
214        (OutputFormat::Json, CommandSuccess::BoardShown(data)) => render_json_success(data),
215        (OutputFormat::Human, CommandSuccess::BoardCreated(data)) => render_board_created(data),
216        (OutputFormat::Json, CommandSuccess::BoardCreated(data)) => render_json_success(data),
217        (OutputFormat::Human, CommandSuccess::BoardRenamed(data)) => render_board_renamed(data),
218        (OutputFormat::Json, CommandSuccess::BoardRenamed(data)) => render_json_success(data),
219        (OutputFormat::Human, CommandSuccess::BoardDeleted(data)) => render_board_deleted(data),
220        (OutputFormat::Json, CommandSuccess::BoardDeleted(data)) => render_json_success(data),
221        (OutputFormat::Human, CommandSuccess::ListCollection(data)) => render_list_collection(data),
222        (OutputFormat::Json, CommandSuccess::ListCollection(data)) => render_json_success(data),
223        (OutputFormat::Human, CommandSuccess::ListShown(data)) => render_list_detail(data),
224        (OutputFormat::Json, CommandSuccess::ListShown(data)) => render_json_success(data),
225        (OutputFormat::Human, CommandSuccess::ListCreated(data)) => render_list_created(data),
226        (OutputFormat::Json, CommandSuccess::ListCreated(data)) => render_json_success(data),
227        (OutputFormat::Human, CommandSuccess::ListUpdated(data)) => render_list_updated(data),
228        (OutputFormat::Json, CommandSuccess::ListUpdated(data)) => render_json_success(data),
229        (OutputFormat::Human, CommandSuccess::ListDeleted(data)) => render_list_deleted(data),
230        (OutputFormat::Json, CommandSuccess::ListDeleted(data)) => render_json_success(data),
231        (OutputFormat::Human, CommandSuccess::CardCollection(data)) => render_card_collection(data),
232        (OutputFormat::Json, CommandSuccess::CardCollection(data)) => render_json_success(data),
233        (OutputFormat::Human, CommandSuccess::CardShown(data)) => render_card_detail(data),
234        (OutputFormat::Json, CommandSuccess::CardShown(data)) => render_json_success(data),
235        (OutputFormat::Human, CommandSuccess::CardCreated(data)) => render_card_created(data),
236        (OutputFormat::Json, CommandSuccess::CardCreated(data)) => render_json_success(data),
237        (OutputFormat::Human, CommandSuccess::CardUpdated(data)) => render_card_updated(data),
238        (OutputFormat::Json, CommandSuccess::CardUpdated(data)) => render_json_success(data),
239        (OutputFormat::Human, CommandSuccess::CardArchived(data)) => render_card_archived(data),
240        (OutputFormat::Json, CommandSuccess::CardArchived(data)) => render_json_success(data),
241        (OutputFormat::Human, CommandSuccess::CardRestored(data)) => render_card_restored(data),
242        (OutputFormat::Json, CommandSuccess::CardRestored(data)) => render_json_success(data),
243        (OutputFormat::Human, CommandSuccess::CardDeleted(data)) => render_card_deleted(data),
244        (OutputFormat::Json, CommandSuccess::CardDeleted(data)) => render_json_success(data),
245        (OutputFormat::Human, CommandSuccess::ChecklistCollection(data)) => {
246            render_checklist_collection(data)
247        }
248        (OutputFormat::Json, CommandSuccess::ChecklistCollection(data)) => {
249            render_json_success(data)
250        }
251        (OutputFormat::Human, CommandSuccess::ChecklistShown(data)) => {
252            render_checklist_detail(data)
253        }
254        (OutputFormat::Json, CommandSuccess::ChecklistShown(data)) => render_json_success(data),
255        (OutputFormat::Human, CommandSuccess::ChecklistCreated(data)) => {
256            render_checklist_created(data)
257        }
258        (OutputFormat::Json, CommandSuccess::ChecklistCreated(data)) => render_json_success(data),
259        (OutputFormat::Human, CommandSuccess::ChecklistDeleted(data)) => {
260            render_checklist_deleted(data)
261        }
262        (OutputFormat::Json, CommandSuccess::ChecklistDeleted(data)) => render_json_success(data),
263        (OutputFormat::Human, CommandSuccess::ChecklistItemShown(data)) => {
264            render_checklist_item_detail(data)
265        }
266        (OutputFormat::Json, CommandSuccess::ChecklistItemShown(data)) => render_json_success(data),
267        (OutputFormat::Human, CommandSuccess::ChecklistItemCreated(data)) => {
268            render_checklist_item_created(data)
269        }
270        (OutputFormat::Json, CommandSuccess::ChecklistItemCreated(data)) => {
271            render_json_success(data)
272        }
273        (OutputFormat::Human, CommandSuccess::ChecklistItemUpdated(data)) => {
274            render_checklist_item_updated(data)
275        }
276        (OutputFormat::Json, CommandSuccess::ChecklistItemUpdated(data)) => {
277            render_json_success(data)
278        }
279        (OutputFormat::Human, CommandSuccess::ChecklistItemDeleted(data)) => {
280            render_checklist_item_deleted(data)
281        }
282        (OutputFormat::Json, CommandSuccess::ChecklistItemDeleted(data)) => {
283            render_json_success(data)
284        }
285        (OutputFormat::Human, CommandSuccess::CustomFieldCollection(data)) => {
286            custom_fields::collection(data)
287        }
288        (OutputFormat::Json, CommandSuccess::CustomFieldCollection(data)) => {
289            render_json_success(data)
290        }
291        (OutputFormat::Human, CommandSuccess::CustomFieldShown(data)) => {
292            custom_fields::detail(data)
293        }
294        (OutputFormat::Json, CommandSuccess::CustomFieldShown(data)) => render_json_success(data),
295        (OutputFormat::Human, CommandSuccess::CustomFieldCreated(data)) => {
296            custom_fields::created(data)
297        }
298        (OutputFormat::Json, CommandSuccess::CustomFieldCreated(data)) => render_json_success(data),
299        (OutputFormat::Human, CommandSuccess::CustomFieldUpdated(data)) => {
300            custom_fields::updated(data)
301        }
302        (OutputFormat::Json, CommandSuccess::CustomFieldUpdated(data)) => render_json_success(data),
303        (OutputFormat::Human, CommandSuccess::CustomFieldDeleted(data)) => {
304            custom_fields::deleted(data)
305        }
306        (OutputFormat::Json, CommandSuccess::CustomFieldDeleted(data)) => render_json_success(data),
307        (OutputFormat::Human, CommandSuccess::CustomFieldItemsCreated(data)) => {
308            custom_field_items::created(data)
309        }
310        (OutputFormat::Json, CommandSuccess::CustomFieldItemsCreated(data)) => {
311            render_json_success(data)
312        }
313        (OutputFormat::Human, CommandSuccess::CustomFieldItemUpdated(data)) => {
314            custom_field_items::updated(data)
315        }
316        (OutputFormat::Json, CommandSuccess::CustomFieldItemUpdated(data)) => {
317            render_json_success(data)
318        }
319        (OutputFormat::Human, CommandSuccess::CustomFieldItemDeleted(data)) => {
320            custom_field_items::deleted(data)
321        }
322        (OutputFormat::Json, CommandSuccess::CustomFieldItemDeleted(data)) => {
323            render_json_success(data)
324        }
325        (OutputFormat::Human, CommandSuccess::CardCustomFieldSet(data)) => {
326            cards::render_card_custom_field_set(data)
327        }
328        (OutputFormat::Json, CommandSuccess::CardCustomFieldSet(data)) => render_json_success(data),
329        (OutputFormat::Human, CommandSuccess::CardCustomFieldQuery(data)) => {
330            cards::render_card_custom_field_query(data)
331        }
332        (OutputFormat::Json, CommandSuccess::CardCustomFieldQuery(data)) => {
333            render_json_success(data)
334        }
335        (OutputFormat::Human, CommandSuccess::CommentCollection(data)) => {
336            render_comment_collection(data)
337        }
338        (OutputFormat::Json, CommandSuccess::CommentCollection(data)) => render_json_success(data),
339        (OutputFormat::Human, CommandSuccess::CommentShown(data)) => render_comment_detail(data),
340        (OutputFormat::Json, CommandSuccess::CommentShown(data)) => render_json_success(data),
341        (OutputFormat::Human, CommandSuccess::CommentCreated(data)) => render_comment_created(data),
342        (OutputFormat::Json, CommandSuccess::CommentCreated(data)) => render_json_success(data),
343        (OutputFormat::Human, CommandSuccess::CommentDeleted(data)) => render_comment_deleted(data),
344        (OutputFormat::Json, CommandSuccess::CommentDeleted(data)) => render_json_success(data),
345        (OutputFormat::Human, CommandSuccess::SwimlaneCollection(data)) => {
346            render_swimlane_collection(data)
347        }
348        (OutputFormat::Json, CommandSuccess::SwimlaneCollection(data)) => render_json_success(data),
349        (OutputFormat::Human, CommandSuccess::SwimlaneShown(data)) => render_swimlane_detail(data),
350        (OutputFormat::Json, CommandSuccess::SwimlaneShown(data)) => render_json_success(data),
351        (OutputFormat::Human, CommandSuccess::SwimlaneCreated(data)) => {
352            render_swimlane_created(data)
353        }
354        (OutputFormat::Json, CommandSuccess::SwimlaneCreated(data)) => render_json_success(data),
355        (OutputFormat::Human, CommandSuccess::SwimlaneUpdated(data)) => {
356            render_swimlane_updated(data)
357        }
358        (OutputFormat::Json, CommandSuccess::SwimlaneUpdated(data)) => render_json_success(data),
359        (OutputFormat::Human, CommandSuccess::SwimlaneDeleted(data)) => {
360            render_swimlane_deleted(data)
361        }
362        (OutputFormat::Json, CommandSuccess::SwimlaneDeleted(data)) => render_json_success(data),
363        (OutputFormat::Human, CommandSuccess::ProfileAdded(data)) => {
364            render_profile_item("Added profile", data)
365        }
366        (OutputFormat::Json, CommandSuccess::ProfileAdded(data))
367        | (OutputFormat::Json, CommandSuccess::ProfileShown(data))
368        | (OutputFormat::Json, CommandSuccess::ProfileUsed(data))
369        | (OutputFormat::Json, CommandSuccess::ProfileUpdated(data)) => {
370            serde_json::to_string(&SuccessEnvelope { ok: true, data })
371                .expect("profile success is always serializable")
372        }
373        (OutputFormat::Human, CommandSuccess::ProfileList(data)) => render_profile_list(data),
374        (OutputFormat::Json, CommandSuccess::ProfileList(data)) => {
375            serde_json::to_string(&SuccessEnvelope { ok: true, data })
376                .expect("profile list success is always serializable")
377        }
378        (OutputFormat::Human, CommandSuccess::ProfileShown(data)) => {
379            render_profile_item("Profile", data)
380        }
381        (OutputFormat::Human, CommandSuccess::ProfileUsed(data)) => {
382            render_profile_item("Using profile", data)
383        }
384        (OutputFormat::Human, CommandSuccess::ProfileUpdated(data)) => {
385            render_profile_item("Updated profile", data)
386        }
387        (OutputFormat::Human, CommandSuccess::ProfileRemoved(data)) => render_profile_removed(data),
388        (OutputFormat::Json, CommandSuccess::ProfileRemoved(data)) => {
389            serde_json::to_string(&SuccessEnvelope { ok: true, data })
390                .expect("profile removal success is always serializable")
391        }
392    }
393}
394
395pub async fn write_success(
396    format: OutputFormat,
397    success: CommandSuccess,
398    stdout: &mut dyn Write,
399    stderr: &mut dyn Write,
400) -> Result<ExitCode, AppError> {
401    if let CommandSuccess::ApiResponse(response) = success {
402        return raw::write_response(format, response, stdout, stderr).await;
403    }
404    if format == OutputFormat::Raw {
405        if let CommandSuccess::AttachmentDownloaded(data) = &success {
406            let bytes = data.bytes.as_deref().ok_or_else(|| {
407                AppError::invalid_input("raw attachment output requires --destination -")
408            })?;
409            stdout
410                .write_all(bytes)
411                .and_then(|()| stdout.flush())
412                .map_err(output_write_error)?;
413            return Ok(ExitCode::SUCCESS);
414        }
415    }
416    let rendered = render_success(format, &success);
417    if !rendered.is_empty() {
418        let written = writeln!(stdout, "{rendered}").and_then(|()| {
419            if matches!(&success, CommandSuccess::AttachmentDownloaded(data) if data.file_saved) {
420                stdout.flush()
421            } else {
422                Ok(())
423            }
424        });
425        written.map_err(|e| {
426            let error = output_write_error(e);
427            if let CommandSuccess::AttachmentDownloaded(data) = &success {
428                if data.file_saved {
429                    return error.with_details(crate::error::ErrorDetails {
430                        file_saved: Some(true),
431                        destination: Some(data.destination.clone()),
432                        ..crate::error::ErrorDetails::default()
433                    });
434                }
435            }
436            error
437        })?;
438    }
439    Ok(ExitCode::SUCCESS)
440}
441pub(crate) fn output_write_error(error: std::io::Error) -> AppError {
442    AppError::new(
443        ErrorCode::InternalError,
444        format!("could not write command output: {error}"),
445        StableExitCode::Transport,
446    )
447}
448
449pub(crate) fn render_json_success<T: Serialize>(data: &T) -> String {
450    serde_json::to_string(&SuccessEnvelope { ok: true, data })
451        .expect("command success is always serializable")
452}
453
454pub fn render_error(format: OutputFormat, error: &AppError) -> String {
455    match format {
456        OutputFormat::Human => {
457            let mut rendered = format!(
458                "Error [{}]: {}",
459                error.code().as_str(),
460                error.message().trim()
461            );
462            if let Some(response) = &error.details().response {
463                rendered.push('\n');
464                rendered.push_str(&render_api_response_human(response));
465            }
466            if error.details().file_saved == Some(true) {
467                if let Some(destination) = &error.details().destination {
468                    rendered.push_str(&format!(
469                        "\nDownload saved to `{}`; completion output failed.",
470                        formatting::escape_terminal_controls(destination)
471                    ));
472                }
473            }
474            rendered
475        }
476        OutputFormat::Json => serde_json::to_string(&ErrorEnvelope {
477            ok: false,
478            error: ErrorBody {
479                code: error.code().as_str(),
480                message: error.message(),
481                details: error.details(),
482            },
483        })
484        .expect("application errors are always serializable"),
485        OutputFormat::Raw => format!(
486            "Error [{}]: {}",
487            error.code().as_str(),
488            error.message().trim()
489        ),
490    }
491}
492
493#[cfg(test)]
494mod tests;