reovim-kernel 0.14.4

Core kernel mechanisms for reovim (Linux kernel/ equivalent)
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
//! Configuration mechanism for kernel.
//!
//! Linux equivalent: `/proc/sys/` + configuration subsystem
//!
//! This module provides the **MECHANISM** for configuration storage.
//! **POLICY** (what to store, validation rules) belongs in modules.
//!
//! # Design
//!
//! - `ConfigValue`: Type-safe primitive values (bool, int, string, array, table)
//! - `Config`: Thread-safe key-value store with flat key access
//! - `ConfigPaths`: XDG-compliant path resolution for config/data/cache directories
//! - `ConfigError`: Error types for config operations
//!
//! # TOML Parsing
//!
//! The kernel does NOT parse TOML directly (no serde dependency).
//! TOML parsing is provided by modules (not the kernel).
//! See [`archive/pre_kernel/lib/core/src/config/loader.rs`](https://github.com/ds1sqe/reovim/blob/81806439/archive/pre_kernel/lib/core/src/config/loader.rs) for the original implementation.
//! This keeps the kernel dependency-free and policy-agnostic.
//!
//! # Example
//!
//! ```ignore
//! use reovim_kernel::api::v1::{Config, ConfigValue, ConfigPaths};
//!
//! let config = Config::new();
//!
//! // Set values
//! config.set_str("editor.theme", "dark");
//! config.set_int("editor.tabwidth", 4);
//! config.set_bool("editor.number", true);
//!
//! // Get values
//! assert_eq!(config.get_str("editor.theme"), Some("dark".to_string()));
//! assert_eq!(config.get_int("editor.tabwidth"), Some(4));
//!
//! // Get config paths
//! let config_file = ConfigPaths::config_file()?;
//! ```

use std::{collections::HashMap, fmt, path::PathBuf};

use reovim_arch::sync::RwLock;

// ============================================================================
// ConfigValue - Type-safe configuration values
// ============================================================================

/// Type-safe configuration value.
///
/// This is a kernel-level primitive for configuration storage.
/// Higher layers (`OptionRegistry`, `ProfileManager`) add validation
/// and metadata on top.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigValue {
    /// Boolean value.
    Bool(bool),
    /// Integer value (i64 for flexibility).
    Integer(i64),
    /// String value.
    String(String),
    /// Array of values (homogeneous).
    Array(Vec<Self>),
    /// Nested table/section.
    Table(HashMap<String, Self>),
}

impl ConfigValue {
    /// Get the type name for error messages.
    #[must_use]
    pub const fn type_name(&self) -> &'static str {
        match self {
            Self::Bool(_) => "bool",
            Self::Integer(_) => "integer",
            Self::String(_) => "string",
            Self::Array(_) => "array",
            Self::Table(_) => "table",
        }
    }

    /// Try to get as boolean.
    #[must_use]
    pub const fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Try to get as integer.
    #[must_use]
    pub const fn as_int(&self) -> Option<i64> {
        match self {
            Self::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Try to get as string reference.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// Try to get as array reference.
    #[must_use]
    pub fn as_array(&self) -> Option<&[Self]> {
        match self {
            Self::Array(a) => Some(a),
            _ => None,
        }
    }

    /// Try to get as table reference.
    #[must_use]
    pub const fn as_table(&self) -> Option<&HashMap<String, Self>> {
        match self {
            Self::Table(t) => Some(t),
            _ => None,
        }
    }

    /// Try to get as mutable table reference.
    #[must_use]
    pub const fn as_table_mut(&mut self) -> Option<&mut HashMap<String, Self>> {
        match self {
            Self::Table(t) => Some(t),
            _ => None,
        }
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl fmt::Display for ConfigValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(b) => write!(f, "{b}"),
            Self::Integer(i) => write!(f, "{i}"),
            Self::String(s) => write!(f, "{s}"),
            Self::Array(arr) => write!(f, "[{} items]", arr.len()),
            Self::Table(t) => write!(f, "{{{} entries}}", t.len()),
        }
    }
}

