dotcfg 0.1.1

Flexible config management for Rust apps
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! # dotcfg
//!
//! Flexible config management for Rust apps.
//!
//! - Choose between `~/.toolname/` or `~/.config/toolname/`
//! - TOML, JSON or YAML format (feature-gated)
//! - Load, save, get, set — full or per-key
//! - Flat (`username`) and nested (`user.username`) key support
//! - Returns `None` if config doesn't exist — no magic auto-create unless you want it
//!
//! ## Features
//!
//! - `toml` (default) — enables TOML support
//! - `json` — enables JSON support
//! - `yaml` — enables YAML support
//!
//! ## Example
//!
//! ```rust,no_run
//! use dotcfg::DotCfg;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Default)]
//! struct MyConfig {
//!     username: String,
//!     port: u16,
//! }
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let cfg = DotCfg::new("mytool");
//!
//!     // Load — returns None if file doesn't exist
//!     let config: Option<MyConfig> = cfg.load()?;
//!
//!     // Save
//!     cfg.save(&MyConfig { username: "john".into(), port: 8080 })?;
//!
//!     // Get a single key
//!     let val = cfg.get("username")?;
//!
//!     // Set a single key
//!     cfg.set("username", "jane")?;
//!
//!     Ok(())
//! }
//! ```

pub mod error;

use std::{fs, path::PathBuf};

use error::DotCfgError;
use serde::{Deserialize, Serialize};

#[cfg(not(any(feature = "toml", feature = "json", feature = "yaml")))]
compile_error!(
    "dotcfg requires at least one of the `toml`, `json` or `yaml` features to be enabled"
);

/// Where the config folder lives
pub enum DirStrategy {
    /// `~/.toolname/` — like `.cargo`, `.ssh`, `.git`
    Dot,
    /// `~/.config/toolname/` — XDG standard
    Xdg,
}

/// Config file format
pub enum Format {
    #[cfg(feature = "toml")]
    Toml,
    #[cfg(feature = "json")]
    Json,
    #[cfg(feature = "yaml")]
    Yaml,
}

/// The main dotcfg handle. Create one per app.
///
/// ```rust,no_run
/// use dotcfg::DotCfg;
///
/// // ~/.mytool/config.toml (default)
/// let cfg = DotCfg::new("mytool");
///
/// // ~/.config/mytool/config.toml
/// let cfg = DotCfg::new("mytool").xdg();
///
/// // ~/.mytool/settings.json (requires `json` feature)
/// #[cfg(feature = "json")]
/// let cfg = DotCfg::new("mytool").json().filename("settings");
///
/// // ~/.mytool/config.yaml (requires `yaml` feature)
/// #[cfg(feature = "yaml")]
/// let cfg = DotCfg::new("mytool").yaml();
/// ```
pub struct DotCfg {
    app_name: String,
    strategy: DirStrategy,
    format: Format,
    filename: String,
}

