Skip to main content

kasl/commands/
init.rs

1//! Application configuration initialization command.
2//!
3//! Provides an interactive setup wizard that guides users through configuring kasl for first-time use.
4//!
5//! ## Usage
6//!
7//! ```bash
8//! # Run interactive setup wizard
9//! kasl setup
10//!
11//! # Reset configuration (remove existing settings)
12//! kasl setup --delete
13//! ```
14
15use crate::{
16    libs::{config::Config, daemon, messages::Message},
17    msg_info, msg_success, msg_warning,
18};
19use anyhow::Result;
20use clap::Args;
21
22/// Command-line arguments for the setup command.
23///
24/// The setup command supports an optional `--delete` flag for removing
25/// existing configuration, which can be useful for testing or troubleshooting.
26#[derive(Debug, Args)]
27pub struct SetupArgs {
28    /// Remove existing configuration instead of creating new one
29    ///
30    /// When specified, this flag will delete the current configuration file
31    /// and global PATH settings, effectively resetting the application to
32    /// its initial state.
33    #[arg(short, long)]
34    delete: bool,
35}
36
37/// Executes the setup command.
38///
39/// Handles configuration setup with interactive wizard for first-time setup,
40/// or configuration removal when `--delete` is used.
41///
42pub fn cmd(setup_args: SetupArgs) -> Result<()> {
43    // Check if watcher is currently running before making changes
44    let watcher_was_running = daemon::is_running();
45    if watcher_was_running {
46        msg_info!(Message::WatcherStoppingForConfig);
47        daemon::stop()?;
48    }
49
50    // Set up global application PATH configuration
51    // This ensures the 'kasl' command is available system-wide
52    match Config::set_app_global() {
53        Ok(()) => {
54            msg_success!(Message::PathConfigured);
55        }
56        Err(e) => {
57            msg_warning!(Message::PathConfigWarning { error: e.to_string() });
58        }
59    }
60
61    // Handle deletion mode - exit early after cleanup
62    if setup_args.delete {
63        // Don't restart watcher after deleting configuration
64        msg_info!(Message::ConfigDeleted);
65        return Ok(());
66    }
67
68    // Run interactive configuration wizard
69    // This will prompt the user to select and configure various modules
70    Config::init()?.save()?;
71
72    // Confirm successful configuration
73    msg_success!(Message::ConfigSaved);
74
75    // Restart watcher if it was running before configuration changes
76    if watcher_was_running {
77        msg_info!(Message::WatcherRestartingAfterConfig);
78        match daemon::spawn() {
79            Ok(()) => {
80                msg_success!(Message::WatcherRestarted);
81            }
82            Err(e) => {
83                msg_warning!(Message::WatcherRestartFailed { error: e.to_string() });
84            }
85        }
86    }
87
88    Ok(())
89}