local-store 0.1.0

Local storage primitives: platform-agnostic paths, ACID file/dir storage, atomic IO, format dispatch
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Platform-agnostic path management for application configuration and data.
//!
//! Provides unified path resolution strategies across different platforms.

use crate::errors::{IoOperationKind, StoreError};
use std::path::PathBuf;

/// Path resolution strategy.
///
/// Determines how configuration and data directories are resolved.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PathStrategy {
    /// Use OS-standard directories (default).
    ///
    /// - Linux:   `~/.config/` (XDG_CONFIG_HOME)
    /// - macOS:   `~/Library/Application Support/`
    /// - Windows: `%APPDATA%`
    #[default]
    System,

    /// Force XDG Base Directory specification on all platforms.
    ///
    /// Uses `~/.config/` for config and `~/.local/share/` for data
    /// on all platforms (Linux, macOS, Windows).
    ///
    /// This is useful for applications that want consistent paths
    /// across platforms (e.g., VSCode, Neovim, orcs).
    Xdg,

    /// Use a custom base directory.
    ///
    /// All paths will be resolved relative to this base directory.
    CustomBase(PathBuf),
}

/// Application path manager with configurable resolution strategies.
///
/// Provides platform-agnostic path resolution for configuration and data directories.
///
/// # Example
///
/// ```ignore
/// use local_store::{AppPaths, PathStrategy};
///
/// // Use OS-standard directories (default)
/// let paths = AppPaths::new("myapp");
/// let config_path = paths.config_file("config.toml")?;
///
/// // Force XDG on all platforms
/// let paths = AppPaths::new("myapp")
///     .config_strategy(PathStrategy::Xdg);
/// let config_path = paths.config_file("config.toml")?;
///
/// // Use custom base directory
/// let paths = AppPaths::new("myapp")
///     .config_strategy(PathStrategy::CustomBase("/opt/myapp".into()));
/// ```
#[derive(Debug, Clone)]
pub struct AppPaths {
    app_name: String,
    config_strategy: PathStrategy,
    data_strategy: PathStrategy,
}

