Skip to main content

wekan_cli/
lib.rs

1pub mod app;
2pub mod cli;
3pub mod client;
4pub mod command_result;
5pub mod commands;
6pub mod config;
7pub mod credentials;
8pub mod error;
9pub mod exit_code;
10pub mod input;
11pub mod output;
12pub mod redaction;
13
14use std::{
15    env,
16    ffi::OsString,
17    io::{self, Write},
18    process::ExitCode,
19};
20
21use clap::{CommandFactory, Parser, error::ErrorKind};
22
23use crate::{
24    app::App,
25    cli::Cli,
26    config::ServerSelection,
27    error::AppError,
28    output::{OutputFormat, render_error, write_success},
29};
30
31/// Parse the process arguments, execute one command, render its result, and
32/// return the stable process exit code.
33pub async fn run() -> ExitCode {
34    let args: Vec<OsString> = env::args_os().collect();
35    let requested_output = OutputFormat::detect_from_args(&args);
36
37    let cli = match Cli::try_parse_from(&args) {
38        Ok(cli) => cli,
39        Err(error)
40            if matches!(
41                error.kind(),
42                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
43            ) =>
44        {
45            let code = error.exit_code();
46            let _ = error.print();
47            return ExitCode::from(code as u8);
48        }
49        Err(error) => {
50            let app_error = AppError::invalid_input(error.to_string());
51            eprintln!("{}", render_error(requested_output, &app_error));
52            return app_error.exit_code().into();
53        }
54    };
55
56    let output_format = cli.output;
57    if output_format == OutputFormat::Raw && !cli.command.supports_raw_output() {
58        let error = AppError::invalid_input("--output raw is valid only with wekan api request");
59        eprintln!("{}", render_error(output_format, &error));
60        return error.exit_code().into();
61    }
62    let app = App::production_with_confirmation_interactivity(
63        ServerSelection::new(cli.server, cli.profile_name, cli.allow_insecure_http),
64        output_format != OutputFormat::Json,
65    );
66
67    match app.execute(cli.command).await {
68        Ok(success) => {
69            let mut stdout = io::stdout().lock();
70            let mut stderr = io::stderr().lock();
71            match write_success(output_format, success, &mut stdout, &mut stderr).await {
72                Ok(exit_code) => exit_code,
73                Err(error) => {
74                    let _ = writeln!(stderr, "{}", render_error(output_format, &error));
75                    error.exit_code().into()
76                }
77            }
78        }
79        Err(error) => {
80            eprintln!("{}", render_error(output_format, &error));
81            error.exit_code().into()
82        }
83    }
84}
85
86/// Return the generated Clap command for completion and contract tests.
87pub fn command() -> clap::Command {
88    Cli::command()
89}