rust/rhg/src/main.rs
author Antoine Cezar <antoine.cezar@octobus.net>
Mon, 17 Aug 2020 16:55:43 +0200
changeset 45440 a6a000ab135b
parent 45438 ed95ccc94333
child 45529 f17caf8f3fef
permissions -rw-r--r--
rhg: print error message when argument parsing fails Differential Revision: https://phab.mercurial-scm.org/D8956

use clap::App;
use clap::AppSettings;
use clap::SubCommand;

mod commands;
mod error;
mod exitcode;
mod ui;
use commands::Command;

fn main() {
    let mut app = App::new("rhg")
        .setting(AppSettings::AllowInvalidUtf8)
        .setting(AppSettings::SubcommandRequired)
        .setting(AppSettings::VersionlessSubcommands)
        .version("0.0.1")
        .subcommand(
            SubCommand::with_name("root").about(commands::root::HELP_TEXT),
        )
        .subcommand(
            SubCommand::with_name("files").about(commands::files::HELP_TEXT),
        );

    let matches = app.clone().get_matches_safe().unwrap_or_else(|err| {
        let _ = ui::Ui::new().writeln_stderr_str(&err.message);
        std::process::exit(exitcode::UNIMPLEMENTED_COMMAND)
    });

    let ui = ui::Ui::new();

    let command_result = match matches.subcommand_name() {
        Some(name) => match name {
            "root" => commands::root::RootCommand::new().run(&ui),
            "files" => commands::files::FilesCommand::new().run(&ui),
            _ => std::process::exit(exitcode::UNIMPLEMENTED_COMMAND),
        },
        _ => {
            match app.print_help() {
                Ok(_) => std::process::exit(exitcode::OK),
                Err(_) => std::process::exit(exitcode::ABORT),
            };
        }
    };

    match command_result {
        Ok(_) => std::process::exit(exitcode::OK),
        Err(e) => {
            let message = e.get_error_message_bytes();
            if let Some(msg) = message {
                match ui.write_stderr(&msg) {
                    Ok(_) => (),
                    Err(_) => std::process::exit(exitcode::ABORT),
                };
            };
            e.exit()
        }
    }
}