// Convenient From implementations
#[cfg_attr(coverage_nightly, coverage(off))]
impl From<bool> for ConfigValue {
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl From<i64> for ConfigValue {
    fn from(i: i64) -> Self {
        Self::Integer(i)
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl From<i32> for ConfigValue {
    fn from(i: i32) -> Self {
        Self::Integer(i64::from(i))
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl From<String> for ConfigValue {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl From<&str> for ConfigValue {
    fn from(s: &str) -> Self {
        Self::String(s.to_string())
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl<T: Into<Self>> From<Vec<T>> for ConfigValue {
    fn from(v: Vec<T>) -> Self {
        Self::Array(v.into_iter().map(Into::into).collect())
    }
}

// ============================================================================
// ConfigError - Error types
// ============================================================================

/// Errors that can occur during configuration operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// Key not found in configuration.
    NotFound(String),
    /// Type mismatch when accessing value.
    TypeMismatch {
        /// The key that was accessed
        key: String,
        /// Expected type
        expected: &'static str,
        /// Actual type
        got: &'static str,
    },
    /// Path-related error (missing home, invalid path).
    PathError(String),
    /// IO error (file not found, permission denied).
    Io(String),
    /// Parse error (invalid format).
    Parse(String),
    /// Serialization error.
    Serialize(String),
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFound(key) => write!(f, "config key not found: {key}"),
            Self::TypeMismatch { key, expected, got } => {
                write!(f, "type mismatch for '{key}': expected {expected}, got {got}")
            }
            Self::PathError(msg) => write!(f, "path error: {msg}"),
            Self::Io(msg) => write!(f, "IO error: {msg}"),
            Self::Parse(msg) => write!(f, "parse error: {msg}"),
            Self::Serialize(msg) => write!(f, "serialize error: {msg}"),
        }
    }
}

impl std::error::Error for ConfigError {}

// ============================================================================
// Config - Thread-safe configuration store
// ============================================================================

/// Thread-safe configuration store.
///
/// Provides flat key-value storage with type-safe accessors.
/// Keys use dot notation for logical grouping: `editor.theme`, `plugin.lsp.timeout`
///
/// # Thread Safety
///
/// All operations are thread-safe via internal `RwLock`.
/// Multiple readers allowed, single writer for mutations.
///
/// # Example
///
/// ```ignore
/// use reovim_kernel::api::v1::{Config, ConfigValue};
///
/// let config = Config::new();
///
/// // Set values
/// config.set_str("editor.theme", "dark");
/// config.set_int("editor.tabwidth", 4);
///
/// // Get values
/// assert_eq!(config.get_str("editor.theme"), Some("dark".to_string()));
/// assert_eq!(config.get_int("editor.tabwidth"), Some(4));
/// ```
#[derive(Debug, Default)]
pub struct Config {
    /// Root configuration data (flat key-value store).
    data: RwLock<HashMap<String, ConfigValue>>,
    /// Associated file path (if loaded from file).
    path: RwLock<Option<PathBuf>>,
}

impl Config {
    /// Create a new empty configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a configuration with an associated file path.
    #[must_use]
    pub fn with_path(path: PathBuf) -> Self {
        Self {
            data: RwLock::new(HashMap::new()),
            path: RwLock::new(Some(path)),
        }
    }

    /// Get the associated file path.
    #[must_use]
    pub fn path(&self) -> Option<PathBuf> {
        self.path.read().clone()
    }

    /// Set the associated file path.
    pub fn set_path(&self, path: PathBuf) {
        *self.path.write() = Some(path);
    }

    // ========================================================================
    // Get operations
    // ========================================================================

    /// Get a configuration value by key.
    ///
    /// Keys use dot notation: `editor.theme`, `plugin.lsp.timeout`
    #[must_use]
    pub fn get(&self, key: &str) -> Option<ConfigValue> {
        let data = self.data.read();
        data.get(key).cloned()
    }

    /// Get a boolean value.
    #[must_use]
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        self.get(key).and_then(|v| v.as_bool())
    }

    /// Get an integer value.
    #[must_use]
    pub fn get_int(&self, key: &str) -> Option<i64> {
        self.get(key).and_then(|v| v.as_int())
    }

    /// Get a string value.
    #[must_use]
    pub fn get_str(&self, key: &str) -> Option<String> {
        self.get(key).and_then(|v| v.as_str().map(String::from))
    }

    /// Get a value with a default fallback.
    #[must_use]
    pub fn get_or(&self, key: &str, default: ConfigValue) -> ConfigValue {
        self.get(key).unwrap_or(default)
    }

    /// Get a boolean with a default.
    #[must_use]
    pub fn get_bool_or(&self, key: &str, default: bool) -> bool {
        self.get_bool(key).unwrap_or(default)
    }

    /// Get an integer with a default.
    #[must_use]
    pub fn get_int_or(&self, key: &str, default: i64) -> i64 {
        self.get_int(key).unwrap_or(default)
    }

    /// Get a string with a default.
    #[must_use]
    pub fn get_str_or(&self, key: &str, default: &str) -> String {
        self.get_str(key).unwrap_or_else(|| default.to_string())
    }

    // ========================================================================
    // Set operations
    // ========================================================================

    /// Set a configuration value.
    ///
    /// Keys use dot notation. Previous value is overwritten.
    pub fn set(&self, key: &str, value: ConfigValue) {
        let mut data = self.data.write();
        data.insert(key.to_string(), value);
    }

    /// Set a boolean value.
    pub fn set_bool(&self, key: &str, value: bool) {
        self.set(key, ConfigValue::Bool(value));
    }

    /// Set an integer value.
    pub fn set_int(&self, key: &str, value: i64) {
        self.set(key, ConfigValue::Integer(value));
    }

    /// Set a string value.
    pub fn set_str(&self, key: &str, value: impl Into<String>) {
        self.set(key, ConfigValue::String(value.into()));
    }

    // ========================================================================
    // Bulk operations
    // ========================================================================

    /// Remove a configuration key.
    ///
    /// Returns the removed value if it existed.
    pub fn remove(&self, key: &str) -> Option<ConfigValue> {
        let mut data = self.data.write();
        data.remove(key)
    }

    /// Check if a key exists.
    #[must_use]
    pub fn contains(&self, key: &str) -> bool {
        let data = self.data.read();
        data.contains_key(key)
    }

    /// Get all keys.
    #[must_use]
    pub fn keys(&self) -> Vec<String> {
        let data = self.data.read();
        data.keys().cloned().collect()
    }

    /// Get all keys matching a prefix.
    #[must_use]
    pub fn keys_with_prefix(&self, prefix: &str) -> Vec<String> {
        let data = self.data.read();
        data.keys()
            .filter(|k| k.starts_with(prefix))
            .cloned()
            .collect()
    }

    /// Clear all configuration data.
    pub fn clear(&self) {
        let mut data = self.data.write();
        data.clear();
    }

    /// Get the number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        let data = self.data.read();
        data.len()
    }

    /// Check if empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        let data = self.data.read();
        data.is_empty()
    }

    /// Merge another config into this one.
    ///
    /// Values from `other` overwrite values in `self`.
    pub fn merge(&self, other: &Self) {
        let other_data = other.data.read();
        let mut self_data = self.data.write();

        for (key, value) in other_data.iter() {
            self_data.insert(key.clone(), value.clone());
        }
    }

    /// Export all data as a `HashMap`.
    #[must_use]
    pub fn to_map(&self) -> HashMap<String, ConfigValue> {
        let data = self.data.read();
        data.clone()
    }

    /// Import data from a `HashMap`.
    pub fn from_map(&self, map: HashMap<String, ConfigValue>) {
        let mut data = self.data.write();
        *data = map;
    }
}

// ============================================================================
// ConfigPaths - XDG-compliant path resolution
// ============================================================================

/// Configuration path utilities.
///
/// Uses `reovim-arch::dirs` for platform-agnostic path resolution.
/// Follows XDG Base Directory Specification on Unix.
///
/// # Environment Variable Overrides
///
/// All paths can be overridden via environment variables for worktree
/// isolation and testing:
///
/// | Variable | Overrides | Purpose |
/// |----------|-----------|---------|
/// | `REOVIM_CONFIG_DIR` | `config_dir()` | User config (modules.toml, profiles) |
/// | `REOVIM_DATA_DIR` | `data_dir()` | Runtime data (.so modules, lock files, logs) |
/// | `REOVIM_CACHE_DIR` | `cache_dir()` | Cache (derived from data if unset) |
///
/// Resolution order: `$REOVIM_*_DIR` > XDG/platform default.
pub struct ConfigPaths;

impl ConfigPaths {
    /// Get the reovim config directory.
    ///
    /// Resolution: `$REOVIM_CONFIG_DIR` > `$XDG_CONFIG_HOME/reovim` > `~/.config/reovim`
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::PathError` if the config directory cannot be determined
    /// and no env override is set.
    pub fn config_dir() -> Result<PathBuf, ConfigError> {
        Self::resolve_dir(
            std::env::var("REOVIM_CONFIG_DIR").ok(),
            reovim_arch::dirs::config_dir(),
            "config",
        )
    }

    /// Get the reovim data directory.
    ///
    /// Resolution: `$REOVIM_DATA_DIR` > `$XDG_DATA_HOME/reovim` > `~/.local/share/reovim`
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::PathError` if the data directory cannot be determined
    /// and no env override is set.
    pub fn data_dir() -> Result<PathBuf, ConfigError> {
        Self::resolve_dir(
            std::env::var("REOVIM_DATA_DIR").ok(),
            reovim_arch::dirs::data_local_dir(),
            "data",
        )
    }

    /// Get the reovim cache directory.
    ///
    /// Resolution: `$REOVIM_CACHE_DIR` > `$XDG_CACHE_HOME/reovim` > `~/.cache/reovim`
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::PathError` if the cache directory cannot be determined
    /// and no env override is set.
    pub fn cache_dir() -> Result<PathBuf, ConfigError> {
        Self::resolve_dir(
            std::env::var("REOVIM_CACHE_DIR").ok(),
            reovim_arch::dirs::cache_dir(),
            "cache",
        )
    }

    /// Resolve a directory path from env override or platform default.
    ///
    /// This is the pure testable core of the path resolution logic.
    /// The env override takes priority; if absent, the platform default
    /// is used with `/reovim` appended.
    fn resolve_dir(
        env_override: Option<String>,
        platform_default: Option<PathBuf>,
        kind: &str,
    ) -> Result<PathBuf, ConfigError> {
        if let Some(dir) = env_override {
            return Ok(PathBuf::from(dir));
        }
        platform_default
            .map(|p| p.join("reovim"))
            .ok_or_else(|| ConfigError::PathError(format!("cannot determine {kind} directory")))
    }

    /// Get the path to the main config file.
    ///
    /// Returns `{config_dir}/config.toml`
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::PathError` if the config directory cannot be determined.
    pub fn config_file() -> Result<PathBuf, ConfigError> {
        Self::config_dir().map(|p| p.join("config.toml"))
    }

    /// Get the profiles directory.
    ///
    /// Returns `{config_dir}/profiles/`
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::PathError` if the config directory cannot be determined.
    pub fn profiles_dir() -> Result<PathBuf, ConfigError> {
        Self::config_dir().map(|p| p.join("profiles"))
    }
}

#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;