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