impl DotCfg {
    /// Create a new DotCfg for your app.
    /// Defaults: `~/.appname/config.toml`, no auto-create.
    pub fn new(app_name: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
            strategy: DirStrategy::Dot,
            #[cfg(feature = "toml")]
            format: Format::Toml,
            #[cfg(all(feature = "json", not(feature = "toml")))]
            format: Format::Json,
            #[cfg(all(feature = "yaml", not(feature = "toml"), not(feature = "json")))]
            format: Format::Yaml,
            filename: "config".to_string(),
        }
    }

    /// Use `~/.config/toolname/` (XDG)
    pub fn xdg(mut self) -> Self {
        self.strategy = DirStrategy::Xdg;
        self
    }

    /// Use `~/.toolname/` (default)
    pub fn dot(mut self) -> Self {
        self.strategy = DirStrategy::Dot;
        self
    }

    /// Use JSON format
    #[cfg(feature = "json")]
    pub fn json(mut self) -> Self {
        self.format = Format::Json;
        self
    }

    /// Use YAML format
    #[cfg(feature = "yaml")]
    pub fn yaml(mut self) -> Self {
        self.format = Format::Yaml;
        self
    }

    /// Use TOML format (default)
    #[cfg(feature = "toml")]
    pub fn toml(mut self) -> Self {
        self.format = Format::Toml;
        self
    }

    /// Set the config filename (without extension). Default is `"config"`.
    pub fn filename(mut self, name: impl Into<String>) -> Self {
        self.filename = name.into();
        self
    }

    /// Returns the config directory path
    pub fn dir(&self) -> Result<PathBuf, DotCfgError> {
        let dir = match self.strategy {
            DirStrategy::Dot => {
                // ~/.toolname/ — Unix convention, we resolve manually
                let home = home::home_dir().ok_or(DotCfgError::NoHomeDir)?;
                home.join(format!(".{}", self.app_name))
            }
            DirStrategy::Xdg => {
                // Uses etcetera — handles Linux (XDG), macOS, Windows correctly
                use etcetera::app_strategy::{AppStrategy, AppStrategyArgs, Xdg};
                let strategy = Xdg::new(AppStrategyArgs {
                    top_level_domain: "".to_string(),
                    author: "".to_string(),
                    app_name: self.app_name.clone(),
                })
                .map_err(|_| DotCfgError::NoHomeDir)?;
                strategy.config_dir()
            }
        };
        Ok(dir)
    }

    /// Returns the full config file path
    pub fn file_path(&self) -> Result<PathBuf, DotCfgError> {
        let ext = match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => "toml",
            #[cfg(feature = "json")]
            Format::Json => "json",
            #[cfg(feature = "yaml")]
            Format::Yaml => "yaml",
        };
        Ok(self.dir()?.join(format!("{}.{}", self.filename, ext)))
    }

    /// Returns true if the config file exists
    pub fn exists(&self) -> Result<bool, DotCfgError> {
        Ok(self.file_path()?.exists())
    }

    /// Ensures the config directory exists, creating it if needed
    fn ensure_dir(&self) -> Result<(), DotCfgError> {
        let dir = self.dir()?;
        if !dir.exists() {
            fs::create_dir_all(&dir)?;
        }
        Ok(())
    }

    /// Load the config file.
    ///
    /// Returns `None` if the file doesn't exist — no auto-create.
    /// Use [`Self::load_or_default`] if you want auto-create behavior.
    pub fn load<T>(&self) -> Result<Option<T>, DotCfgError>
    where
        T: for<'de> Deserialize<'de>,
    {
        let path = self.file_path()?;

        if !path.exists() {
            return Ok(None);
        }

        let content = fs::read_to_string(&path)?;

        let config = match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => toml::from_str(&content)?,
            #[cfg(feature = "json")]
            Format::Json => serde_json::from_str(&content)?,
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::from_str(&content)?,
        };

        Ok(Some(config))
    }

    /// Load the config or return an error if it doesn't exist.
    ///
    /// Useful when your CLI requires setup before use.
    pub fn load_or_error<T>(&self) -> Result<T, DotCfgError>
    where
        T: for<'de> Deserialize<'de>,
    {
        self.load()?.ok_or(DotCfgError::NotFound)
    }

    /// Load the config or create it with default values if it doesn't exist.
    ///
    /// This is the confy-style behavior — opt-in.
    pub fn load_or_default<T>(&self) -> Result<T, DotCfgError>
    where
        T: for<'de> Deserialize<'de> + Serialize + Default,
    {
        match self.load()? {
            Some(cfg) => Ok(cfg),
            None => {
                let default = T::default();
                self.save(&default)?;
                Ok(default)
            }
        }
    }

    /// Save a config struct to disk.
    ///
    /// Creates the config directory if it doesn't exist.
    pub fn save<T: Serialize>(&self, config: &T) -> Result<(), DotCfgError> {
        self.ensure_dir()?;
        let path = self.file_path()?;

        let content = match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => toml::to_string_pretty(config)?,
            #[cfg(feature = "json")]
            Format::Json => serde_json::to_string_pretty(config)?,
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::to_string(config)?,
        };

        fs::write(&path, content)?;
        Ok(())
    }

    /// Get a single config value by key.
    ///
    /// Supports flat keys (`"username"`) and nested keys (`"user.username"`).
    ///
    /// Returns the value as a `String`.
    pub fn get(&self, key: &str) -> Result<String, DotCfgError> {
        let path = self.file_path()?;

        if !path.exists() {
            return Err(DotCfgError::NotFound);
        }

        let content = fs::read_to_string(&path)?;

        match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => {
                let value: toml::Value = toml::from_str(&content)?;
                get_toml_value(&value, key)
            }
            #[cfg(feature = "json")]
            Format::Json => {
                let value: serde_json::Value = serde_json::from_str(&content)?;
                get_json_value(&value, key)
            }
            #[cfg(feature = "yaml")]
            Format::Yaml => {
                let value: serde_yaml::Value = serde_yaml::from_str(&content)?;
                get_yaml_value(&value, key)
            }
        }
    }

    /// Set a single config value by key.
    ///
    /// Supports flat keys (`"username"`) and nested keys (`"user.username"`).
    ///
    /// Creates the config file and directory if they don't exist.
    /// If the file exists, only the specified key is updated — everything else is preserved.
    pub fn set(&self, key: &str, value: &str) -> Result<(), DotCfgError> {
        let path = self.file_path()?;

        match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => {
                let mut table: toml::Value = if path.exists() {
                    let content = fs::read_to_string(&path)?;
                    toml::from_str(&content)?
                } else {
                    toml::Value::Table(toml::map::Map::new())
                };

                set_toml_value(&mut table, key, value)?;
                self.ensure_dir()?;
                fs::write(&path, toml::to_string_pretty(&table)?)?;
            }
            #[cfg(feature = "json")]
            Format::Json => {
                let mut json: serde_json::Value = if path.exists() {
                    let content = fs::read_to_string(&path)?;
                    serde_json::from_str(&content)?
                } else {
                    serde_json::Value::Object(serde_json::Map::new())
                };

                set_json_value(&mut json, key, value)?;
                self.ensure_dir()?;
                fs::write(&path, serde_json::to_string_pretty(&json)?)?;
            }
            #[cfg(feature = "yaml")]
            Format::Yaml => {
                let mut yaml: serde_yaml::Value = if path.exists() {
                    let content = fs::read_to_string(&path)?;
                    serde_yaml::from_str(&content)?
                } else {
                    serde_yaml::Value::Mapping(serde_yaml::Mapping::new())
                };

                set_yaml_value(&mut yaml, key, value)?;
                self.ensure_dir()?;
                fs::write(&path, serde_yaml::to_string(&yaml)?)?;
            }
        }

        Ok(())
    }

    /// Delete the config file. The directory is kept.
    pub fn delete_file(&self) -> Result<(), DotCfgError> {
        let path = self.file_path()?;
        if path.exists() {
            fs::remove_file(path)?;
        }
        Ok(())
    }

    /// Delete the entire config directory and all its contents.
    pub fn delete_dir(&self) -> Result<(), DotCfgError> {
        let dir = self.dir()?;
        if dir.exists() {
            fs::remove_dir_all(dir)?;
        }
        Ok(())
    }
}

