Skip to main content

kasl/commands/
mod.rs

1//! Command-line interface commands for kasl application.
2//!
3//! Contains all CLI command implementations for task management, activity monitoring,
4//! reporting, and system configuration.
5//!
6//! ## Features
7//!
8//! - **Core Commands**: Task management, activity monitoring, reporting, export
9//! - **Utility Commands**: Configuration, summaries, pauses, adjustments, updates
10//! - **Advanced Commands**: Templates, tags, database migrations
11//!
12//! ## Usage
13//!
14//! ```bash
15//! kasl watch                    # Start activity monitoring
16//! kasl task --name "Review code" # Create a new task
17//! kasl report                   # Generate today's report
18//! kasl export tasks --format csv # Export tasks to CSV
19//! ```
20
21pub mod breaks;
22pub mod autostart;
23pub mod export;
24pub mod init;
25pub mod migrations;
26pub mod pauses;
27pub mod report;
28pub mod sum;
29pub mod tag;
30pub mod task;
31pub mod template;
32pub mod update;
33pub mod watch;
34
35use crate::{db::workdays::Workdays, libs::messages::types::Message, msg_info};
36use anyhow::Result;
37use chrono::Local;
38use clap::{Parser, Subcommand};
39
40/// Defines the main subcommands that the application can execute.
41///
42/// Each variant corresponds to a specific command with its own argument structure.
43/// Commands are organized by functionality and frequency of use.
44#[derive(Debug, Subcommand)]
45enum Commands {
46    /// Manage autostart configuration for system boot
47    ///
48    /// Controls whether kasl automatically starts monitoring when the system boots.
49    /// Supports both system-level and user-level autostart on Windows.
50    #[command(about = "Manage autostart on system boot")]
51    Autostart(autostart::AutostartArgs),
52
53    /// Initialize application configuration interactively
54    ///
55    /// Guides the user through setting up API credentials, monitor settings,
56    /// and other configuration options required for kasl to function properly.
57    #[command(about = "Configuration initialization")]
58    Init(init::InitArgs),
59
60    /// Comprehensive task management command
61    ///
62    /// Handles all task-related operations including creation, editing, deletion,
63    /// viewing, and integration with external services like GitLab and Jira.
64    #[command(about = "Create task")]
65    Task(task::TaskArgs),
66
67    /// Manually end the current workday
68    ///
69    /// Records the end timestamp for today's work session. Typically used
70    /// when the automatic monitoring needs to be manually finalized.
71    #[command(about = "Write end timestamp to database")]
72    End,
73
74    /// Display monthly working hours summary
75    ///
76    /// Shows a comprehensive overview of work hours, productivity metrics,
77    /// and daily breakdowns for the current month.
78    #[command(about = "Get summary")]
79    Sum(sum::SumArgs),
80
81    /// Update application to the latest version
82    ///
83    /// Checks GitHub releases for newer versions and automatically downloads
84    /// and installs updates if available.
85    #[command(about = "Update the application to the latest version")]
86    Update,
87
88    /// Generate and optionally submit work reports
89    ///
90    /// Creates detailed daily reports with work intervals, tasks, and productivity
91    /// metrics. Can automatically submit reports to configured APIs.
92    #[command(about = "Prepare a report")]
93    Report(report::ReportArgs),
94
95    /// Export application data to external formats
96    ///
97    /// Supports exporting tasks, reports, and summaries to CSV, JSON, and Excel
98    /// formats for external analysis or backup purposes.
99    #[command(about = "Export data to various formats")]
100    Export(export::ExportArgs),
101
102    /// Manage reusable task templates
103    ///
104    /// Create, edit, and use templates for frequently created tasks to
105    /// streamline task creation workflow.
106    #[command(about = "Manage task templates")]
107    Template(template::TemplateArgs),
108
109    /// Organize tasks with custom tags
110    ///
111    /// Create and manage tags to categorize and filter tasks by project,
112    /// priority, or any custom criteria.
113    #[command(about = "Manage task tags")]
114    Tag(tag::TagArgs),
115
116    /// Background activity monitoring daemon
117    ///
118    /// Monitors user input activity to automatically detect work sessions,
119    /// breaks, and workday boundaries. Can run as a background service.
120    #[command(about = "Watch user activity in the background to record pauses")]
121    Watch(watch::WatchArgs),
122
123    /// Display recorded breaks and pauses
124    ///
125    /// Shows all detected pauses for a specific date with duration calculations
126    /// and filtering options.
127    #[command(about = "Display pauses for a given date")]
128    Pauses(pauses::PausesArgs),
129
130    /// Add manual breaks for productivity optimization
131    ///
132    /// Create strategically placed breaks to improve productivity metrics
133    /// and meet minimum thresholds for report submission.
134    #[command(about = "Add manual breaks for productivity optimization")]
135    Breaks(breaks::BreaksArgs),
136
137    /// Database migration management utilities (debug builds only)
138    ///
139    /// Provides tools for database schema management, migration history,
140    /// and rollback operations. Available only in debug builds for safety.
141    #[cfg(debug_assertions)]
142    #[command(about = "Database migration management")]
143    Migrations(migrations::MigrationsArgs),
144}
145
146/// The main CLI structure that parses command-line arguments.
147///
148/// Uses `clap` to define the application's interface and delegates
149/// command execution to the appropriate subcommand module. The CLI
150/// requires at least one subcommand to be specified.
151///
152/// # Examples
153///
154/// ```bash
155/// # Display help
156/// kasl --help
157///
158/// # Run a specific command
159/// kasl task --name "New task"
160/// ```
161#[derive(Debug, Parser)]
162#[command(author, version, about, long_about = None)]
163#[command(arg_required_else_help(true))]
164pub struct Cli {
165    #[command(subcommand)]
166    command: Commands,
167}
168
169impl Cli {
170    /// Parses command-line arguments and executes the corresponding command.
171    ///
172    /// This is the main entry point for the CLI logic. It handles command
173    /// routing and provides centralized error handling for all commands.
174    ///
175    /// # Returns
176    ///
177    /// Returns `Ok(())` on successful command execution, or an error if
178    /// the command fails or invalid arguments are provided.
179    ///
180    /// # Examples
181    ///
182    /// ```rust,no_run
183    /// use kasl::commands::Cli;
184    ///
185    /// #[tokio::main]
186    /// async fn main() -> anyhow::Result<()> {
187    ///     Cli::menu().await
188    /// }
189    /// ```
190    pub async fn menu() -> Result<()> {
191        let cli = Self::parse();
192
193        match cli.command {
194            Commands::Autostart(args) => autostart::cmd(args),
195            Commands::Init(args) => init::cmd(args),
196            Commands::Task(args) => task::cmd(args).await,
197            Commands::End => {
198                // Manually end the current workday
199                Workdays::new()?.insert_end(Local::now().date_naive())?;
200                msg_info!(Message::WorkdayEnded);
201                Ok(())
202            }
203            Commands::Sum(args) => sum::cmd(args).await,
204            Commands::Report(args) => report::cmd(args).await,
205            Commands::Export(args) => export::cmd(args).await,
206            Commands::Template(args) => template::cmd(args),
207            Commands::Tag(args) => tag::cmd(args).await,
208            Commands::Update => update::cmd().await,
209            Commands::Watch(args) => watch::cmd(args).await,
210            Commands::Pauses(args) => pauses::cmd(args).await,
211            Commands::Breaks(args) => breaks::cmd(args).await,
212
213            // Database migrations only available in debug builds
214            #[cfg(debug_assertions)]
215            Commands::Migrations(args) => migrations::cmd(args),
216        }
217    }
218}