1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[macro_use]
extern crate log;

pub mod commands;
pub mod error;
pub mod manifest;

use clap::Clap;
use colored::Colorize;
use commands::*;
use creator_tools::utils::{Config, Shell, Verbosity};
use manifest::*;
use std::path::PathBuf;

#[derive(Clap, Clone, Debug)]
#[clap(author, about, version)]
pub struct Opts {
    /// The current directory where to run all commands
    #[clap(short, long)]
    pub current_dir: Option<PathBuf>,
    /// A level of verbosity, and can be used multiple times
    #[clap(short, long, parse(from_occurrences))]
    pub verbose: u32,
    /// No output printed to stdout
    #[clap(short, long)]
    pub quiet: bool,

    #[clap(subcommand)]
    pub cmd: Commands,
}

pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let opts = Opts::parse();
    let verbosity = if opts.quiet {
        Verbosity::Quiet
    } else {
        // Vary the output based on how many times the user used the "verbose" flag.
        // Example: `creator -v -v -v' or 'creator -vvv' vs 'creator -v'
        match opts.verbose {
            0 => Verbosity::Normal,
            1 => Verbosity::Verbose,
            _ => {
                pretty_env_logger::formatted_builder()
                    .filter_level(log::LevelFilter::Trace)
                    .init();
                Verbosity::Verbose
            }
        }
    };
    let mut shell = Shell::new();
    shell.set_verbosity(verbosity);
    let current_dir = opts
        .current_dir
        .clone()
        .unwrap_or_else(|| std::env::current_dir().unwrap());
    let config = Config::new(shell, current_dir);
    opts.cmd.handle_command(&config)?;
    trace!("Command finished");
    Ok(())
}

pub fn handle_errors(run: impl FnOnce() -> std::result::Result<(), Box<dyn std::error::Error>>) {
    if let Err(error) = run() {
        eprintln!("{}: {}", "error".red().bold(), error);
        handle_error_source(error.source());
        std::process::exit(1);
    };
}

fn handle_error_source(source: Option<&(dyn std::error::Error + 'static)>) {
    if let Some(error) = source {
        eprintln!("{}: {}", "caused by".red().bold(), error);
        handle_error_source(error.source());
    }
}