impl AppPaths {
    /// Create a new path manager for the given application name.
    ///
    /// Uses `System` strategy by default for both config and data.
    ///
    /// # Arguments
    ///
    /// * `app_name` - Application name (used as subdirectory name)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let paths = AppPaths::new("myapp");
    /// ```
    pub fn new(app_name: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
            config_strategy: PathStrategy::default(),
            data_strategy: PathStrategy::default(),
        }
    }

    /// Set the configuration directory resolution strategy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let paths = AppPaths::new("myapp")
    ///     .config_strategy(PathStrategy::Xdg);
    /// ```
    pub fn config_strategy(mut self, strategy: PathStrategy) -> Self {
        self.config_strategy = strategy;
        self
    }

    /// Set the data directory resolution strategy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let paths = AppPaths::new("myapp")
    ///     .data_strategy(PathStrategy::Xdg);
    /// ```
    pub fn data_strategy(mut self, strategy: PathStrategy) -> Self {
        self.data_strategy = strategy;
        self
    }

    /// Get the configuration directory path.
    ///
    /// Creates the directory if it doesn't exist.
    ///
    /// # Returns
    ///
    /// The resolved configuration directory path.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::HomeDirNotFound` if the home directory cannot be determined.
    /// Returns `StoreError::IoError` if directory creation fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config_dir = paths.config_dir()?;
    /// // On Linux with System strategy: ~/.config/myapp
    /// // On macOS with System strategy: ~/Library/Application Support/myapp
    /// ```
    pub fn config_dir(&self) -> Result<PathBuf, StoreError> {
        let dir = self.resolve_config_dir()?;
        self.ensure_dir_exists(&dir)?;
        Ok(dir)
    }

    /// Get the data directory path.
    ///
    /// Creates the directory if it doesn't exist.
    ///
    /// # Returns
    ///
    /// The resolved data directory path.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::HomeDirNotFound` if the home directory cannot be determined.
    /// Returns `StoreError::IoError` if directory creation fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let data_dir = paths.data_dir()?;
    /// // On Linux with System strategy: ~/.local/share/myapp
    /// // On macOS with System strategy: ~/Library/Application Support/myapp
    /// ```
    pub fn data_dir(&self) -> Result<PathBuf, StoreError> {
        let dir = self.resolve_data_dir()?;
        self.ensure_dir_exists(&dir)?;
        Ok(dir)
    }

    /// Get a configuration file path.
    ///
    /// This is a convenience method that joins the filename to the config directory.
    /// Creates the parent directory if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `filename` - The configuration file name
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config_file = paths.config_file("config.toml")?;
    /// // On Linux with System strategy: ~/.config/myapp/config.toml
    /// ```
    pub fn config_file(&self, filename: &str) -> Result<PathBuf, StoreError> {
        Ok(self.config_dir()?.join(filename))
    }

    /// Get a data file path.
    ///
    /// This is a convenience method that joins the filename to the data directory.
    /// Creates the parent directory if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `filename` - The data file name
    ///
    /// # Example
    ///
    /// ```ignore
    /// let data_file = paths.data_file("cache.db")?;
    /// // On Linux with System strategy: ~/.local/share/myapp/cache.db
    /// ```
    pub fn data_file(&self, filename: &str) -> Result<PathBuf, StoreError> {
        Ok(self.data_dir()?.join(filename))
    }

    /// Resolve the configuration directory path based on the strategy.
    fn resolve_config_dir(&self) -> Result<PathBuf, StoreError> {
        match &self.config_strategy {
            PathStrategy::System => {
                // Use OS-standard config directory
                let base = dirs::config_dir().ok_or(StoreError::HomeDirNotFound)?;
                Ok(base.join(&self.app_name))
            }
            PathStrategy::Xdg => {
                // Force XDG on all platforms
                let home = dirs::home_dir().ok_or(StoreError::HomeDirNotFound)?;
                Ok(home.join(".config").join(&self.app_name))
            }
            PathStrategy::CustomBase(base) => Ok(base.join(&self.app_name)),
        }
    }

    /// Resolve the data directory path based on the strategy.
    fn resolve_data_dir(&self) -> Result<PathBuf, StoreError> {
        match &self.data_strategy {
            PathStrategy::System => {
                // Use OS-standard data directory
                let base = dirs::data_dir().ok_or(StoreError::HomeDirNotFound)?;
                Ok(base.join(&self.app_name))
            }
            PathStrategy::Xdg => {
                // Force XDG on all platforms
                let home = dirs::home_dir().ok_or(StoreError::HomeDirNotFound)?;
                Ok(home.join(".local/share").join(&self.app_name))
            }
            PathStrategy::CustomBase(base) => Ok(base.join("data").join(&self.app_name)),
        }
    }

    /// Ensure a directory exists, creating it if necessary.
    fn ensure_dir_exists(&self, path: &PathBuf) -> Result<(), StoreError> {
        if !path.exists() {
            std::fs::create_dir_all(path).map_err(|e| StoreError::IoError {
                operation: IoOperationKind::CreateDir,
                path: path.display().to_string(),
                context: None,
                error: e.to_string(),
            })?;
        }
        Ok(())
    }
}

/// Preference path manager for OS-recommended preference/configuration directories.
///
/// Unlike `AppPaths`, `PrefPath` strictly follows OS-specific conventions:
/// - macOS: `~/Library/Preferences/`
/// - Linux: `~/.config/` (XDG_CONFIG_HOME)
/// - Windows: `%APPDATA%`
///
/// # Example
///
/// ```ignore
/// use local_store::PrefPath;
///
/// let pref = PrefPath::new("com.example.myapp");
/// let pref_file = pref.pref_file("settings.plist")?;
/// // On macOS: ~/Library/Preferences/com.example.myapp/settings.plist
/// // On Linux: ~/.config/com.example.myapp/settings.plist
/// ```
#[derive(Debug, Clone)]
pub struct PrefPath {
    app_name: String,
}

