docs: Add comprehensive rustdoc to common module functions

Co-authored-by: aider (openai/andrew/openrouter/sonoma-sky-alpha) <aider@aider.chat>
This commit is contained in:
Andrew Phillips
2025-09-10 12:53:21 -03:00
parent c199590b3c
commit a7bcad40bb

View File

@@ -1,3 +1,17 @@
/// Common utilities shared across different modes in the Keep application.
///
/// This module provides helper functions for formatting, configuration parsing,
/// table creation, and environment variable handling used by various CLI modes.
///
/// # Usage
///
/// These utilities are typically used internally by mode implementations:
///
/// ```
/// use crate::modes::common::{format_size, OutputFormat};
/// let formatted = format_size(1024, true); // "1.0K"
/// let format = OutputFormat::from_str("json")?;
/// ```
use crate::config; use crate::config;
use crate::compression_engine::CompressionType; use crate::compression_engine::CompressionType;
use crate::meta_plugin::MetaPluginType; use crate::meta_plugin::MetaPluginType;
@@ -11,6 +25,16 @@ use std::env;
use std::io::IsTerminal; use std::io::IsTerminal;
use std::str::FromStr; use std::str::FromStr;
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
/// Enum representing supported output formats for structured data.
///
/// Used to determine how to display lists, info, and status information.
///
/// # Variants
///
/// * `Table` - Formatted table output (default).
/// * `Json` - JSON structured output.
/// * `Yaml` - YAML structured output.
#[derive(Debug, Clone, strum::EnumString, strum::Display, PartialEq)] #[derive(Debug, Clone, strum::EnumString, strum::Display, PartialEq)]
#[strum(ascii_case_insensitive)] #[strum(ascii_case_insensitive)]
pub enum OutputFormat { pub enum OutputFormat {
@@ -19,6 +43,23 @@ pub enum OutputFormat {
Yaml, Yaml,
} }
/// Extracts metadata from KEEP_META_* environment variables.
///
/// Scans environment for variables prefixed with KEEP_META_ and extracts
/// key-value pairs for initial item metadata.
///
/// # Returns
///
/// `HashMap<String, String>` - Metadata from environment variables.
///
/// # Examples
///
/// ```
/// # use std::env;
/// env::set_var("KEEP_META_COMMAND", "ls -la");
/// let meta = get_meta_from_env();
/// assert_eq!(meta.get("COMMAND"), Some(&"ls -la".to_string()));
/// ```
pub fn get_meta_from_env() -> HashMap<String, String> { pub fn get_meta_from_env() -> HashMap<String, String> {
debug!("COMMON: Getting meta from KEEP_META_*"); debug!("COMMON: Getting meta from KEEP_META_*");
let re = Regex::new(r"^KEEP_META_(.+)$").unwrap(); let re = Regex::new(r"^KEEP_META_(.+)$").unwrap();
@@ -36,6 +77,23 @@ pub fn get_meta_from_env() -> HashMap<String, String> {
meta_env meta_env
} }
/// Formats a file size in bytes to human-readable or raw format.
///
/// # Arguments
///
/// * `size` - Size in bytes.
/// * `human_readable` - If true, use units like KB, MB; otherwise, raw bytes.
///
/// # Returns
///
/// `String` - Formatted size string.
///
/// # Examples
///
/// ```
/// let raw = format_size(1024, false); // "1024"
/// let human = format_size(1024, true); // "1.0K"
/// ```
pub fn format_size(size: u64, human_readable: bool) -> String { pub fn format_size(size: u64, human_readable: bool) -> String {
match human_readable { match human_readable {
true => humansize::format_size(size, humansize::DECIMAL), true => humansize::format_size(size, humansize::DECIMAL),
@@ -43,8 +101,20 @@ pub fn format_size(size: u64, human_readable: bool) -> String {
} }
} }
/// Enum representing column types for table display.
///
/// Defines standard and meta columns for list/info modes.
///
/// # Variants
///
/// * `Id` - Item ID column.
/// * `Time` - Timestamp column.
/// * `Size` - Content size column.
/// * `Compression` - Compression type column.
/// * `FileSize` - On-disk file size column.
/// * `FilePath` - File path column.
/// * `Tags` - Tags column.
/// * `Meta` - Metadata column (with sub-type via string parsing).
#[derive(Debug, Eq, PartialEq, Clone, strum::EnumIter, strum::Display, strum::EnumString)] #[derive(Debug, Eq, PartialEq, Clone, strum::EnumIter, strum::Display, strum::EnumString)]
#[strum(ascii_case_insensitive)] #[strum(ascii_case_insensitive)]
pub enum ColumnType { pub enum ColumnType {
@@ -59,7 +129,22 @@ pub enum ColumnType {
} }
impl ColumnType { impl ColumnType {
/// Returns a Result with error message if the string is not a valid ColumnType /// Parses a string to a ColumnType, handling "meta:<name>" pattern.
///
/// # Arguments
///
/// * `s` - Input string to parse.
///
/// # Returns
///
/// * `anyhow::Result<ColumnType>` - Parsed type or error.
///
/// # Examples
///
/// ```
/// let meta = ColumnType::from_str("meta:hostname")?;
/// assert_eq!(meta, ColumnType::Meta);
/// ```
pub fn from_str(s: &str) -> anyhow::Result<Self> { pub fn from_str(s: &str) -> anyhow::Result<Self> {
if s.starts_with("meta:") { if s.starts_with("meta:") {
// Handle meta:<name> pattern - this is still a Meta column type // Handle meta:<name> pattern - this is still a Meta column type
@@ -71,13 +156,22 @@ impl ColumnType {
} }
} }
// impl TryFrom<&str> for ColumnType is already implemented by strum_macros /// Extracts configured meta plugin types from settings and command.
// so we remove this conflicting implementation ///
/// Handles comma-separated plugin names and validates against registered types.
///
/// # Arguments
///
/// * `cmd` - Mutable Clap command for error reporting.
/// * `settings` - Application settings with plugin config.
///
/// # Returns
///
/// `Vec<MetaPluginType>` - List of enabled plugin types.
///
/// # Panics
///
/// Exits via Clap error if unknown plugin type specified.
pub fn settings_meta_plugin_types(cmd: &mut Command, settings: &config::Settings) -> Vec<MetaPluginType> { pub fn settings_meta_plugin_types(cmd: &mut Command, settings: &config::Settings) -> Vec<MetaPluginType> {
let mut meta_plugin_types = Vec::new(); let mut meta_plugin_types = Vec::new();
@@ -115,7 +209,22 @@ pub fn settings_meta_plugin_types(cmd: &mut Command, settings: &config::Settings
meta_plugin_types meta_plugin_types
} }
/// Determines compression type from settings and command arguments.
///
/// Validates the compression name and returns the corresponding enum variant.
///
/// # Arguments
///
/// * `cmd` - Mutable Clap command for error reporting.
/// * `settings` - Application settings.
///
/// # Returns
///
/// `CompressionType` - The resolved compression type.
///
/// # Panics
///
/// Exits via Clap error if invalid compression specified.
pub fn settings_compression_type(cmd: &mut Command, settings: &config::Settings) -> CompressionType { pub fn settings_compression_type(cmd: &mut Command, settings: &config::Settings) -> CompressionType {
let compression_name = settings let compression_name = settings
.compression() .compression()
@@ -133,6 +242,17 @@ pub fn settings_compression_type(cmd: &mut Command, settings: &config::Settings)
compression_type_opt.unwrap() compression_type_opt.unwrap()
} }
/// Parses output format from settings.
///
/// Defaults to `Table` if not specified or invalid.
///
/// # Arguments
///
/// * `settings` - Application settings.
///
/// # Returns
///
/// `OutputFormat` - Parsed or default format.
pub fn settings_output_format(settings: &config::Settings) -> OutputFormat { pub fn settings_output_format(settings: &config::Settings) -> OutputFormat {
settings.output_format settings.output_format
.as_ref() .as_ref()
@@ -140,7 +260,24 @@ pub fn settings_output_format(settings: &config::Settings) -> OutputFormat {
.unwrap_or(OutputFormat::Table) .unwrap_or(OutputFormat::Table)
} }
/// Trim whitespace from the end of each line in a string /// Trims trailing whitespace from each line in a multi-line string.
///
/// Useful for cleaning up table output before printing.
///
/// # Arguments
///
/// * `s` - Input string with potential trailing whitespace.
///
/// # Returns
///
/// `String` - Cleaned string with trimmed lines.
///
/// # Examples
///
/// ```
/// let cleaned = trim_lines_end("line1 \nline2 ");
/// assert_eq!(cleaned, "line1\nline2");
/// ```
pub fn trim_lines_end(s: &str) -> String { pub fn trim_lines_end(s: &str) -> String {
s.lines() s.lines()
.map(|line| line.trim_end()) .map(|line| line.trim_end())
@@ -148,7 +285,24 @@ pub fn trim_lines_end(s: &str) -> String {
.join("\n") .join("\n")
} }
/// Create a table with consistent styling and terminal detection /// Creates a new table with styling based on terminal detection.
///
/// Loads appropriate preset (UTF8 or ASCII) if styling is enabled.
///
/// # Arguments
///
/// * `use_styling` - If true, apply visual styling.
///
/// # Returns
///
/// `Table` - Configured table instance.
///
/// # Examples
///
/// ```
/// let table = create_table(true);
/// table.add_row(vec!["Header1", "Header2"]);
/// ```
pub fn create_table(use_styling: bool) -> Table { pub fn create_table(use_styling: bool) -> Table {
let mut table = Table::new(); let mut table = Table::new();
table.set_content_arrangement(ContentArrangement::Dynamic); table.set_content_arrangement(ContentArrangement::Dynamic);
@@ -171,7 +325,24 @@ pub fn create_table(use_styling: bool) -> Table {
table table
} }
/// Create a table using the provided table configuration /// Creates a table configured from application table settings.
///
/// Applies style presets, modifiers, content arrangement, and truncation indicators.
///
/// # Arguments
///
/// * `table_config` - Table configuration from settings.
///
/// # Returns
///
/// `Table` - Fully configured table.
///
/// # Examples
///
/// ```
/// let config = TableConfig::default();
/// let table = create_table_with_config(&config);
/// ```
pub fn create_table_with_config(table_config: &crate::config::TableConfig) -> Table { pub fn create_table_with_config(table_config: &crate::config::TableConfig) -> Table {
let mut table = Table::new(); let mut table = Table::new();
@@ -235,3 +406,5 @@ pub fn create_table_with_config(table_config: &crate::config::TableConfig) -> Ta
table table
} }
/// Exports public types and functions for use in other modules.
pub use self::{ColumnType, OutputFormat, format_size, settings_output_format};