// TOML helpers

#[cfg(feature = "toml")]
fn get_toml_value(value: &toml::Value, key: &str) -> Result<String, DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();

    match parts.as_slice() {
        [field] => value
            .get(field)
            .map(toml_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        [section, field] => value
            .get(section)
            .and_then(|s| s.get(field))
            .map(toml_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        _ => Err(DotCfgError::InvalidKey(key.to_string())),
    }
}

#[cfg(feature = "toml")]
fn set_toml_value(value: &mut toml::Value, key: &str, new_val: &str) -> Result<(), DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();
    let table = value
        .as_table_mut()
        .ok_or_else(|| DotCfgError::NotATable("root".to_string()))?;

    match parts.as_slice() {
        [field] => {
            table.insert(field.to_string(), toml::Value::String(new_val.to_string()));
        }
        [section, field] => {
            let section_val = table
                .entry(section.to_string())
                .or_insert_with(|| toml::Value::Table(toml::map::Map::new()));

            let section_table = section_val
                .as_table_mut()
                .ok_or_else(|| DotCfgError::NotATable(section.to_string()))?;

            section_table.insert(field.to_string(), toml::Value::String(new_val.to_string()));
        }
        _ => return Err(DotCfgError::InvalidKey(key.to_string())),
    }

    Ok(())
}

