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 let Err(error) = cli.command.validate_output(output_format) {
58        eprintln!("{}", render_error(output_format, &error));
59        return error.exit_code().into();
60    }
61    let app = App::production_with_confirmation_interactivity(
62        ServerSelection::new(cli.server, cli.profile_name, cli.allow_insecure_http),
63        output_format != OutputFormat::Json,
64    );
65
66    match app.execute(cli.command).await {
67        Ok(success) => {
68            let mut stdout = io::stdout().lock();
69            let mut stderr = io::stderr().lock();
70            match write_success(output_format, success, &mut stdout, &mut stderr).await {
71                Ok(exit_code) => exit_code,
72                Err(error) => {
73                    let _ = writeln!(stderr, "{}", render_error(output_format, &error));
74                    error.exit_code().into()
75                }
76            }
77        }
78        Err(error) => {
79            eprintln!("{}", render_error(output_format, &error));
80            error.exit_code().into()
81        }
82    }
83}
84
85/// Return the generated Clap command for completion and contract tests.
86pub fn command() -> clap::Command {
87    Cli::command()
88}