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::progress::LocalProgressStore;
13use crate::application::run::{self, RunOptions};
14use crate::project::Project;
15
16use crate::adapters::browser::{is_native_origin, run_native_host};
17use args::{Cli, Commands};
18use error::CliError;
19
20pub fn run() -> ExitCode {
21 if env::args_os()
22 .nth(1)
23 .and_then(|arg| arg.into_string().ok())
24 .is_some_and(|arg| is_native_origin(&arg))
25 {
26 return run_native_host();
27 }
28
29 let cli = Cli::parse();
30
31 execute(cli.command).unwrap_or_else(|error| {
32 output::error::print_error(&error);
33
34 ExitCode::FAILURE
35 })
36}
37
38fn execute(command: Commands) -> Result<ExitCode, CliError> {
39 match command {
40 Commands::Init(args) => {
41 commands::init::execute(args)?;
42
43 Ok(ExitCode::SUCCESS)
44 }
45
46 Commands::Run(args) => {
47 let options = RunOptions::from(args);
48
49 if let Err(error) = options.validate() {
50 Cli::command()
51 .error(ErrorKind::InvalidValue, error.to_string())
52 .exit();
53 }
54
55 let cwd = env::current_dir().map_err(CliError::CurrentDirectory)?;
56 let project = Project::discover(&cwd)?;
57 let execution = run::execute_with_report(&project, &options)?;
58
59 if let Some(report) = &execution.progress_report {
60 let store = LocalProgressStore::new(&project.root, project.config.project.language);
61
62 match store.record(report) {
63 Err(error) => output::error::print_progress_warning(&error),
64 Ok(()) if report.days.iter().any(|day| !day.parts.is_empty()) => {
65 if let Err(error) =
66 commands::progress::update_readme_after_run(&project, &store)
67 {
68 output::error::print_readme_warning(&error);
69 }
70 }
71 Ok(()) => {}
72 }
73 }
74
75 Ok(process_exit_code(execution.status))
76 }
77 Commands::New(args) => {
78 commands::new::execute(&args)?;
79
80 Ok(ExitCode::SUCCESS)
81 }
82 Commands::Auth(args) => {
83 commands::auth::execute(&args)?;
84
85 Ok(ExitCode::SUCCESS)
86 }
87 Commands::Browser(args) => {
88 commands::browser::execute(&args)?;
89
90 Ok(ExitCode::SUCCESS)
91 }
92 Commands::Setup(args) => {
93 commands::setup::execute(&args)?;
94
95 Ok(ExitCode::SUCCESS)
96 }
97 Commands::Fetch(args) => {
98 let success = commands::fetch::execute(&args)?;
99
100 Ok(if success {
101 ExitCode::SUCCESS
102 } else {
103 ExitCode::FAILURE
104 })
105 }
106 Commands::Progress(args) => {
107 commands::progress::execute(&args)?;
108
109 Ok(ExitCode::SUCCESS)
110 }
111 }
112}
113
114fn process_exit_code(status: ExitStatus) -> ExitCode {
115 status
116 .code()
117 .and_then(|code| u8::try_from(code).ok())
118 .map_or(ExitCode::FAILURE, ExitCode::from)
119}