#[cfg(feature = "toml")]
fn toml_val_to_string(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => s.clone(),
        toml::Value::Integer(i) => i.to_string(),
        toml::Value::Float(f) => f.to_string(),
        toml::Value::Boolean(b) => b.to_string(),
        toml::Value::Datetime(d) => d.to_string(),
        toml::Value::Array(a) => {
            toml::to_string(&toml::Value::Array(a.clone())).unwrap_or_default()
        }
        toml::Value::Table(t) => toml::to_string(t).unwrap_or_default(),
    }
}

// JSON helpers
#[cfg(feature = "json")]
fn get_json_value(value: &serde_json::Value, key: &str) -> Result<String, DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();

    match parts.as_slice() {
        [field] => value
            .get(field)
            .map(json_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        [section, field] => value
            .get(section)
            .and_then(|s| s.get(field))
            .map(json_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        _ => Err(DotCfgError::InvalidKey(key.to_string())),
    }
}

#[cfg(feature = "json")]
fn set_json_value(
    value: &mut serde_json::Value,
    key: &str,
    new_val: &str,
) -> Result<(), DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();
    let obj = value
        .as_object_mut()
        .ok_or_else(|| DotCfgError::NotATable("root".to_string()))?;

    match parts.as_slice() {
        [field] => {
            obj.insert(
                field.to_string(),
                serde_json::Value::String(new_val.to_string()),
            );
        }
        [section, field] => {
            let section_val = obj
                .entry(section.to_string())
                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));

            let section_obj = section_val
                .as_object_mut()
                .ok_or_else(|| DotCfgError::NotATable(section.to_string()))?;

            section_obj.insert(
                field.to_string(),
                serde_json::Value::String(new_val.to_string()),
            );
        }
        _ => return Err(DotCfgError::InvalidKey(key.to_string())),
    }

    Ok(())
}

#[cfg(feature = "json")]
fn json_val_to_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            serde_json::to_string(value).unwrap_or_default()
        }
    }
}

// YAML helpers
#[cfg(feature = "yaml")]
fn get_yaml_value(value: &serde_yaml::Value, key: &str) -> Result<String, DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();

    match parts.as_slice() {
        [field] => value
            .get(field)
            .map(yaml_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        [section, field] => value
            .get(section)
            .and_then(|s| s.get(field))
            .map(yaml_val_to_string)
            .ok_or_else(|| DotCfgError::KeyNotFound(key.to_string())),

        _ => Err(DotCfgError::InvalidKey(key.to_string())),
    }
}

#[cfg(feature = "yaml")]
fn set_yaml_value(
    value: &mut serde_yaml::Value,
    key: &str,
    new_val: &str,
) -> Result<(), DotCfgError> {
    let parts: Vec<&str> = key.splitn(2, '.').collect();
    let map = value
        .as_mapping_mut()
        .ok_or_else(|| DotCfgError::NotATable("root".to_string()))?;

    match parts.as_slice() {
        [field] => {
            map.insert(
                serde_yaml::Value::String(field.to_string()),
                serde_yaml::Value::String(new_val.to_string()),
            );
        }
        [section, field] => {
            let section_val = map
                .entry(serde_yaml::Value::String(section.to_string()))
                .or_insert_with(|| serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));

            let section_map = section_val
                .as_mapping_mut()
                .ok_or_else(|| DotCfgError::NotATable(section.to_string()))?;

            section_map.insert(
                serde_yaml::Value::String(field.to_string()),
                serde_yaml::Value::String(new_val.to_string()),
            );
        }
        _ => return Err(DotCfgError::InvalidKey(key.to_string())),
    }

    Ok(())
}

