Skip to main content

carch_cli/
args.rs

1use crate::commands;
2use crate::state::{clear_favorite_theme, load_favorite_theme, save_favorite_theme};
3use carch_core::error::{CarchError, Result};
4use carch_core::{VALID_THEMES, is_valid_theme, version};
5use clap::builder::styling::{AnsiColor, Style};
6use clap::{ArgAction, Parser, Subcommand};
7use env_logger::{Builder, Target};
8use log::info;
9use std::env;
10use std::fs::{self, OpenOptions};
11use std::path::PathBuf;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14fn timestamped_log_filename() -> String {
15    let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
16
17    let days = (secs / 86400) as i64 + 719468;
18    let era = days.div_euclid(146097);
19    let doe = (days - era * 146097) as u64;
20    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
21    let year_era = yoe as i64 + era * 400;
22    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
23    let mp = (5 * doy + 2) / 153;
24    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
25    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
26    let year = (year_era + if month <= 2 { 1 } else { 0 }) as u32;
27
28    let tod = secs % 86400;
29    let hour = (tod / 3600) as u32;
30    let minute = ((tod % 3600) / 60) as u32;
31    let second = (tod % 60) as u32;
32
33    format!("carch-{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}.log")
34}
35
36fn styles() -> clap::builder::Styles {
37    clap::builder::Styles::styled()
38        .header(Style::new().fg_color(Some(AnsiColor::Green.into())).bold())
39        .usage(Style::new().fg_color(Some(AnsiColor::Green.into())).bold())
40        .literal(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
41        .placeholder(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
42}
43
44#[derive(Parser)]
45#[command(author, about, long_about = None, styles = styles())]
46pub struct Cli {
47    #[command(subcommand)]
48    pub command:          Option<Commands>,
49    #[arg(short = 'v', long = "version", action = ArgAction::SetTrue, help = "Print version information")]
50    version:              bool,
51    #[arg(short = 'c', long, global = true, help = "Set theme to Catppuccin Mocha")]
52    pub catppuccin_mocha: bool,
53    #[arg(short = 'd', long, global = true, help = "Set theme to Dracula")]
54    pub dracula:          bool,
55    #[arg(short = 'g', long, global = true, help = "Set theme to Gruvbox")]
56    pub gruvbox:          bool,
57    #[arg(short = 'n', long, global = true, help = "Set theme to Nord")]
58    pub nord:             bool,
59    #[arg(short = 'r', long, global = true, help = "Set theme to Rosé Pine")]
60    pub rose_pine:        bool,
61    /// Save the given theme as favorite and exit.
62    #[arg(long, global = true, value_name = "THEME")]
63    pub fav:              Option<String>,
64    /// Clear the saved favorite theme.
65    #[arg(long, global = true, conflicts_with = "fav")]
66    pub unfav:            bool,
67}
68
69#[derive(Subcommand)]
70pub enum Commands {
71    #[command(about = "Check for updates")]
72    CheckUpdate,
73    #[command(about = "Update the application")]
74    Update,
75    #[command(about = "Uninstall the application")]
76    Uninstall,
77}
78
79#[derive(Clone, Default)]
80pub struct Settings {
81    pub log_mode:     bool,
82    pub theme:        String,
83    pub theme_locked: bool,
84}
85
86pub fn parse_args() -> Result<()> {
87    let cli = Cli::parse();
88
89    if cli.version {
90        println!("{}", version::get_current_version());
91        return Ok(());
92    }
93
94    if let Some(theme) = cli.fav.as_deref() {
95        if !is_valid_theme(theme) {
96            return Err(CarchError::Command(format!(
97                "Unknown theme '{theme}'. Valid themes: {}",
98                VALID_THEMES.join(", ")
99            )));
100        }
101        return save_favorite_theme(theme).map(|()| {
102            println!("Favorite theme set to '{theme}'. It will be used on future launches.");
103        });
104    }
105    if cli.unfav {
106        match clear_favorite_theme() {
107            Ok(true) => println!("Favorite theme cleared."),
108            Ok(false) => println!("No favorite theme was set."),
109            Err(e) => return Err(e),
110        }
111        return Ok(());
112    }
113
114    let mut settings = Settings { log_mode: true, ..Default::default() };
115
116    let explicit_theme =
117        cli.catppuccin_mocha || cli.dracula || cli.gruvbox || cli.nord || cli.rose_pine;
118
119    settings.theme = if cli.catppuccin_mocha {
120        "catppuccin-mocha".to_string()
121    } else if cli.dracula {
122        "dracula".to_string()
123    } else if cli.gruvbox {
124        "gruvbox".to_string()
125    } else if cli.nord {
126        "nord".to_string()
127    } else if cli.rose_pine {
128        "rose-pine".to_string()
129    } else if let Some(fav) = load_favorite_theme() {
130        // Saved favorite is locked so `t` can't overwrite it.
131        settings.theme_locked = true;
132        fav
133    } else {
134        "catppuccin-mocha".to_string()
135    };
136
137    if explicit_theme {
138        settings.theme_locked = true;
139    }
140
141    match cli.command {
142        Some(Commands::CheckUpdate) => {
143            info!("Checking for updates");
144            commands::check_for_updates()
145        }
146        Some(Commands::Update) => {
147            info!("Running update process");
148            commands::update()
149        }
150        Some(Commands::Uninstall) => {
151            info!("Running uninstall process");
152            commands::uninstall()
153        }
154        None => {
155            let home_dir = env::var("HOME").map_err(|_| CarchError::HomeDirNotFound)?;
156            let log_dir = PathBuf::from(home_dir).join(".config/carch");
157            fs::create_dir_all(&log_dir)?;
158            let log_file = log_dir.join(timestamped_log_filename());
159
160            let file =
161                OpenOptions::new().create(true).write(true).truncate(true).open(&log_file)?;
162
163            Builder::new()
164                .target(Target::Pipe(Box::new(file)))
165                .filter(None, log::LevelFilter::Info)
166                .init();
167            info!("Carch TUI started");
168
169            let result = crate::run_tui(settings);
170
171            println!("Log saved: {}", log_file.display());
172
173            result
174        }
175    }
176}