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 execute(cli.command).unwrap_or_else(|error| {
31 output::error::print_error(&error);
32
33 ExitCode::FAILURE
34 })
35}
36
37fn execute(command: Commands) -> Result<ExitCode, CliError> {
38 match command {
39 Commands::Init(args) => {
40 commands::init::execute(args)?;
41
42 Ok(ExitCode::SUCCESS)
43 }
44
45 Commands::Run(args) => {
46 let options = RunOptions::from(args);
47
48 if let Err(error) = options.validate() {
49 Cli::command()
50 .error(ErrorKind::InvalidValue, error.to_string())
51 .exit();
52 }
53
54 let cwd = env::current_dir().map_err(CliError::CurrentDirectory)?;
55
56 let project = Project::discover(&cwd)?;
57
58 let status = run::execute(&project, &options)?;
59
60 Ok(process_exit_code(status))
61 }
62 Commands::New(args) => {
63 commands::new::execute(&args)?;
64
65 Ok(ExitCode::SUCCESS)
66 }
67 Commands::Auth(args) => {
68 commands::auth::execute(&args)?;
69
70 Ok(ExitCode::SUCCESS)
71 }
72 Commands::Browser(args) => {
73 commands::browser::execute(&args)?;
74
75 Ok(ExitCode::SUCCESS)
76 }
77 Commands::Setup(args) => {
78 commands::setup::execute(&args)?;
79
80 Ok(ExitCode::SUCCESS)
81 }
82 Commands::Fetch(args) => {
83 let success = commands::fetch::execute(&args)?;
84
85 Ok(if success {
86 ExitCode::SUCCESS
87 } else {
88 ExitCode::FAILURE
89 })
90 }
91 }
92}
93
94fn process_exit_code(status: ExitStatus) -> ExitCode {
95 status
96 .code()
97 .and_then(|code| u8::try_from(code).ok())
98 .map_or(ExitCode::FAILURE, ExitCode::from)
99}