#[cfg(feature = "yaml")]
fn yaml_val_to_string(value: &serde_yaml::Value) -> String {
    match value {
        serde_yaml::Value::String(s) => s.clone(),
        serde_yaml::Value::Number(n) => n.to_string(),
        serde_yaml::Value::Bool(b) => b.to_string(),
        serde_yaml::Value::Null => "null".to_string(),
        // Sequences, mappings and tagged values are re-emitted as YAML;
        // `to_string` appends a trailing newline we don't want in a `get()` result.
        _ => serde_yaml::to_string(value)
            .unwrap_or_default()
            .trim_end()
            .to_string(),
    }
}

// Unit tests for private helpers
#[cfg(test)]
mod unit_tests {
    use super::*;

    #[cfg(feature = "toml")]
    #[test]
    fn toml_val_to_string_variants() {
        // `get()` returns String for all types, so non-strings are stringified
        assert_eq!(toml_val_to_string(&toml::Value::String("hi".into())), "hi");
        assert_eq!(toml_val_to_string(&toml::Value::Integer(42)), "42");
        assert_eq!(toml_val_to_string(&toml::Value::Boolean(true)), "true");
    }

    #[cfg(feature = "toml")]
    #[test]
    fn get_set_toml_helper() {
        // Helpers are tested in-memory to avoid creating temp files
        // and to keep tests fast and isolated from the filesystem.
        let mut val = toml::Value::Table(toml::map::Map::new());
        set_toml_value(&mut val, "username", "tayo").unwrap();
        assert_eq!(get_toml_value(&val, "username").unwrap(), "tayo");
        set_toml_value(&mut val, "user.username", "jane").unwrap();
        assert_eq!(get_toml_value(&val, "user.username").unwrap(), "jane");
        assert!(get_toml_value(&val, "missing").is_err());
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_val_to_string_variants() {
        assert_eq!(
            json_val_to_string(&serde_json::Value::String("hi".into())),
            "hi"
        );
        assert_eq!(
            json_val_to_string(&serde_json::Value::Number(42.into())),
            "42"
        );
        assert_eq!(json_val_to_string(&serde_json::Value::Bool(false)), "false");
    }

    #[cfg(feature = "json")]
    #[test]
    fn get_set_json_helper() {
        let mut val = serde_json::Value::Object(serde_json::Map::new());
        set_json_value(&mut val, "username", "tayo").unwrap();
        assert_eq!(get_json_value(&val, "username").unwrap(), "tayo");
        set_json_value(&mut val, "user.username", "jane").unwrap();
        assert_eq!(get_json_value(&val, "user.username").unwrap(), "jane");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn yaml_val_to_string_variants() {
        assert_eq!(
            yaml_val_to_string(&serde_yaml::Value::String("hi".into())),
            "hi"
        );
        assert_eq!(
            yaml_val_to_string(&serde_yaml::Value::Number(42.into())),
            "42"
        );
        assert_eq!(yaml_val_to_string(&serde_yaml::Value::Bool(false)), "false");
        assert_eq!(yaml_val_to_string(&serde_yaml::Value::Null), "null");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn get_set_yaml_helper() {
        let mut val = serde_yaml::Value::Mapping(serde_yaml::Mapping::new());
        set_yaml_value(&mut val, "username", "tayo").unwrap();
        assert_eq!(get_yaml_value(&val, "username").unwrap(), "tayo");
        set_yaml_value(&mut val, "user.username", "jane").unwrap();
        assert_eq!(get_yaml_value(&val, "user.username").unwrap(), "jane");
        assert!(get_yaml_value(&val, "missing").is_err());
    }
}