kasl/libs/data_storage.rs
1//! Cross-platform data storage path management for application files.
2//!
3//! Provides a unified interface for managing application data storage locations
4//! across different operating systems following OS conventions.
5//!
6//! ## Features
7//!
8//! - **Platform Support**: Windows LocalAppData, macOS Application Support, Linux XDG
9//! - **Automatic Directory Creation**: Creates required directories on first access
10//! - **Permission Handling**: Uses locations where users have write permissions
11//! - **Environment Variable Support**: Respects custom environment overrides
12//! - **Fallback Strategy**: Uses current directory if standard locations fail
13//!
14//! ## Usage
15//!
16//! ```rust
17//! use kasl::libs::data_storage::DataStorage;
18//!
19//! let storage = DataStorage::new();
20//! let db_path = storage.get_path("kasl.db")?;
21//! let config_path = storage.get_path("config.json")?;
22//! ```
23
24use anyhow::Result;
25use serde::Deserialize;
26use std::env::consts::OS;
27use std::env::var;
28use std::path::{Path, PathBuf};
29use std::{fs, str};
30
31// Include compile-time application metadata
32include!(concat!(env!("OUT_DIR"), "/app_metadata.rs"));
33
34/// Cross-platform data storage path manager.
35///
36/// The `DataStorage` struct provides a centralized way to manage file paths
37/// for application data across different operating systems. It encapsulates
38/// platform-specific logic and provides a consistent interface for path
39/// resolution and directory management.
40///
41/// ## Design Philosophy
42///
43/// The storage manager follows these principles:
44/// - **Platform Compliance**: Adheres to OS-specific directory conventions
45/// - **User-Centric**: Stores data in user-accessible locations
46/// - **Predictable**: Provides consistent behavior across platforms
47/// - **Robust**: Handles edge cases and permission issues gracefully
48///
49/// ## Initialization
50///
51/// The base path is determined during construction based on:
52/// 1. Operating system detection
53/// 2. Environment variable resolution
54/// 3. Fallback to safe defaults if needed
55/// 4. Organization and application name incorporation
56///
57/// ## Thread Safety
58///
59/// The struct is designed to be used safely across multiple threads,
60/// as path resolution is deterministic and doesn't modify internal state.
61#[derive(Deserialize, Clone)]
62pub struct DataStorage {
63 /// Base directory path for all application data.
64 ///
65 /// This path includes the platform-specific user data directory,
66 /// organization name, and application name. All application files
67 /// are stored as children of this base path.
68 ///
69 /// The path is resolved once during construction and remains constant
70 /// throughout the lifetime of the instance.
71 base_path: PathBuf,
72}
73
74impl DataStorage {
75 /// Creates a new DataStorage instance with platform-appropriate base path.
76 ///
77 /// This constructor performs automatic platform detection and constructs
78 /// the appropriate base directory path following OS conventions. It uses
79 /// environment variables where available and falls back to safe defaults.
80 ///
81 /// ## Platform Resolution Logic
82 ///
83 /// The constructor determines the base path using this priority order:
84 /// 1. **Environment Variables**: Uses OS-specific environment variables
85 /// 2. **Fallback Values**: Uses current directory if environment vars fail
86 /// 3. **Path Construction**: Appends organization and application names
87 /// 4. **Validation**: Ensures the resulting path is usable
88 ///
89 /// ## Application Metadata Integration
90 ///
91 /// The method uses compile-time metadata to construct paths:
92 /// - `APP_METADATA_OWNER`: Organization name (e.g., "lacodda")
93 /// - `APP_METADATA_NAME`: Application name (e.g., "kasl")
94 ///
95 /// This ensures consistent branding and path structure across builds.
96 ///
97 /// # Returns
98 ///
99 /// Returns a new `DataStorage` instance configured for the current platform
100 /// and user environment.
101 ///
102 /// # Example
103 ///
104 /// ```rust
105 /// use kasl::libs::data_storage::DataStorage;
106 ///
107 /// // Create platform-specific storage manager
108 /// let storage = DataStorage::new();
109 ///
110 /// // Base path is automatically configured
111 /// println!("Base path: {:?}", storage.base_path);
112 /// ```
113 ///
114 /// ## Environment Variable Usage
115 ///
116 /// - **Windows**: Uses `LOCALAPPDATA` for local application data
117 /// - **macOS**: Uses `HOME` to construct ~/Library/Application Support path
118 /// - **Linux**: Uses `HOME` to construct ~/.local/share path
119 ///
120 /// ## Error Resilience
121 ///
122 /// If environment variables are not available, the constructor:
123 /// - Falls back to current directory (".")
124 /// - Continues with path construction
125 /// - Defers directory creation until first access
126 /// - Allows application to function in restricted environments
127 pub fn new() -> Self {
128 // Determine platform-specific base directory
129 let base_path = match OS {
130 "windows" => {
131 // Windows: Use Local AppData for per-user application data
132 var("LOCALAPPDATA").unwrap_or_else(|_| ".".into())
133 }
134 "macos" => {
135 // macOS: Use Application Support following Apple guidelines
136 var("HOME").unwrap_or_else(|_| ".".into()) + "/Library/Application Support"
137 }
138 _ => {
139 // Linux/Unix: Use XDG-compliant local share directory
140 var("HOME").unwrap_or_else(|_| ".".into()) + "/.local/share"
141 }
142 };
143
144 // Construct full application path with organization and app name
145 let base_path = Path::new(&base_path).join(APP_METADATA_OWNER).join(APP_METADATA_NAME);
146
147 Self { base_path }
148 }
149
150 /// Resolves a filename to a complete path within the application data directory.
151 ///
152 /// This method takes a filename and returns the complete path where that file
153 /// should be stored within the application's data directory. It automatically
154 /// handles directory creation and ensures the path is ready for file operations.
155 ///
156 /// ## Directory Creation
157 ///
158 /// The method ensures that all necessary parent directories exist:
159 /// - Creates the entire directory tree if missing
160 /// - Uses OS-appropriate permissions for new directories
161 /// - Handles concurrent access scenarios safely
162 /// - Provides clear error messages if creation fails
163 ///
164 /// ## Path Construction
165 ///
166 /// The resulting path combines:
167 /// 1. **Base Path**: Platform-specific application data directory
168 /// 2. **Organization**: Namespace isolation (e.g., "lacodda")
169 /// 3. **Application**: Application-specific subdirectory (e.g., "kasl")
170 /// 4. **Filename**: The requested file within the application directory
171 ///
172 /// # Arguments
173 ///
174 /// * `file_name` - Name of the file to resolve to a full path
175 ///
176 /// # Returns
177 ///
178 /// Returns the complete `PathBuf` where the file should be stored,
179 /// or an error if directory creation fails or paths are invalid.
180 ///
181 /// # Example
182 ///
183 /// ```rust
184 /// use kasl::libs::data_storage::DataStorage;
185 ///
186 /// let storage = DataStorage::new();
187 ///
188 /// // Get path for database file
189 /// let db_path = storage.get_path("kasl.db")?;
190 /// // Result: /home/user/.local/share/lacodda/kasl/kasl.db (Linux)
191 /// // C:\Users\User\AppData\Local\lacodda\kasl\kasl.db (Windows)
192 ///
193 /// // Get path for configuration file
194 /// let config_path = storage.get_path("config.json")?;
195 ///
196 /// // Get path for session cache
197 /// let session_path = storage.get_path(".jira_session_id")?;
198 /// ```
199 ///
200 /// ## File Naming Conventions
201 ///
202 /// The method accepts any valid filename, but common patterns include:
203 /// - **Database files**: `kasl.db`, `backup.db`
204 /// - **Configuration**: `config.json`, `settings.toml`
205 /// - **Cache files**: `.session_id`, `.auth_token`
206 /// - **Process files**: `kasl-watch.pid`
207 /// - **Logs**: `kasl.log`, `debug.log`
208 ///
209 /// ## Error Scenarios
210 ///
211 /// The method can fail in several situations:
212 /// - **Permission Denied**: Insufficient permissions to create directories
213 /// - **Disk Full**: No space available for directory creation
214 /// - **Path Too Long**: Resulting path exceeds OS limits
215 /// - **Invalid Characters**: Filename contains invalid characters for the OS
216 /// - **Read-Only Filesystem**: Target location is mounted read-only
217 ///
218 /// ## Concurrency Safety
219 ///
220 /// The directory creation process is designed to handle concurrent access:
221 /// - Multiple processes can safely call this method simultaneously
222 /// - Directory creation is atomic where supported by the OS
223 /// - Existing directories are not affected by creation attempts
224 /// - Race conditions in directory creation are handled gracefully
225 pub fn get_path(&self, file_name: &str) -> Result<PathBuf> {
226 // Ensure the base directory structure exists
227 if !self.base_path.exists() {
228 fs::create_dir_all(&self.base_path)?;
229 }
230
231 // Construct and return the complete file path
232 Ok(self.base_path.join(file_name))
233 }
234}