🎨 style(cli): apply rustfmt formatting standards to CLI modules

- Apply cargo fmt to ensure consistent code formatting across CLI modules
- Fix trailing whitespace in documentation comments
- Optimize comment formatting and indentation
- All clippy checks pass with no warnings
- Documentation generates cleanly with strict nightly flags
- All tests continue to pass after formatting changes
This commit is contained in:
Jeremiah Russell
2025-10-20 15:35:57 +01:00
committed by Jeremiah Russell
parent 97947033ce
commit 3979379795
4 changed files with 224 additions and 224 deletions

View File

@@ -43,32 +43,32 @@ use clap::Parser;
use cull_gmail::{Error, GmailClient}; use cull_gmail::{Error, GmailClient};
/// Command-line interface for Gmail label inspection and display. /// Command-line interface for Gmail label inspection and display.
/// ///
/// This structure represents the `labels` subcommand, which provides functionality /// This structure represents the `labels` subcommand, which provides functionality
/// to list and inspect all Gmail labels available in the user's account. The command /// to list and inspect all Gmail labels available in the user's account. The command
/// requires no additional arguments and displays comprehensive label information. /// requires no additional arguments and displays comprehensive label information.
/// ///
/// # Features /// # Features
/// ///
/// - **Complete label listing**: Shows all labels including system and user-created labels /// - **Complete label listing**: Shows all labels including system and user-created labels
/// - **ID mapping**: Displays both human-readable names and internal Gmail IDs /// - **ID mapping**: Displays both human-readable names and internal Gmail IDs
/// - **Simple usage**: No configuration or arguments required /// - **Simple usage**: No configuration or arguments required
/// - **Authentication handling**: Automatic OAuth2 authentication through GmailClient /// - **Authentication handling**: Automatic OAuth2 authentication through GmailClient
/// ///
/// # Usage Context /// # Usage Context
/// ///
/// This command is typically used: /// This command is typically used:
/// 1. **Before creating queries**: To understand available labels for message filtering /// 1. **Before creating queries**: To understand available labels for message filtering
/// 2. **Before configuring rules**: To verify target labels exist /// 2. **Before configuring rules**: To verify target labels exist
/// 3. **For debugging**: To inspect label structure and IDs /// 3. **For debugging**: To inspect label structure and IDs
/// 4. **For exploration**: To understand Gmail organization structure /// 4. **For exploration**: To understand Gmail organization structure
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust,no_run /// ```rust,no_run
/// use cull_gmail::cli::labels_cli::LabelsCli; /// use cull_gmail::cli::labels_cli::LabelsCli;
/// use cull_gmail::GmailClient; /// use cull_gmail::GmailClient;
/// ///
/// # async fn example(client: GmailClient) -> Result<(), cull_gmail::Error> { /// # async fn example(client: GmailClient) -> Result<(), cull_gmail::Error> {
/// let labels_cli = LabelsCli {}; /// let labels_cli = LabelsCli {};
/// labels_cli.run(client).await?; /// labels_cli.run(client).await?;
@@ -80,42 +80,42 @@ pub struct LabelsCli {}
impl LabelsCli { impl LabelsCli {
/// Executes the labels command to display Gmail label information. /// Executes the labels command to display Gmail label information.
/// ///
/// This method coordinates the label inspection workflow by utilizing the /// This method coordinates the label inspection workflow by utilizing the
/// Gmail client to retrieve and display all available labels in the user's account. /// Gmail client to retrieve and display all available labels in the user's account.
/// The output includes both system labels (like INBOX, SENT) and user-created labels. /// The output includes both system labels (like INBOX, SENT) and user-created labels.
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `client` - Authenticated Gmail client for API communication /// * `client` - Authenticated Gmail client for API communication
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<(), Error>` indicating success or failure of the operation. /// Returns `Result<(), Error>` indicating success or failure of the operation.
/// ///
/// # Operation Details /// # Operation Details
/// ///
/// The function performs the following steps: /// The function performs the following steps:
/// 1. **Label Retrieval**: Fetches all labels from the Gmail API /// 1. **Label Retrieval**: Fetches all labels from the Gmail API
/// 2. **Format Processing**: Organizes labels for display /// 2. **Format Processing**: Organizes labels for display
/// 3. **Display Output**: Shows labels with names and IDs /// 3. **Display Output**: Shows labels with names and IDs
/// ///
/// # Output Format /// # Output Format
/// ///
/// Labels are displayed in the format: /// Labels are displayed in the format:
/// ```text /// ```text
/// <Label Name>: <Label ID> /// <Label Name>: <Label ID>
/// ``` /// ```
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// Possible errors include: /// Possible errors include:
/// - **Authentication failures**: OAuth2 token issues or expired credentials /// - **Authentication failures**: OAuth2 token issues or expired credentials
/// - **API communication errors**: Network issues or Gmail API unavailability /// - **API communication errors**: Network issues or Gmail API unavailability
/// - **Permission errors**: Insufficient OAuth2 scopes for label access /// - **Permission errors**: Insufficient OAuth2 scopes for label access
/// ///
/// # Side Effects /// # Side Effects
/// ///
/// This function produces output to stdout showing the label information. /// This function produces output to stdout showing the label information.
/// No Gmail account modifications are performed. /// No Gmail account modifications are performed.
pub async fn run(&self, client: GmailClient) -> Result<(), Error> { pub async fn run(&self, client: GmailClient) -> Result<(), Error> {

View File

@@ -46,13 +46,13 @@
//! ```toml //! ```toml
//! # OAuth2 credential file (required) //! # OAuth2 credential file (required)
//! credential_file = "client_secret.json" //! credential_file = "client_secret.json"
//! //!
//! # Configuration root directory //! # Configuration root directory
//! config_root = "h:.cull-gmail" //! config_root = "h:.cull-gmail"
//! //!
//! # Rules configuration file //! # Rules configuration file
//! rules = "rules.toml" //! rules = "rules.toml"
//! //!
//! # Default execution mode (false = dry-run, true = execute) //! # Default execution mode (false = dry-run, true = execute)
//! execute = false //! execute = false
//! ``` //! ```
@@ -75,7 +75,7 @@
//! ```bash //! ```bash
//! # List recent messages //! # List recent messages
//! cull-gmail messages -m 10 list //! cull-gmail messages -m 10 list
//! //!
//! # Find old promotional emails //! # Find old promotional emails
//! cull-gmail messages -Q "label:promotions older_than:1y" list //! cull-gmail messages -Q "label:promotions older_than:1y" list
//! ``` //! ```
@@ -84,7 +84,7 @@
//! ```bash //! ```bash
//! # Preview rule execution (dry-run) //! # Preview rule execution (dry-run)
//! cull-gmail rules run //! cull-gmail rules run
//! //!
//! # Execute rules for real //! # Execute rules for real
//! cull-gmail rules run --execute //! cull-gmail rules run --execute
//! ``` //! ```
@@ -124,18 +124,18 @@ use messages_cli::MessagesCli;
use rules_cli::RulesCli; use rules_cli::RulesCli;
/// Main CLI application structure defining global options and subcommands. /// Main CLI application structure defining global options and subcommands.
/// ///
/// This struct represents the root of the command-line interface, providing /// This struct represents the root of the command-line interface, providing
/// global configuration options and dispatching to specific subcommands for /// global configuration options and dispatching to specific subcommands for
/// labels, messages, and rules management. /// labels, messages, and rules management.
/// ///
/// # Global Options /// # Global Options
/// ///
/// - **Logging**: Configurable verbosity levels for operation visibility /// - **Logging**: Configurable verbosity levels for operation visibility
/// - **Subcommands**: Optional command selection (defaults to rule execution) /// - **Subcommands**: Optional command selection (defaults to rule execution)
/// ///
/// # Default Behavior /// # Default Behavior
/// ///
/// When no subcommand is provided, the CLI executes the default rule processing /// When no subcommand is provided, the CLI executes the default rule processing
/// workflow, loading rules from the configuration file and executing them /// workflow, loading rules from the configuration file and executing them
/// according to the current execution mode (dry-run or live). /// according to the current execution mode (dry-run or live).
@@ -143,52 +143,52 @@ use rules_cli::RulesCli;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// Logging verbosity control. /// Logging verbosity control.
/// ///
/// Use `-q` for quiet (errors only), default for info level, /// Use `-q` for quiet (errors only), default for info level,
/// `-v` for debug level, `-vv` for trace level. /// `-v` for debug level, `-vv` for trace level.
#[clap(flatten)] #[clap(flatten)]
logging: clap_verbosity_flag::Verbosity, logging: clap_verbosity_flag::Verbosity,
/// Optional subcommand selection. /// Optional subcommand selection.
/// ///
/// If not provided, the CLI will execute the default rule processing workflow. /// If not provided, the CLI will execute the default rule processing workflow.
#[command(subcommand)] #[command(subcommand)]
sub_command: Option<SubCmds>, sub_command: Option<SubCmds>,
} }
/// Available CLI subcommands for Gmail message management. /// Available CLI subcommands for Gmail message management.
/// ///
/// Each subcommand provides specialized functionality for different aspects /// Each subcommand provides specialized functionality for different aspects
/// of Gmail message lifecycle management, from inspection to automated processing. /// of Gmail message lifecycle management, from inspection to automated processing.
/// ///
/// # Command Categories /// # Command Categories
/// ///
/// - **Messages**: Direct message querying, filtering, and batch operations /// - **Messages**: Direct message querying, filtering, and batch operations
/// - **Labels**: Gmail label inspection and management /// - **Labels**: Gmail label inspection and management
/// - **Rules**: Automated message lifecycle rule configuration and execution /// - **Rules**: Automated message lifecycle rule configuration and execution
/// ///
/// # Display Order /// # Display Order
/// ///
/// Commands are ordered by typical usage workflow: inspect labels first, /// Commands are ordered by typical usage workflow: inspect labels first,
/// then query specific messages, and finally configure automated rules. /// then query specific messages, and finally configure automated rules.
#[derive(Subcommand, Debug)] #[derive(Subcommand, Debug)]
enum SubCmds { enum SubCmds {
/// Query, filter, and perform batch operations on Gmail messages. /// Query, filter, and perform batch operations on Gmail messages.
/// ///
/// Supports advanced Gmail query syntax, label filtering, and batch actions /// Supports advanced Gmail query syntax, label filtering, and batch actions
/// including trash and permanent deletion with safety controls. /// including trash and permanent deletion with safety controls.
#[clap(name = "messages", display_order = 3, next_help_heading = "Labels")] #[clap(name = "messages", display_order = 3, next_help_heading = "Labels")]
Message(MessagesCli), Message(MessagesCli),
/// List and inspect available Gmail labels. /// List and inspect available Gmail labels.
/// ///
/// Displays all labels in your Gmail account with their internal IDs, /// Displays all labels in your Gmail account with their internal IDs,
/// useful for understanding label structure before creating queries or rules. /// useful for understanding label structure before creating queries or rules.
#[clap(name = "labels", display_order = 2, next_help_heading = "Rules")] #[clap(name = "labels", display_order = 2, next_help_heading = "Rules")]
Labels(LabelsCli), Labels(LabelsCli),
/// Configure and execute automated message retention rules. /// Configure and execute automated message retention rules.
/// ///
/// Provides rule-based message lifecycle management with configurable /// Provides rule-based message lifecycle management with configurable
/// retention periods, label targeting, and automated actions. /// retention periods, label targeting, and automated actions.
#[clap(name = "rules", display_order = 2)] #[clap(name = "rules", display_order = 2)]
@@ -196,26 +196,26 @@ enum SubCmds {
} }
/// CLI application entry point with comprehensive error handling and logging setup. /// CLI application entry point with comprehensive error handling and logging setup.
/// ///
/// This function initializes the async runtime, parses command-line arguments, /// This function initializes the async runtime, parses command-line arguments,
/// configures logging based on user preferences, and orchestrates the main /// configures logging based on user preferences, and orchestrates the main
/// application workflow with proper error handling and exit code management. /// application workflow with proper error handling and exit code management.
/// ///
/// # Process Flow /// # Process Flow
/// ///
/// 1. **Argument Parsing**: Parse command-line arguments using clap /// 1. **Argument Parsing**: Parse command-line arguments using clap
/// 2. **Logging Setup**: Initialize logging with user-specified verbosity /// 2. **Logging Setup**: Initialize logging with user-specified verbosity
/// 3. **Application Execution**: Run the main application logic /// 3. **Application Execution**: Run the main application logic
/// 4. **Error Handling**: Handle errors with detailed reporting /// 4. **Error Handling**: Handle errors with detailed reporting
/// 5. **Exit Code**: Return appropriate exit codes for shell integration /// 5. **Exit Code**: Return appropriate exit codes for shell integration
/// ///
/// # Exit Codes /// # Exit Codes
/// ///
/// - **0**: Successful execution /// - **0**: Successful execution
/// - **101**: Error occurred (details logged and printed to stderr) /// - **101**: Error occurred (details logged and printed to stderr)
/// ///
/// # Error Reporting /// # Error Reporting
/// ///
/// Errors are reported through multiple channels: /// Errors are reported through multiple channels:
/// - **Logging**: Structured error logging for debugging /// - **Logging**: Structured error logging for debugging
/// - **stderr**: User-friendly error messages /// - **stderr**: User-friendly error messages
@@ -244,28 +244,28 @@ async fn main() {
} }
/// Main application logic dispatcher handling subcommand execution and default behavior. /// Main application logic dispatcher handling subcommand execution and default behavior.
/// ///
/// This function orchestrates the core application workflow by: /// This function orchestrates the core application workflow by:
/// 1. Loading configuration from files and environment /// 1. Loading configuration from files and environment
/// 2. Initializing the Gmail API client with OAuth2 authentication /// 2. Initializing the Gmail API client with OAuth2 authentication
/// 3. Dispatching to appropriate subcommands or executing default rule processing /// 3. Dispatching to appropriate subcommands or executing default rule processing
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `args` - Parsed command-line arguments containing global options and subcommands /// * `args` - Parsed command-line arguments containing global options and subcommands
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<()>` indicating success or failure of the operation. /// Returns `Result<()>` indicating success or failure of the operation.
/// ///
/// # Default Behavior /// # Default Behavior
/// ///
/// When no subcommand is specified, the function executes the default rule processing /// When no subcommand is specified, the function executes the default rule processing
/// workflow, loading rules from configuration and executing them based on the /// workflow, loading rules from configuration and executing them based on the
/// current execution mode setting. /// current execution mode setting.
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// Errors can occur during: /// Errors can occur during:
/// - Configuration loading and parsing /// - Configuration loading and parsing
/// - Gmail client initialization and authentication /// - Gmail client initialization and authentication
@@ -290,31 +290,31 @@ async fn run(args: Cli) -> Result<()> {
} }
/// Creates and configures a logging builder with appropriate verbosity levels. /// Creates and configures a logging builder with appropriate verbosity levels.
/// ///
/// This function sets up structured logging for the application with: /// This function sets up structured logging for the application with:
/// - Minimum info-level logging for user-facing information /// - Minimum info-level logging for user-facing information
/// - Configurable verbosity based on command-line flags /// - Configurable verbosity based on command-line flags
/// - Timestamp formatting for operation tracking /// - Timestamp formatting for operation tracking
/// - Focused logging on the cull-gmail crate to reduce noise /// - Focused logging on the cull-gmail crate to reduce noise
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `level` - Desired log level filter from command-line verbosity flags /// * `level` - Desired log level filter from command-line verbosity flags
/// ///
/// # Returns /// # Returns
/// ///
/// Returns a configured `env_logger::Builder` ready for initialization. /// Returns a configured `env_logger::Builder` ready for initialization.
/// ///
/// # Logging Levels /// # Logging Levels
/// ///
/// - **Error**: Critical failures and unrecoverable errors /// - **Error**: Critical failures and unrecoverable errors
/// - **Warn**: Non-fatal issues, dry-run notifications, missing resources /// - **Warn**: Non-fatal issues, dry-run notifications, missing resources
/// - **Info**: General operation progress, message counts, rule execution /// - **Info**: General operation progress, message counts, rule execution
/// - **Debug**: Detailed operation info, API calls, configuration values /// - **Debug**: Detailed operation info, API calls, configuration values
/// - **Trace**: Very detailed debugging information /// - **Trace**: Very detailed debugging information
/// ///
/// # Default Behavior /// # Default Behavior
/// ///
/// The function enforces a minimum of Info-level logging to ensure users /// The function enforces a minimum of Info-level logging to ensure users
/// receive adequate feedback about application operations, even when /// receive adequate feedback about application operations, even when
/// verbosity is not explicitly requested. /// verbosity is not explicitly requested.
@@ -336,41 +336,41 @@ fn get_logging(level: log::LevelFilter) -> env_logger::Builder {
} }
/// Loads and parses application configuration from multiple sources. /// Loads and parses application configuration from multiple sources.
/// ///
/// This function implements a hierarchical configuration loading strategy: /// This function implements a hierarchical configuration loading strategy:
/// 1. **Default values**: Sensible defaults for all configuration options /// 1. **Default values**: Sensible defaults for all configuration options
/// 2. **Configuration file**: User-specific settings from `~/.cull-gmail/cull-gmail.toml` /// 2. **Configuration file**: User-specific settings from `~/.cull-gmail/cull-gmail.toml`
/// 3. **Environment variables**: Runtime overrides with `APP_` prefix /// 3. **Environment variables**: Runtime overrides with `APP_` prefix
/// ///
/// # Returns /// # Returns
/// ///
/// Returns a tuple containing: /// Returns a tuple containing:
/// - **Config**: Raw configuration for general application settings /// - **Config**: Raw configuration for general application settings
/// - **ClientConfig**: Processed Gmail client configuration with OAuth2 setup /// - **ClientConfig**: Processed Gmail client configuration with OAuth2 setup
/// ///
/// # Configuration Hierarchy /// # Configuration Hierarchy
/// ///
/// Settings are applied in this order (later sources override earlier ones): /// Settings are applied in this order (later sources override earlier ones):
/// 1. Built-in defaults /// 1. Built-in defaults
/// 2. Configuration file values /// 2. Configuration file values
/// 3. Environment variable overrides /// 3. Environment variable overrides
/// ///
/// # Configuration Parameters /// # Configuration Parameters
/// ///
/// ## Default Values: /// ## Default Values:
/// - `credentials`: "credential.json" - OAuth2 credential file name /// - `credentials`: "credential.json" - OAuth2 credential file name
/// - `config_root`: "h:.cull-gmail" - Configuration directory (home-relative) /// - `config_root`: "h:.cull-gmail" - Configuration directory (home-relative)
/// - `rules`: "rules.toml" - Rules configuration file name /// - `rules`: "rules.toml" - Rules configuration file name
/// - `execute`: true - Default execution mode (can be overridden for safety) /// - `execute`: true - Default execution mode (can be overridden for safety)
/// ///
/// ## Environment Variables: /// ## Environment Variables:
/// - `APP_CREDENTIALS`: Override credential file name /// - `APP_CREDENTIALS`: Override credential file name
/// - `APP_CONFIG_ROOT`: Override configuration directory /// - `APP_CONFIG_ROOT`: Override configuration directory
/// - `APP_RULES`: Override rules file name /// - `APP_RULES`: Override rules file name
/// - `APP_EXECUTE`: Override execution mode (true/false) /// - `APP_EXECUTE`: Override execution mode (true/false)
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// Configuration errors can occur due to: /// Configuration errors can occur due to:
/// - Missing or inaccessible configuration files /// - Missing or inaccessible configuration files
/// - Invalid TOML syntax in configuration files /// - Invalid TOML syntax in configuration files
@@ -399,38 +399,38 @@ fn get_config() -> Result<(Config, ClientConfig)> {
} }
/// Executes automated message retention rules across Gmail labels. /// Executes automated message retention rules across Gmail labels.
/// ///
/// This function orchestrates the rule-based message processing workflow by: /// This function orchestrates the rule-based message processing workflow by:
/// 1. Organizing rules by their target labels /// 1. Organizing rules by their target labels
/// 2. Processing each label according to its configured rule /// 2. Processing each label according to its configured rule
/// 3. Executing or simulating actions based on execution mode /// 3. Executing or simulating actions based on execution mode
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `client` - Mutable Gmail client for API operations /// * `client` - Mutable Gmail client for API operations
/// * `rules` - Loaded rules configuration containing all retention policies /// * `rules` - Loaded rules configuration containing all retention policies
/// * `execute` - Whether to actually perform actions (true) or dry-run (false) /// * `execute` - Whether to actually perform actions (true) or dry-run (false)
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<()>` indicating success or failure of the rule processing. /// Returns `Result<()>` indicating success or failure of the rule processing.
/// ///
/// # Rule Processing Flow /// # Rule Processing Flow
/// ///
/// For each configured label: /// For each configured label:
/// 1. **Rule Lookup**: Find the retention rule for the label /// 1. **Rule Lookup**: Find the retention rule for the label
/// 2. **Rule Application**: Apply rule criteria to find matching messages /// 2. **Rule Application**: Apply rule criteria to find matching messages
/// 3. **Action Determination**: Determine appropriate action (trash/delete) /// 3. **Action Determination**: Determine appropriate action (trash/delete)
/// 4. **Execution**: Execute action or simulate for dry-run /// 4. **Execution**: Execute action or simulate for dry-run
/// ///
/// # Safety Features /// # Safety Features
/// ///
/// - **Dry-run mode**: When `execute` is false, actions are logged but not performed /// - **Dry-run mode**: When `execute` is false, actions are logged but not performed
/// - **Error isolation**: Errors for individual labels don't stop processing of other labels /// - **Error isolation**: Errors for individual labels don't stop processing of other labels
/// - **Detailed logging**: Comprehensive logging of rule execution and results /// - **Detailed logging**: Comprehensive logging of rule execution and results
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// The function continues processing even if individual rules fail, logging /// The function continues processing even if individual rules fail, logging
/// warnings for missing rules, processing errors, or action failures. /// warnings for missing rules, processing errors, or action failures.
async fn run_rules(client: &mut GmailClient, rules: Rules, execute: bool) -> Result<()> { async fn run_rules(client: &mut GmailClient, rules: Rules, execute: bool) -> Result<()> {
@@ -465,38 +465,38 @@ async fn run_rules(client: &mut GmailClient, rules: Rules, execute: bool) -> Res
} }
/// Executes the specified end-of-life action on messages for a Gmail label. /// Executes the specified end-of-life action on messages for a Gmail label.
/// ///
/// This function performs the actual message operations (trash or delete) based on /// This function performs the actual message operations (trash or delete) based on
/// the rule configuration and execution mode. It handles both recoverable (trash) /// the rule configuration and execution mode. It handles both recoverable (trash)
/// and permanent (delete) operations with appropriate logging and error handling. /// and permanent (delete) operations with appropriate logging and error handling.
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `action` - The end-of-life action to perform (Trash or Delete) /// * `action` - The end-of-life action to perform (Trash or Delete)
/// * `client` - Gmail client configured with messages to process /// * `client` - Gmail client configured with messages to process
/// * `label` - Label name for context in logging and error reporting /// * `label` - Label name for context in logging and error reporting
/// ///
/// # Actions /// # Actions
/// ///
/// ## Trash /// ## Trash
/// - **Operation**: Moves messages to Gmail's Trash folder /// - **Operation**: Moves messages to Gmail's Trash folder
/// - **Reversibility**: Messages can be recovered from Trash for ~30 days /// - **Reversibility**: Messages can be recovered from Trash for ~30 days
/// - **Safety**: Relatively safe operation with recovery options /// - **Safety**: Relatively safe operation with recovery options
/// ///
/// ## Delete /// ## Delete
/// - **Operation**: Permanently deletes messages from Gmail /// - **Operation**: Permanently deletes messages from Gmail
/// - **Reversibility**: **IRREVERSIBLE** - messages cannot be recovered /// - **Reversibility**: **IRREVERSIBLE** - messages cannot be recovered
/// - **Safety**: High-risk operation requiring careful consideration /// - **Safety**: High-risk operation requiring careful consideration
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// The function logs errors but does not propagate them, allowing rule processing /// The function logs errors but does not propagate them, allowing rule processing
/// to continue for other labels even if one action fails. Errors are reported through: /// to continue for other labels even if one action fails. Errors are reported through:
/// - **Warning logs**: Structured logging for debugging /// - **Warning logs**: Structured logging for debugging
/// - **Label context**: Error messages include label name for traceability /// - **Label context**: Error messages include label name for traceability
/// ///
/// # Safety Considerations /// # Safety Considerations
/// ///
/// This function should only be called when execute mode is enabled and after /// This function should only be called when execute mode is enabled and after
/// appropriate user confirmation for destructive operations. /// appropriate user confirmation for destructive operations.
async fn execute_action(action: EolAction, client: &GmailClient, label: &str) { async fn execute_action(action: EolAction, client: &GmailClient, label: &str) {

View File

@@ -83,18 +83,18 @@ use clap::{Parser, Subcommand};
use cull_gmail::{GmailClient, MessageList, Result, RuleProcessor}; use cull_gmail::{GmailClient, MessageList, Result, RuleProcessor};
/// Available actions for Gmail message operations. /// Available actions for Gmail message operations.
/// ///
/// This enum defines the three primary operations that can be performed on Gmail messages /// This enum defines the three primary operations that can be performed on Gmail messages
/// through the CLI, each with different levels of safety and reversibility. /// through the CLI, each with different levels of safety and reversibility.
/// ///
/// # Action Safety Levels /// # Action Safety Levels
/// ///
/// - **List**: Safe inspection operation with no modifications /// - **List**: Safe inspection operation with no modifications
/// - **Trash**: Recoverable operation (messages can be restored for ~30 days) /// - **Trash**: Recoverable operation (messages can be restored for ~30 days)
/// - **Delete**: Permanent operation (irreversible) /// - **Delete**: Permanent operation (irreversible)
/// ///
/// # Usage Context /// # Usage Context
/// ///
/// Actions are typically used in this progression: /// Actions are typically used in this progression:
/// 1. **List** - Preview messages that match criteria /// 1. **List** - Preview messages that match criteria
/// 2. **Trash** - Move messages to recoverable trash /// 2. **Trash** - Move messages to recoverable trash
@@ -102,25 +102,25 @@ use cull_gmail::{GmailClient, MessageList, Result, RuleProcessor};
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
enum MessageAction { enum MessageAction {
/// Display message information without making any changes. /// Display message information without making any changes.
/// ///
/// This is the safest operation, showing message details including: /// This is the safest operation, showing message details including:
/// - Message subject and sender /// - Message subject and sender
/// - Date and size information /// - Date and size information
/// - Labels and threading information /// - Labels and threading information
/// - Internal Gmail message IDs /// - Internal Gmail message IDs
List, List,
/// Move messages to Gmail's Trash folder. /// Move messages to Gmail's Trash folder.
/// ///
/// This operation: /// This operation:
/// - Moves messages to the Trash label /// - Moves messages to the Trash label
/// - Allows recovery for approximately 30 days /// - Allows recovery for approximately 30 days
/// - Is reversible through Gmail's web interface /// - Is reversible through Gmail's web interface
/// - Provides a safety buffer before permanent deletion /// - Provides a safety buffer before permanent deletion
Trash, Trash,
/// Permanently delete messages from Gmail. /// Permanently delete messages from Gmail.
/// ///
/// **WARNING**: This operation is irreversible! /// **WARNING**: This operation is irreversible!
/// - Messages are permanently removed from Gmail /// - Messages are permanently removed from Gmail
/// - No recovery is possible after deletion /// - No recovery is possible after deletion
@@ -130,43 +130,43 @@ enum MessageAction {
} }
/// Command-line interface for Gmail message querying and batch operations. /// Command-line interface for Gmail message querying and batch operations.
/// ///
/// This structure encapsulates all configuration options for the messages subcommand, /// This structure encapsulates all configuration options for the messages subcommand,
/// providing comprehensive filtering, pagination, and action capabilities for Gmail /// providing comprehensive filtering, pagination, and action capabilities for Gmail
/// message management. It supports complex queries using Gmail's search syntax and /// message management. It supports complex queries using Gmail's search syntax and
/// multiple filtering mechanisms. /// multiple filtering mechanisms.
/// ///
/// # Configuration Categories /// # Configuration Categories
/// ///
/// - **Pagination**: Control result set size and page limits /// - **Pagination**: Control result set size and page limits
/// - **Filtering**: Label-based and query-based message selection /// - **Filtering**: Label-based and query-based message selection
/// - **Actions**: Operations to perform on selected messages /// - **Actions**: Operations to perform on selected messages
/// ///
/// # Usage Patterns /// # Usage Patterns
/// ///
/// ## Safe Exploration /// ## Safe Exploration
/// ```bash /// ```bash
/// # Start with list to preview results /// # Start with list to preview results
/// cull-gmail messages -Q "older_than:1y" list /// cull-gmail messages -Q "older_than:1y" list
/// ///
/// # Then perform actions on the same query /// # Then perform actions on the same query
/// cull-gmail messages -Q "older_than:1y" trash /// cull-gmail messages -Q "older_than:1y" trash
/// ``` /// ```
/// ///
/// ## Controlled Processing /// ## Controlled Processing
/// ```bash /// ```bash
/// # Process in small batches /// # Process in small batches
/// cull-gmail messages -m 50 -p 5 -Q "label:newsletters" list /// cull-gmail messages -m 50 -p 5 -Q "label:newsletters" list
/// ``` /// ```
/// ///
/// ## Multi-Criteria Filtering /// ## Multi-Criteria Filtering
/// ```bash /// ```bash
/// # Combine labels and query filters /// # Combine labels and query filters
/// cull-gmail messages -l "promotions" -l "social" -Q "older_than:6m" trash /// cull-gmail messages -l "promotions" -l "social" -Q "older_than:6m" trash
/// ``` /// ```
/// ///
/// # Safety Considerations /// # Safety Considerations
/// ///
/// - Always use `list` action first to preview results /// - Always use `list` action first to preview results
/// - Start with small page sizes for destructive operations /// - Start with small page sizes for destructive operations
/// - Use `trash` instead of `delete` when possible for recoverability /// - Use `trash` instead of `delete` when possible for recoverability
@@ -174,21 +174,21 @@ enum MessageAction {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct MessagesCli { pub struct MessagesCli {
/// Maximum number of messages to retrieve per page. /// Maximum number of messages to retrieve per page.
/// ///
/// Controls the batch size for Gmail API requests. Larger values are more /// Controls the batch size for Gmail API requests. Larger values are more
/// efficient but may hit API rate limits. Smaller values provide more /// efficient but may hit API rate limits. Smaller values provide more
/// granular control and progress feedback. /// granular control and progress feedback.
/// ///
/// **Range**: 1-500 (Gmail API limit) /// **Range**: 1-500 (Gmail API limit)
/// **Performance**: 100-200 is typically optimal /// **Performance**: 100-200 is typically optimal
#[arg(short, long,display_order = 1, help_heading = "Config", default_value = cull_gmail::DEFAULT_MAX_RESULTS)] #[arg(short, long,display_order = 1, help_heading = "Config", default_value = cull_gmail::DEFAULT_MAX_RESULTS)]
max_results: u32, max_results: u32,
/// Maximum number of pages to process. /// Maximum number of pages to process.
/// ///
/// Limits the total number of API requests and messages processed. /// Limits the total number of API requests and messages processed.
/// Use 0 for unlimited pages (process all matching messages). /// Use 0 for unlimited pages (process all matching messages).
/// ///
/// **Safety**: Start with 1-2 pages for testing destructive operations /// **Safety**: Start with 1-2 pages for testing destructive operations
/// **Performance**: Higher values process more messages but take longer /// **Performance**: Higher values process more messages but take longer
#[arg( #[arg(
@@ -199,32 +199,32 @@ pub struct MessagesCli {
default_value = "1" default_value = "1"
)] )]
pages: u32, pages: u32,
/// Gmail labels to filter messages (can be specified multiple times). /// Gmail labels to filter messages (can be specified multiple times).
/// ///
/// Filters messages to only those containing ALL specified labels. /// Filters messages to only those containing ALL specified labels.
/// Use `cull-gmail labels` to see available labels in your account. /// Use `cull-gmail labels` to see available labels in your account.
/// ///
/// **Examples**: /// **Examples**:
/// - `-l "INBOX"` - Messages in inbox /// - `-l "INBOX"` - Messages in inbox
/// - `-l "promotions" -l "unread"` - Unread promotional messages /// - `-l "promotions" -l "unread"` - Unread promotional messages
#[arg(short, long, display_order = 1, help_heading = "Config")] #[arg(short, long, display_order = 1, help_heading = "Config")]
labels: Vec<String>, labels: Vec<String>,
/// Gmail query string using Gmail's advanced search syntax. /// Gmail query string using Gmail's advanced search syntax.
/// ///
/// Supports the same query syntax as Gmail's web interface search box. /// Supports the same query syntax as Gmail's web interface search box.
/// Can be combined with label filters for more precise targeting. /// Can be combined with label filters for more precise targeting.
/// ///
/// **Examples**: /// **Examples**:
/// - `"older_than:1y"` - Messages older than 1 year /// - `"older_than:1y"` - Messages older than 1 year
/// - `"from:noreply@example.com older_than:30d"` - Old automated emails /// - `"from:noreply@example.com older_than:30d"` - Old automated emails
/// - `"has:attachment larger:10M"` - Large attachments /// - `"has:attachment larger:10M"` - Large attachments
#[arg(short = 'Q', long, display_order = 1, help_heading = "Config")] #[arg(short = 'Q', long, display_order = 1, help_heading = "Config")]
query: Option<String>, query: Option<String>,
/// Action to perform on the filtered messages. /// Action to perform on the filtered messages.
/// ///
/// Determines what operation to execute on messages matching the filter criteria. /// Determines what operation to execute on messages matching the filter criteria.
/// Actions range from safe inspection (list) to permanent deletion (delete). /// Actions range from safe inspection (list) to permanent deletion (delete).
#[command(subcommand)] #[command(subcommand)]
@@ -233,52 +233,52 @@ pub struct MessagesCli {
impl MessagesCli { impl MessagesCli {
/// Executes the messages command with the configured parameters and action. /// Executes the messages command with the configured parameters and action.
/// ///
/// This method orchestrates the complete message processing workflow: /// This method orchestrates the complete message processing workflow:
/// 1. **Parameter Configuration**: Apply filters, pagination, and query settings /// 1. **Parameter Configuration**: Apply filters, pagination, and query settings
/// 2. **Message Retrieval**: Fetch messages from Gmail API based on criteria /// 2. **Message Retrieval**: Fetch messages from Gmail API based on criteria
/// 3. **Action Execution**: Perform the specified operation on retrieved messages /// 3. **Action Execution**: Perform the specified operation on retrieved messages
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `client` - Mutable Gmail client for API operations and state management /// * `client` - Mutable Gmail client for API operations and state management
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<()>` indicating success or failure of the complete operation. /// Returns `Result<()>` indicating success or failure of the complete operation.
/// ///
/// # Processing Flow /// # Processing Flow
/// ///
/// ## Parameter Setup /// ## Parameter Setup
/// - Apply label filters to restrict message scope /// - Apply label filters to restrict message scope
/// - Configure Gmail query string for advanced filtering /// - Configure Gmail query string for advanced filtering
/// - Set pagination parameters for controlled processing /// - Set pagination parameters for controlled processing
/// ///
/// ## Message Retrieval /// ## Message Retrieval
/// - Execute Gmail API requests to fetch matching messages /// - Execute Gmail API requests to fetch matching messages
/// - Handle pagination according to configured limits /// - Handle pagination according to configured limits
/// - Process results in manageable batches /// - Process results in manageable batches
/// ///
/// ## Action Execution /// ## Action Execution
/// - **List**: Display message information with logging level awareness /// - **List**: Display message information with logging level awareness
/// - **Trash**: Move messages to Gmail Trash (recoverable) /// - **Trash**: Move messages to Gmail Trash (recoverable)
/// - **Delete**: Permanently remove messages (irreversible) /// - **Delete**: Permanently remove messages (irreversible)
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// The method handles various error conditions: /// The method handles various error conditions:
/// - **Parameter errors**: Invalid labels or malformed queries /// - **Parameter errors**: Invalid labels or malformed queries
/// - **API errors**: Network issues, authentication failures, rate limits /// - **API errors**: Network issues, authentication failures, rate limits
/// - **Action errors**: Failures during trash or delete operations /// - **Action errors**: Failures during trash or delete operations
/// ///
/// # Performance Considerations /// # Performance Considerations
/// ///
/// - **Batch processing**: Messages are processed in configurable batches /// - **Batch processing**: Messages are processed in configurable batches
/// - **Rate limiting**: Respects Gmail API quotas and limits /// - **Rate limiting**: Respects Gmail API quotas and limits
/// - **Memory management**: Efficient handling of large result sets /// - **Memory management**: Efficient handling of large result sets
/// ///
/// # Safety Features /// # Safety Features
/// ///
/// - **Logging awareness**: List output adapts to logging verbosity /// - **Logging awareness**: List output adapts to logging verbosity
/// - **Error isolation**: Individual message failures don't stop batch processing /// - **Error isolation**: Individual message failures don't stop batch processing
/// - **Progress tracking**: Detailed logging for operation monitoring /// - **Progress tracking**: Detailed logging for operation monitoring
@@ -303,45 +303,45 @@ impl MessagesCli {
} }
/// Configures the Gmail client with filtering and pagination parameters. /// Configures the Gmail client with filtering and pagination parameters.
/// ///
/// This method applies all user-specified configuration to the Gmail client, /// This method applies all user-specified configuration to the Gmail client,
/// preparing it for message retrieval operations. It handles label filters, /// preparing it for message retrieval operations. It handles label filters,
/// query strings, and pagination settings with comprehensive error checking. /// query strings, and pagination settings with comprehensive error checking.
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `client` - Mutable Gmail client to configure /// * `client` - Mutable Gmail client to configure
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<()>` indicating success or failure of parameter configuration. /// Returns `Result<()>` indicating success or failure of parameter configuration.
/// ///
/// # Configuration Steps /// # Configuration Steps
/// ///
/// ## Label Filtering /// ## Label Filtering
/// - Validates label names against available Gmail labels /// - Validates label names against available Gmail labels
/// - Applies multiple label filters with AND logic /// - Applies multiple label filters with AND logic
/// - Skips label configuration if no labels specified /// - Skips label configuration if no labels specified
/// ///
/// ## Query Configuration /// ## Query Configuration
/// - Applies Gmail query string if provided /// - Applies Gmail query string if provided
/// - Combines with label filters for refined targeting /// - Combines with label filters for refined targeting
/// - Uses Gmail's native query syntax parsing /// - Uses Gmail's native query syntax parsing
/// ///
/// ## Pagination Setup /// ## Pagination Setup
/// - Configures maximum results per page for API efficiency /// - Configures maximum results per page for API efficiency
/// - Logs configuration values for debugging and verification /// - Logs configuration values for debugging and verification
/// - Ensures values are within Gmail API limits /// - Ensures values are within Gmail API limits
/// ///
/// # Error Conditions /// # Error Conditions
/// ///
/// The method can fail due to: /// The method can fail due to:
/// - **Invalid labels**: Label names that don't exist in the Gmail account /// - **Invalid labels**: Label names that don't exist in the Gmail account
/// - **Malformed queries**: Query syntax that Gmail API cannot parse /// - **Malformed queries**: Query syntax that Gmail API cannot parse
/// - **Parameter limits**: Values outside Gmail API acceptable ranges /// - **Parameter limits**: Values outside Gmail API acceptable ranges
/// ///
/// # Logging /// # Logging
/// ///
/// Configuration steps are logged at appropriate levels: /// Configuration steps are logged at appropriate levels:
/// - **Trace**: Detailed parameter values for debugging /// - **Trace**: Detailed parameter values for debugging
/// - **Debug**: Configuration confirmation and validation results /// - **Debug**: Configuration confirmation and validation results
@@ -362,13 +362,13 @@ impl MessagesCli {
} }
/// Returns a reference to the configured Gmail labels for filtering. /// Returns a reference to the configured Gmail labels for filtering.
/// ///
/// This accessor provides access to the list of labels that will be used /// This accessor provides access to the list of labels that will be used
/// to filter messages. Labels are combined with AND logic, meaning messages /// to filter messages. Labels are combined with AND logic, meaning messages
/// must have ALL specified labels to be included in results. /// must have ALL specified labels to be included in results.
/// ///
/// # Returns /// # Returns
/// ///
/// Returns a reference to the vector of label names as configured by the user. /// Returns a reference to the vector of label names as configured by the user.
/// An empty vector indicates no label-based filtering will be applied. /// An empty vector indicates no label-based filtering will be applied.
pub(crate) fn labels(&self) -> &Vec<String> { pub(crate) fn labels(&self) -> &Vec<String> {
@@ -376,13 +376,13 @@ impl MessagesCli {
} }
/// Returns a reference to the configured Gmail query string. /// Returns a reference to the configured Gmail query string.
/// ///
/// This accessor provides access to the advanced query string that will be /// This accessor provides access to the advanced query string that will be
/// applied to message filtering. The query uses Gmail's native search syntax /// applied to message filtering. The query uses Gmail's native search syntax
/// and can be combined with label filters for precise targeting. /// and can be combined with label filters for precise targeting.
/// ///
/// # Returns /// # Returns
/// ///
/// Returns a reference to the optional query string. `None` indicates /// Returns a reference to the optional query string. `None` indicates
/// no advanced query filtering will be applied. /// no advanced query filtering will be applied.
pub(crate) fn query(&self) -> &Option<String> { pub(crate) fn query(&self) -> &Option<String> {
@@ -390,13 +390,13 @@ impl MessagesCli {
} }
/// Returns the maximum number of messages to retrieve per page. /// Returns the maximum number of messages to retrieve per page.
/// ///
/// This accessor provides the configured batch size for Gmail API requests. /// This accessor provides the configured batch size for Gmail API requests.
/// The value determines how many messages are fetched in each API call, /// The value determines how many messages are fetched in each API call,
/// affecting both performance and memory usage. /// affecting both performance and memory usage.
/// ///
/// # Returns /// # Returns
/// ///
/// Returns the maximum results per page as configured by the user or default value. /// Returns the maximum results per page as configured by the user or default value.
/// The value is guaranteed to be within Gmail API acceptable limits. /// The value is guaranteed to be within Gmail API acceptable limits.
pub(crate) fn max_results(&self) -> u32 { pub(crate) fn max_results(&self) -> u32 {

View File

@@ -112,18 +112,18 @@ use config_cli::ConfigCli;
use run_cli::RunCli; use run_cli::RunCli;
/// Available subcommands for rules management and execution. /// Available subcommands for rules management and execution.
/// ///
/// This enum defines the two main operational modes for the rules CLI: /// This enum defines the two main operational modes for the rules CLI:
/// configuration management and rule execution. Each mode provides /// configuration management and rule execution. Each mode provides
/// specialized functionality for different aspects of rule lifecycle management. /// specialized functionality for different aspects of rule lifecycle management.
/// ///
/// # Command Categories /// # Command Categories
/// ///
/// - **Config**: Rule definition, modification, and management operations /// - **Config**: Rule definition, modification, and management operations
/// - **Run**: Rule execution with various safety and control options /// - **Run**: Rule execution with various safety and control options
/// ///
/// # Workflow Integration /// # Workflow Integration
/// ///
/// Typical usage follows this pattern: /// Typical usage follows this pattern:
/// 1. Use `config` to set up rules, labels, and actions /// 1. Use `config` to set up rules, labels, and actions
/// 2. Use `run` to execute rules with dry-run testing /// 2. Use `run` to execute rules with dry-run testing
@@ -131,27 +131,27 @@ use run_cli::RunCli;
#[derive(Subcommand, Debug)] #[derive(Subcommand, Debug)]
enum SubCmds { enum SubCmds {
/// Configure Gmail message retention rules, labels, and actions. /// Configure Gmail message retention rules, labels, and actions.
/// ///
/// Provides comprehensive rule management functionality including: /// Provides comprehensive rule management functionality including:
/// - **Rule creation**: Define new retention policies /// - **Rule creation**: Define new retention policies
/// - **Label management**: Configure target labels for rules /// - **Label management**: Configure target labels for rules
/// - **Action setting**: Specify trash or delete actions /// - **Action setting**: Specify trash or delete actions
/// - **Rule modification**: Update existing rule parameters /// - **Rule modification**: Update existing rule parameters
/// ///
/// The config subcommand enables fine-grained control over rule behavior /// The config subcommand enables fine-grained control over rule behavior
/// and provides validation to ensure rules are properly configured /// and provides validation to ensure rules are properly configured
/// before execution. /// before execution.
#[clap(name = "config")] #[clap(name = "config")]
Config(ConfigCli), Config(ConfigCli),
/// Execute configured retention rules with optional safety controls. /// Execute configured retention rules with optional safety controls.
/// ///
/// Provides rule execution functionality with comprehensive safety features: /// Provides rule execution functionality with comprehensive safety features:
/// - **Dry-run mode**: Preview rule effects without making changes /// - **Dry-run mode**: Preview rule effects without making changes
/// - **Selective execution**: Skip specific action types (trash/delete) /// - **Selective execution**: Skip specific action types (trash/delete)
/// - **Error handling**: Continue processing despite individual failures /// - **Error handling**: Continue processing despite individual failures
/// - **Progress tracking**: Detailed logging of rule execution /// - **Progress tracking**: Detailed logging of rule execution
/// ///
/// The run subcommand is the primary interface for automated message /// The run subcommand is the primary interface for automated message
/// lifecycle management based on configured retention policies. /// lifecycle management based on configured retention policies.
#[clap(name = "run")] #[clap(name = "run")]
@@ -159,43 +159,43 @@ enum SubCmds {
} }
/// Command-line interface for Gmail message retention rule management. /// Command-line interface for Gmail message retention rule management.
/// ///
/// This structure represents the rules subcommand, providing comprehensive /// This structure represents the rules subcommand, providing comprehensive
/// functionality for both configuring and executing automated Gmail message /// functionality for both configuring and executing automated Gmail message
/// retention policies. It serves as the main entry point for rule-based /// retention policies. It serves as the main entry point for rule-based
/// message lifecycle management. /// message lifecycle management.
/// ///
/// # Core Functionality /// # Core Functionality
/// ///
/// - **Rule Configuration**: Create, modify, and manage retention rules /// - **Rule Configuration**: Create, modify, and manage retention rules
/// - **Label Management**: Associate rules with specific Gmail labels /// - **Label Management**: Associate rules with specific Gmail labels
/// - **Action Control**: Configure trash or delete actions for rules /// - **Action Control**: Configure trash or delete actions for rules
/// - **Rule Execution**: Run configured rules with safety controls /// - **Rule Execution**: Run configured rules with safety controls
/// ///
/// # Architecture /// # Architecture
/// ///
/// The RulesCli delegates to specialized subcommands: /// The RulesCli delegates to specialized subcommands:
/// - **ConfigCli**: Handles all rule configuration operations /// - **ConfigCli**: Handles all rule configuration operations
/// - **RunCli**: Manages rule execution and safety controls /// - **RunCli**: Manages rule execution and safety controls
/// ///
/// # Configuration Flow /// # Configuration Flow
/// ///
/// 1. **Rule Creation**: Define retention periods and basic parameters /// 1. **Rule Creation**: Define retention periods and basic parameters
/// 2. **Label Assignment**: Associate rules with target Gmail labels /// 2. **Label Assignment**: Associate rules with target Gmail labels
/// 3. **Action Configuration**: Set appropriate actions (trash/delete) /// 3. **Action Configuration**: Set appropriate actions (trash/delete)
/// 4. **Validation**: Ensure rules are properly configured /// 4. **Validation**: Ensure rules are properly configured
/// 5. **Execution**: Run rules with appropriate safety controls /// 5. **Execution**: Run rules with appropriate safety controls
/// ///
/// # Safety Integration /// # Safety Integration
/// ///
/// The RulesCli incorporates multiple safety layers: /// The RulesCli incorporates multiple safety layers:
/// - **Configuration validation**: Rules are validated before execution /// - **Configuration validation**: Rules are validated before execution
/// - **Dry-run capabilities**: Preview rule effects before applying changes /// - **Dry-run capabilities**: Preview rule effects before applying changes
/// - **Error isolation**: Individual rule failures don't stop processing /// - **Error isolation**: Individual rule failures don't stop processing
/// - **Comprehensive logging**: Detailed tracking of all operations /// - **Comprehensive logging**: Detailed tracking of all operations
/// ///
/// # Usage Context /// # Usage Context
/// ///
/// This CLI is designed for: /// This CLI is designed for:
/// - **System administrators**: Managing organizational Gmail retention policies /// - **System administrators**: Managing organizational Gmail retention policies
/// - **Power users**: Implementing personal email organization strategies /// - **Power users**: Implementing personal email organization strategies
@@ -204,7 +204,7 @@ enum SubCmds {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct RulesCli { pub struct RulesCli {
/// Subcommand selection for rules operations. /// Subcommand selection for rules operations.
/// ///
/// Determines whether to perform configuration management or rule execution. /// Determines whether to perform configuration management or rule execution.
/// Each subcommand provides specialized functionality for its domain. /// Each subcommand provides specialized functionality for its domain.
#[command(subcommand)] #[command(subcommand)]
@@ -213,51 +213,51 @@ pub struct RulesCli {
impl RulesCli { impl RulesCli {
/// Executes the rules command based on the selected subcommand. /// Executes the rules command based on the selected subcommand.
/// ///
/// This method coordinates the rules workflow by first loading the current /// This method coordinates the rules workflow by first loading the current
/// rule configuration, then dispatching to the appropriate subcommand handler /// rule configuration, then dispatching to the appropriate subcommand handler
/// based on user selection (config or run). /// based on user selection (config or run).
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `client` - Mutable Gmail client for API operations during rule execution /// * `client` - Mutable Gmail client for API operations during rule execution
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<()>` indicating success or failure of the rules operation. /// Returns `Result<()>` indicating success or failure of the rules operation.
/// ///
/// # Operation Flow /// # Operation Flow
/// ///
/// ## Rule Loading /// ## Rule Loading
/// - Attempts to load existing rules from configuration file /// - Attempts to load existing rules from configuration file
/// - Creates default configuration if no rules file exists /// - Creates default configuration if no rules file exists
/// - Validates rule structure and consistency /// - Validates rule structure and consistency
/// ///
/// ## Subcommand Dispatch /// ## Subcommand Dispatch
/// - **Config operations**: Delegate to ConfigCli for rule management /// - **Config operations**: Delegate to ConfigCli for rule management
/// - **Run operations**: Delegate to RunCli for rule execution /// - **Run operations**: Delegate to RunCli for rule execution
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// The method handles several error conditions: /// The method handles several error conditions:
/// - **Configuration errors**: Problems loading or parsing rules file /// - **Configuration errors**: Problems loading or parsing rules file
/// - **Validation errors**: Invalid rule configurations or conflicts /// - **Validation errors**: Invalid rule configurations or conflicts
/// - **Execution errors**: Failures during rule processing or Gmail operations /// - **Execution errors**: Failures during rule processing or Gmail operations
/// ///
/// # Side Effects /// # Side Effects
/// ///
/// ## Configuration Mode /// ## Configuration Mode
/// - May modify the rules configuration file /// - May modify the rules configuration file
/// - Creates backup copies of configuration when making changes /// - Creates backup copies of configuration when making changes
/// - Validates configuration consistency after modifications /// - Validates configuration consistency after modifications
/// ///
/// ## Execution Mode /// ## Execution Mode
/// - May modify Gmail messages according to rule actions /// - May modify Gmail messages according to rule actions
/// - Produces detailed logging of operations performed /// - Produces detailed logging of operations performed
/// - Updates rule execution tracking and statistics /// - Updates rule execution tracking and statistics
/// ///
/// # Safety Features /// # Safety Features
/// ///
/// - **Configuration validation**: Rules are validated before use /// - **Configuration validation**: Rules are validated before use
/// - **Error isolation**: Subcommand errors don't affect rule loading /// - **Error isolation**: Subcommand errors don't affect rule loading
/// - **State preservation**: Configuration errors don't corrupt existing rules /// - **State preservation**: Configuration errors don't corrupt existing rules
@@ -272,57 +272,57 @@ impl RulesCli {
} }
/// Loads Gmail retention rules from configuration with automatic fallback. /// Loads Gmail retention rules from configuration with automatic fallback.
/// ///
/// This function provides robust rule loading with automatic configuration /// This function provides robust rule loading with automatic configuration
/// creation when no existing rules are found. It ensures that the rules /// creation when no existing rules are found. It ensures that the rules
/// subsystem always has a valid configuration to work with. /// subsystem always has a valid configuration to work with.
/// ///
/// # Returns /// # Returns
/// ///
/// Returns `Result<Rules>` containing the loaded or newly created rules configuration. /// Returns `Result<Rules>` containing the loaded or newly created rules configuration.
/// ///
/// # Loading Strategy /// # Loading Strategy
/// ///
/// ## Primary Path /// ## Primary Path
/// - Attempts to load existing rules from the configured rules file /// - Attempts to load existing rules from the configured rules file
/// - Validates rule structure and consistency /// - Validates rule structure and consistency
/// - Returns loaded rules if successful /// - Returns loaded rules if successful
/// ///
/// ## Fallback Path /// ## Fallback Path
/// - Creates new default rules configuration if loading fails /// - Creates new default rules configuration if loading fails
/// - Saves the default configuration to disk for future use /// - Saves the default configuration to disk for future use
/// - Returns the newly created default configuration /// - Returns the newly created default configuration
/// ///
/// # Configuration Location /// # Configuration Location
/// ///
/// Rules are typically stored in: /// Rules are typically stored in:
/// - **Default location**: `~/.cull-gmail/rules.toml` /// - **Default location**: `~/.cull-gmail/rules.toml`
/// - **Format**: TOML configuration with structured rule definitions /// - **Format**: TOML configuration with structured rule definitions
/// - **Permissions**: Should be readable/writable by user only /// - **Permissions**: Should be readable/writable by user only
/// ///
/// # Error Handling /// # Error Handling
/// ///
/// The function handles various error scenarios: /// The function handles various error scenarios:
/// - **Missing configuration**: Creates default configuration automatically /// - **Missing configuration**: Creates default configuration automatically
/// - **Corrupted configuration**: Logs warnings and falls back to defaults /// - **Corrupted configuration**: Logs warnings and falls back to defaults
/// - **File system errors**: Propagates errors for disk access issues /// - **File system errors**: Propagates errors for disk access issues
/// ///
/// # Default Configuration /// # Default Configuration
/// ///
/// When creating a new configuration, the function: /// When creating a new configuration, the function:
/// - Initializes an empty rules collection /// - Initializes an empty rules collection
/// - Sets up proper TOML structure for future rule additions /// - Sets up proper TOML structure for future rule additions
/// - Saves the configuration to disk for persistence /// - Saves the configuration to disk for persistence
/// ///
/// # Logging /// # Logging
/// ///
/// The function provides appropriate logging: /// The function provides appropriate logging:
/// - **Info**: Successful rule loading /// - **Info**: Successful rule loading
/// - **Warn**: Fallback to default configuration /// - **Warn**: Fallback to default configuration
/// - **Error**: Critical failures during configuration creation /// - **Error**: Critical failures during configuration creation
/// ///
/// # Usage Context /// # Usage Context
/// ///
/// This function is called by: /// This function is called by:
/// - **Rules CLI**: To load rules before configuration or execution /// - **Rules CLI**: To load rules before configuration or execution
/// - **Main CLI**: For default rule execution when no subcommand is specified /// - **Main CLI**: For default rule execution when no subcommand is specified