impl PrefPath {
    /// Create a new preference path manager.
    ///
    /// # Arguments
    ///
    /// * `app_name` - Application identifier (e.g., "com.example.myapp" for macOS bundle ID style)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pref = PrefPath::new("com.example.myapp");
    /// ```
    pub fn new(app_name: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
        }
    }

    /// Get the preference directory path.
    ///
    /// Creates the directory if it doesn't exist.
    ///
    /// # Returns
    ///
    /// The resolved preference directory path:
    /// - macOS: `~/Library/Preferences/{app_name}`
    /// - Linux: `~/.config/{app_name}`
    /// - Windows: `%APPDATA%\{app_name}`
    ///
    /// # Errors
    ///
    /// Returns `StoreError::HomeDirNotFound` if the home directory cannot be determined.
    /// Returns `StoreError::IoError` if directory creation fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pref_dir = pref.pref_dir()?;
    /// // On macOS: ~/Library/Preferences/com.example.myapp
    /// ```
    pub fn pref_dir(&self) -> Result<PathBuf, StoreError> {
        let dir = self.resolve_pref_dir()?;
        self.ensure_dir_exists(&dir)?;
        Ok(dir)
    }

    /// Get a preference file path.
    ///
    /// This is a convenience method that joins the filename to the preference directory.
    /// Creates the parent directory if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `filename` - The preference file name (e.g., "settings.plist", "config.json")
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pref_file = pref.pref_file("settings.plist")?;
    /// // On macOS: ~/Library/Preferences/com.example.myapp/settings.plist
    /// ```
    pub fn pref_file(&self, filename: &str) -> Result<PathBuf, StoreError> {
        Ok(self.pref_dir()?.join(filename))
    }

    /// Resolve the preference directory path based on OS.
    fn resolve_pref_dir(&self) -> Result<PathBuf, StoreError> {
        #[cfg(target_os = "macos")]
        {
            // macOS: ~/Library/Preferences
            let home = dirs::home_dir().ok_or(StoreError::HomeDirNotFound)?;
            Ok(home.join("Library/Preferences").join(&self.app_name))
        }

        #[cfg(not(target_os = "macos"))]
        {
            // Linux/Windows: Use OS-standard config directory
            let base = dirs::config_dir().ok_or(StoreError::HomeDirNotFound)?;
            Ok(base.join(&self.app_name))
        }
    }

    /// Ensure a directory exists, creating it if necessary.
    fn ensure_dir_exists(&self, path: &PathBuf) -> Result<(), StoreError> {
        if !path.exists() {
            std::fs::create_dir_all(path).map_err(|e| StoreError::IoError {
                operation: IoOperationKind::CreateDir,
                path: path.display().to_string(),
                context: None,
                error: e.to_string(),
            })?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_path_strategy_default() {
        assert_eq!(PathStrategy::default(), PathStrategy::System);
    }

    #[test]
    fn test_app_paths_new() {
        let paths = AppPaths::new("testapp");
        assert_eq!(paths.app_name, "testapp");
        assert_eq!(paths.config_strategy, PathStrategy::System);
        assert_eq!(paths.data_strategy, PathStrategy::System);
    }

    #[test]
    fn test_app_paths_builder() {
        let paths = AppPaths::new("testapp")
            .config_strategy(PathStrategy::Xdg)
            .data_strategy(PathStrategy::Xdg);

        assert_eq!(paths.config_strategy, PathStrategy::Xdg);
        assert_eq!(paths.data_strategy, PathStrategy::Xdg);
    }

    #[test]
    fn test_system_strategy_config_dir() {
        let paths = AppPaths::new("testapp").config_strategy(PathStrategy::System);
        let config_dir = paths.resolve_config_dir().unwrap();

        // Should end with app name
        assert!(config_dir.ends_with("testapp"));

        // On Unix-like systems, should be under config dir
        #[cfg(unix)]
        {
            let home = dirs::home_dir().unwrap();
            // macOS uses Library/Application Support, Linux uses .config
            assert!(
                config_dir.starts_with(home.join("Library/Application Support"))
                    || config_dir.starts_with(home.join(".config"))
            );
        }
    }

    #[test]
    fn test_xdg_strategy_config_dir() {
        let paths = AppPaths::new("testapp").config_strategy(PathStrategy::Xdg);
        let config_dir = paths.resolve_config_dir().unwrap();

        // Should be ~/.config/testapp on all platforms
        let home = dirs::home_dir().unwrap();
        assert_eq!(config_dir, home.join(".config/testapp"));
    }

    #[test]
    fn test_xdg_strategy_data_dir() {
        let paths = AppPaths::new("testapp").data_strategy(PathStrategy::Xdg);
        let data_dir = paths.resolve_data_dir().unwrap();

        // Should be ~/.local/share/testapp on all platforms
        let home = dirs::home_dir().unwrap();
        assert_eq!(data_dir, home.join(".local/share/testapp"));
    }

    #[test]
    fn test_custom_base_strategy() {
        let temp_dir = TempDir::new().unwrap();
        let custom_base = temp_dir.path().to_path_buf();

        let paths = AppPaths::new("testapp")
            .config_strategy(PathStrategy::CustomBase(custom_base.clone()))
            .data_strategy(PathStrategy::CustomBase(custom_base.clone()));

        let config_dir = paths.resolve_config_dir().unwrap();
        let data_dir = paths.resolve_data_dir().unwrap();

        assert_eq!(config_dir, custom_base.join("testapp"));
        assert_eq!(data_dir, custom_base.join("data/testapp"));
    }

    #[test]
    fn test_config_file() {
        let temp_dir = TempDir::new().unwrap();
        let custom_base = temp_dir.path().to_path_buf();

        let paths =
            AppPaths::new("testapp").config_strategy(PathStrategy::CustomBase(custom_base.clone()));

        let config_file = paths.config_file("config.toml").unwrap();
        assert_eq!(config_file, custom_base.join("testapp/config.toml"));

        // Verify directory was created
        assert!(custom_base.join("testapp").exists());
    }

    #[test]
    fn test_data_file() {
        let temp_dir = TempDir::new().unwrap();
        let custom_base = temp_dir.path().to_path_buf();

        let paths =
            AppPaths::new("testapp").data_strategy(PathStrategy::CustomBase(custom_base.clone()));

        let data_file = paths.data_file("cache.db").unwrap();
        assert_eq!(data_file, custom_base.join("data/testapp/cache.db"));

        // Verify directory was created
        assert!(custom_base.join("data/testapp").exists());
    }

    #[test]
    fn test_ensure_dir_exists() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("nested/test/path");

        let paths = AppPaths::new("testapp");
        paths.ensure_dir_exists(&test_path).unwrap();

        assert!(test_path.exists());
        assert!(test_path.is_dir());
    }

    #[test]
    fn test_multiple_calls_idempotent() {
        let temp_dir = TempDir::new().unwrap();
        let custom_base = temp_dir.path().to_path_buf();

        let paths =
            AppPaths::new("testapp").config_strategy(PathStrategy::CustomBase(custom_base.clone()));

        // Call config_dir multiple times
        let dir1 = paths.config_dir().unwrap();
        let dir2 = paths.config_dir().unwrap();
        let dir3 = paths.config_dir().unwrap();

        assert_eq!(dir1, dir2);
        assert_eq!(dir2, dir3);
    }

    // PrefPath tests
    #[test]
    fn test_pref_path_new() {
        let pref = PrefPath::new("com.example.testapp");
        assert_eq!(pref.app_name, "com.example.testapp");
    }

    #[test]
    fn test_pref_path_resolve_dir() {
        let pref = PrefPath::new("com.example.testapp");
        let pref_dir = pref.resolve_pref_dir().unwrap();

        // Should end with app name
        assert!(pref_dir.ends_with("com.example.testapp"));

        // Platform-specific checks
        #[cfg(target_os = "macos")]
        {
            let home = dirs::home_dir().unwrap();
            assert_eq!(
                pref_dir,
                home.join("Library/Preferences/com.example.testapp")
            );
        }

        #[cfg(all(unix, not(target_os = "macos")))]
        {
            let home = dirs::home_dir().unwrap();
            assert_eq!(pref_dir, home.join(".config/com.example.testapp"));
        }

        #[cfg(target_os = "windows")]
        {
            // On Windows, should use APPDATA
            assert!(pref_dir.to_string_lossy().contains("AppData"));
        }
    }

    #[test]
    fn test_pref_file() {
        let pref = PrefPath::new("com.example.testapp");
        let pref_file = pref.pref_file("settings.plist").unwrap();

        // Should end with the filename
        assert!(pref_file.ends_with("settings.plist"));

        // Should contain app name
        assert!(pref_file.to_string_lossy().contains("com.example.testapp"));

        #[cfg(target_os = "macos")]
        {
            let home = dirs::home_dir().unwrap();
            assert_eq!(
                pref_file,
                home.join("Library/Preferences/com.example.testapp/settings.plist")
            );
        }
    }

    #[test]
    fn test_pref_dir_creates_directory() {
        // This test would require mocking or a temp directory
        // For now, we just verify it doesn't panic with the real home dir
        let pref = PrefPath::new("test_version_migrate_pref");
        let pref_dir = pref.pref_dir().unwrap();

        // Clean up
        if pref_dir.exists() {
            let _ = std::fs::remove_dir_all(&pref_dir);
        }
    }

    #[test]
    fn test_pref_path_multiple_calls_idempotent() {
        let pref = PrefPath::new("test_version_migrate_pref2");

        let dir1 = pref.pref_dir().unwrap();
        let dir2 = pref.pref_dir().unwrap();
        let dir3 = pref.pref_dir().unwrap();

        assert_eq!(dir1, dir2);
        assert_eq!(dir2, dir3);

        // Clean up
        if dir1.exists() {
            let _ = std::fs::remove_dir_all(&dir1);
        }
    }
}