Skip to main content

aoc_toolkit/cli/
mod.rs

1mod args;
2mod commands;
3mod error;
4
5pub mod output;
6
7use std::env;
8use std::process::{ExitCode, ExitStatus};
9
10use clap::{CommandFactory, Parser, error::ErrorKind};
11
12use crate::application::run::{self, RunOptions};
13use crate::project::Project;
14
15use crate::adapters::browser::{is_native_origin, run_native_host};
16use args::{Cli, Commands};
17use error::CliError;
18
19pub fn run() -> ExitCode {
20    if env::args_os()
21        .nth(1)
22        .and_then(|arg| arg.into_string().ok())
23        .is_some_and(|arg| is_native_origin(&arg))
24    {
25        return run_native_host();
26    }
27
28    let cli = Cli::parse();
29
30    match execute(cli.command) {
31        Ok(code) => code,
32        Err(error) => {
33            eprintln!("✗ {error}");
34            ExitCode::FAILURE
35        }
36    }
37}
38
39fn execute(command: Commands) -> Result<ExitCode, CliError> {
40    match command {
41        Commands::Init(args) => {
42            commands::init::execute(args)?;
43
44            Ok(ExitCode::SUCCESS)
45        }
46
47        Commands::Run(args) => {
48            let options = RunOptions::from(args);
49
50            if let Err(error) = options.validate() {
51                Cli::command()
52                    .error(ErrorKind::InvalidValue, error.to_string())
53                    .exit();
54            }
55
56            let cwd = env::current_dir().map_err(CliError::CurrentDirectory)?;
57
58            let project = Project::discover(&cwd)?;
59
60            let status = run::execute(&project, &options)?;
61
62            Ok(process_exit_code(status))
63        }
64        Commands::New(args) => {
65            commands::new::execute(&args)?;
66
67            Ok(ExitCode::SUCCESS)
68        }
69        Commands::Auth(args) => {
70            commands::auth::execute(&args)?;
71
72            Ok(ExitCode::SUCCESS)
73        }
74        Commands::Browser(args) => {
75            commands::browser::execute(&args)?;
76
77            Ok(ExitCode::SUCCESS)
78        }
79        Commands::Setup(args) => {
80            commands::setup::execute(&args)?;
81
82            Ok(ExitCode::SUCCESS)
83        }
84    }
85}
86
87fn process_exit_code(status: ExitStatus) -> ExitCode {
88    status
89        .code()
90        .and_then(|code| u8::try_from(code).ok())
91        .map_or(ExitCode::FAILURE, ExitCode::from)
92}