lds-core 0.13.1

Session state and configuration primitives for local-develop-server (lds)
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
//! First-class configuration for lds.
//!
//! Reads and writes `~/.config/lds/config.toml` (or an explicit path).
//! The primary design constraints are:
//!
//! 1. **patch-safe write** — `Config::save` uses `toml_edit` to update only
//!    the `recipes.dirs` array while preserving comments and unrelated sections.
//! 2. **tilde expansion** — any path stored on disk must be an absolute path;
//!    tilde literals are never written to `config.toml`.
//! 3. **shared file, decoupled schemas** — the same `config.toml` (both the
//!    user-global file and a session's project-local override) also carries
//!    `[[route]]` / `[[export]]` array-of-tables consumed by the `lds-router`
//!    crate (see `lds_router::RouteConfig` / `lds_router::ExportConfig`).
//!    `Config` has no `route` or `export` field and does not depend on
//!    `lds-router` — serde's default "ignore unrecognized keys" behavior
//!    (no `#[serde(deny_unknown_fields)]` here or on `lds_router`'s
//!    deserialization target) means each side parses the same file and
//!    silently skips the sections it does not own. This keeps the two crates
//!    decoupled while letting one physical file hold both.

use std::io;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use thiserror::Error;
use toml_edit::{Array, DocumentMut, Item, Value};

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors that can occur during config load or save operations.
#[derive(Debug, Error)]
pub enum ConfigError {
    /// An I/O error (e.g. permission denied, parent directory not found).
    #[error("config I/O error: {0}")]
    Io(#[from] io::Error),

    /// TOML deserialization error (returned by `Config::load`).
    #[error("config parse error: {0}")]
    Parse(#[from] toml::de::Error),

    /// `toml_edit` document-level error (returned by `Config::save`).
    #[error("config edit error: {0}")]
    Edit(#[from] toml_edit::TomlError),

    /// TOML serialization error.
    #[error("config serialize error: {0}")]
    Serialize(#[from] toml::ser::Error),
}

// ---------------------------------------------------------------------------
// Config structs
// ---------------------------------------------------------------------------

/// Top-level configuration for lds.
///
/// Deserializes from `~/.config/lds/config.toml`.  Missing sections fall back
/// to `Default` via `#[serde(default)]`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Config {
    /// Recipe directory settings.
    pub recipes: Recipes,
    /// Path overrides.
    pub paths: Paths,
}

/// Recipe-related configuration.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Recipes {
    /// Additional global recipe directories (highest priority source).
    ///
    /// Entries are absolute paths.  Tilde is expanded on load and must be
    /// absent from `config.toml` on disk.
    pub dirs: Vec<PathBuf>,
}

/// Path overrides for well-known lds locations.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Paths {
    /// Override for the global justfile path (default: `~/.config/lds/justfile`).
    pub global_justfile: Option<PathBuf>,
}

// ---------------------------------------------------------------------------
// tilde_expand
// ---------------------------------------------------------------------------

/// Expand a leading `~/` or lone `~` to the user's home directory.
///
/// # Arguments
///
/// * `input` — A path string that may start with `~/`.
///
/// # Returns
///
/// An absolute `PathBuf`.  If `input` does not start with `~/` or `~`, it is
/// returned as-is wrapped in `PathBuf`.
///
/// # Errors
///
/// Returns `ConfigError::Io(NotFound)` when the home directory cannot be
/// determined (e.g. `$HOME` is unset on Unix).
pub fn tilde_expand(input: &str) -> Result<PathBuf, ConfigError> {
    if input == "~" {
        let home = dirs::home_dir().ok_or_else(|| {
            ConfigError::Io(io::Error::new(io::ErrorKind::NotFound, "HOME not set"))
        })?;
        Ok(home)
    } else if let Some(rest) = input.strip_prefix("~/") {
        let home = dirs::home_dir().ok_or_else(|| {
            ConfigError::Io(io::Error::new(io::ErrorKind::NotFound, "HOME not set"))
        })?;
        Ok(home.join(rest))
    } else {
        Ok(PathBuf::from(input))
    }
}

// ---------------------------------------------------------------------------
// Config impl
// ---------------------------------------------------------------------------

/// Resolve the well-known path to the user-global config file
/// (`~/.config/lds/config.toml`).
///
/// Returns `None` if the home directory cannot be determined (e.g. `$HOME`
/// is unset). Shared by [`Config::load_or_default`] and by the `lds` binary
/// crate, which also points `lds_router::RouteConfig::load_all` at this same
/// path so `[[route]]` / `[[export]]` declarations live in the one file.
pub fn user_config_path() -> Option<PathBuf> {
    dirs::home_dir().map(|home| home.join(".config/lds/config.toml"))
}

impl Config {
    /// Load configuration from an explicit file path.
    ///
    /// # Arguments
    ///
    /// * `path` — Path to a TOML configuration file.
    ///
    /// # Returns
    ///
    /// A fully populated `Config`.  Missing optional sections are filled with
    /// `Default`.
    ///
    /// # Errors
    ///
    /// - `ConfigError::Io` if the file cannot be read.
    /// - `ConfigError::Parse` if the TOML is malformed.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        let content = std::fs::read_to_string(path)?;
        let config: Config = toml::from_str(&content)?;
        Ok(config)
    }

    /// Load configuration from the default path (`~/.config/lds/config.toml`).
    ///
    /// If the file does not exist this returns `Config::default()` silently.
    /// Any other I/O error or parse error is also silently swallowed and the
    /// default is returned — suitable for startup where a missing config is
    /// expected to be common.
    ///
    /// # Returns
    ///
    /// A `Config`, falling back to `Default` on any error.
    pub fn load_or_default() -> Self {
        let Some(path) = user_config_path() else {
            return Self::default();
        };
        match Self::load(&path) {
            Ok(cfg) => cfg,
            Err(ConfigError::Io(e)) if e.kind() == io::ErrorKind::NotFound => Self::default(),
            Err(e) => {
                tracing::warn!("failed to load config from {}: {}", path.display(), e);
                Self::default()
            }
        }
    }

    /// Save the `recipes.dirs` list to `path` using a **patch-safe** write.
    ///
    /// The file is parsed by `toml_edit` so that comments and sections not
    /// managed by this function (e.g. `[paths]`) are preserved verbatim.
    /// Only the `recipes.dirs` array is replaced.
    ///
    /// All paths in `dirs` must already be absolute (tilde-expanded before
    /// calling this function).  Passing a tilde literal is a logic error and
    /// will be written literally — callers are responsible for expanding first.
    ///
    /// If the parent directory does not exist it is created with
    /// `fs::create_dir_all`.
    ///
    /// # Arguments
    ///
    /// * `path` — Destination file (typically `~/.config/lds/config.toml`).
    /// * `dirs` — Absolute paths to persist in `recipes.dirs`.
    ///
    /// # Errors
    ///
    /// - `ConfigError::Io` for I/O failures (create dir, read, write).
    /// - `ConfigError::Edit` if the existing file is not valid TOML.
    pub fn save(path: &Path, dirs: &[PathBuf]) -> Result<(), ConfigError> {
        // Ensure parent directory exists.
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Read existing content (empty string when file is absent).
        let existing = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(),
            Err(e) => return Err(ConfigError::Io(e)),
        };

        // Parse with toml_edit to preserve comments and unrelated sections.
        let mut doc: DocumentMut = existing.parse::<DocumentMut>()?;

        // Build a fresh TOML array from `dirs`.
        let mut arr = Array::new();
        for dir in dirs {
            // Safety: PathBuf::to_string_lossy is infallible (may be lossy on
            // non-UTF-8 systems, but that is acceptable given TOML's UTF-8 requirement).
            arr.push(dir.to_string_lossy().as_ref());
        }

        // Write `recipes.dirs` — create intermediate tables as needed.
        if !doc.contains_table("recipes") {
            doc["recipes"] = toml_edit::table();
        }
        doc["recipes"]["dirs"] = Item::Value(Value::Array(arr));

        std::fs::write(path, doc.to_string())?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // ------------------------------------------------------------------
    // T1: happy-path / property tests
    // ------------------------------------------------------------------

    /// T1-a: round-trip — serialize a Config and read it back identically.
    #[test]
    fn test_round_trip_load_save() {
        let dir = TempDir::new().unwrap(); // justification: TempDir::new is infallible in practice; any failure surfaces as a test setup panic which is acceptable in test code
        let path = dir.path().join("config.toml");

        let other_root = TempDir::new().unwrap();
        let dirs_in = vec![
            dir.path().join("shared-recipes"),
            other_root.path().join("team-recipes"),
        ];

        Config::save(&path, &dirs_in).expect("save should succeed");
        let cfg = Config::load(&path).expect("load should succeed");

        assert_eq!(cfg.recipes.dirs, dirs_in);
    }

    /// T1-b: load_or_default returns Default when no file exists.
    #[test]
    fn test_load_or_default_missing_file() {
        // Temporarily override HOME to a directory with no config.toml.
        let dir = TempDir::new().unwrap(); // justification: same as above
        // We cannot easily unset HOME in a portable way, so we test Config::load
        // directly with a non-existent path to exercise the NotFound branch.
        let path = dir.path().join("nonexistent/config.toml");
        match Config::load(&path) {
            Err(ConfigError::Io(e)) => {
                assert_eq!(e.kind(), io::ErrorKind::NotFound);
            }
            other => panic!("expected Io(NotFound), got {:?}", other),
        }
    }

    /// T1-c0: `user_config_path` resolves to `<home>/.config/lds/config.toml`
    /// when the home directory is available.
    #[test]
    fn test_user_config_path_under_home() {
        let Some(home) = dirs::home_dir() else {
            return;
        };
        let path = user_config_path().expect("home dir is available in this test branch");
        assert_eq!(path, home.join(".config/lds/config.toml"));
    }

    /// T1-c: tilde_expand returns an absolute path for a ~/... input.
    #[test]
    fn test_tilde_expand_tilde_slash() {
        // Only run when HOME is available.
        if dirs::home_dir().is_none() {
            return;
        }
        let result = tilde_expand("~/foo/bar").expect("tilde_expand should succeed");
        let home = dirs::home_dir().unwrap(); // justification: we just checked it is Some above
        assert_eq!(result, home.join("foo/bar"));
    }

    /// T1-d: tilde_expand with bare `~`.
    #[test]
    fn test_tilde_expand_bare_tilde() {
        if dirs::home_dir().is_none() {
            return;
        }
        let result = tilde_expand("~").expect("bare tilde should expand");
        let home = dirs::home_dir().unwrap(); // justification: checked is Some above
        assert_eq!(result, home);
    }

    // ------------------------------------------------------------------
    // T2: boundary / edge-case tests
    // ------------------------------------------------------------------

    /// T2-a: empty dirs list produces empty `recipes.dirs` array.
    #[test]
    fn test_save_empty_dirs() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");

        Config::save(&path, &[]).expect("save should succeed");
        let cfg = Config::load(&path).expect("load should succeed");
        assert!(cfg.recipes.dirs.is_empty());
    }

    /// T2-b: load_or_default on truly missing file via `Config::load` NotFound.
    #[test]
    fn test_load_or_default_does_not_panic_on_missing() {
        // Exercise the public load_or_default by calling it; if HOME is not
        // set or the file is absent it returns Default without panic.
        let _cfg = Config::load_or_default();
        // No assertion needed — absence of panic is the contract.
    }

    /// T2-c: tilde_expand with no tilde passes through unchanged.
    #[test]
    fn test_tilde_expand_no_tilde() {
        let result = tilde_expand("/absolute/path").expect("should succeed");
        assert_eq!(result, PathBuf::from("/absolute/path"));
    }

    /// T2-d: tilde_expand with a relative path (no tilde) passes through.
    #[test]
    fn test_tilde_expand_relative() {
        let result = tilde_expand("relative/path").expect("should succeed");
        assert_eq!(result, PathBuf::from("relative/path"));
    }

    /// T2-e: Config::load on an empty file returns all-default values.
    #[test]
    fn test_load_empty_file() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");
        fs::write(&path, "").unwrap(); // justification: writing empty file in test, infallible on tempdir

        let cfg = Config::load(&path).expect("empty file should parse as default");
        assert!(cfg.recipes.dirs.is_empty());
        assert!(cfg.paths.global_justfile.is_none());
    }

    /// T2-f: Config::load on a file with only [paths] section (no [recipes]).
    #[test]
    fn test_load_partial_file_no_recipes() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");
        fs::write(&path, "[paths]\nglobal_justfile = \"/etc/lds/justfile\"\n").unwrap(); // justification: writing known-good TOML in test

        let cfg = Config::load(&path).expect("partial file should parse");
        assert!(
            cfg.recipes.dirs.is_empty(),
            "missing [recipes] should default to empty"
        );
        assert_eq!(
            cfg.paths.global_justfile,
            Some(PathBuf::from("/etc/lds/justfile"))
        );
    }

    /// T2-g: `Config::load` ignores `[[route]]` / `[[export]]` sections.
    ///
    /// `lds-router` parses these same array-of-tables out of the same
    /// physical `config.toml` (see the module doc comment's "shared file,
    /// decoupled schemas" note); `Config` has no `route`/`export` field, so
    /// this exercises serde's "unrecognized top-level keys are ignored"
    /// default behavior rather than a hard failure — this is the sole
    /// mechanism that lets the two crates share one file without either
    /// depending on the other's types.
    #[test]
    fn test_load_ignores_route_and_export_sections() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");
        fs::write(
            &path,
            r#"
[recipes]
dirs = ["/opt/shared-recipes"]

[[route]]
name = "outline"
command = "outline-mcp"

[[export]]
route = "outline"
tools = ["snapshot_create"]
"#,
        )
        .unwrap(); // justification: writing known-good TOML in test

        let cfg = Config::load(&path).expect("route/export sections must not fail Config parsing");
        assert_eq!(cfg.recipes.dirs, vec![PathBuf::from("/opt/shared-recipes")]);
    }

    // ------------------------------------------------------------------
    // T3: error-path tests
    // ------------------------------------------------------------------

    /// T3-a: Config::load on a non-existent path returns ConfigError::Io(NotFound).
    #[test]
    fn test_load_nonexistent_returns_io_not_found() {
        let result = Config::load(Path::new("/nonexistent/path/config.toml"));
        match result {
            Err(ConfigError::Io(e)) => {
                assert_eq!(e.kind(), io::ErrorKind::NotFound);
            }
            other => panic!("expected Io(NotFound), got {:?}", other),
        }
    }

    /// T3-b: Config::load on malformed TOML returns ConfigError::Parse.
    #[test]
    fn test_load_malformed_toml_returns_parse_error() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");
        fs::write(&path, "this is not = valid toml [\n").unwrap(); // justification: intentional bad TOML for error path test

        let result = Config::load(&path);
        assert!(
            matches!(result, Err(ConfigError::Parse(_))),
            "malformed TOML should yield Parse error, got {:?}",
            result
        );
    }

    // ------------------------------------------------------------------
    // Crux 2 preservation test: patch-safe write
    // ------------------------------------------------------------------

    /// Crux 2: `Config::save` must preserve comments and unrelated sections.
    ///
    /// This test writes a config.toml with a comment and `[paths]` section,
    /// then calls `Config::save` to update `recipes.dirs`, and asserts that
    /// the comment and `[paths]` section survive unmodified.
    #[test]
    fn test_save_preserves_comments_and_other_sections() {
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");

        // Seed file with a comment and [paths] section.
        let initial = r#"# This is a user comment that must survive.
[recipes]
dirs = []

[paths]
global_justfile = "/etc/lds/justfile"
"#;
        fs::write(&path, initial).unwrap(); // justification: seeding known-good TOML in test

        let new_dirs = vec![PathBuf::from("/opt/recipes")];
        Config::save(&path, &new_dirs).expect("save should succeed");

        let saved = fs::read_to_string(&path).unwrap(); // justification: reading back tempfile in test

        // Comment must be preserved.
        assert!(
            saved.contains("# This is a user comment that must survive."),
            "comment was not preserved:\n{}",
            saved
        );

        // [paths] section must be preserved.
        assert!(
            saved.contains("[paths]"),
            "[paths] section was not preserved:\n{}",
            saved
        );
        assert!(
            saved.contains("global_justfile"),
            "global_justfile key was not preserved:\n{}",
            saved
        );

        // recipes.dirs must be updated.
        let cfg = Config::load(&path).expect("load after save should succeed");
        assert_eq!(cfg.recipes.dirs, new_dirs);

        // Crux 2: tilde literal must not appear on disk.
        assert!(
            !saved.contains('~'),
            "tilde literal found on disk — crux 2 violation:\n{}",
            saved
        );
    }

    /// Crux 2 (tilde): paths saved to disk must be absolute (no tilde literal).
    #[test]
    fn test_save_does_not_write_tilde_literal() {
        if dirs::home_dir().is_none() {
            return;
        }
        let dir = TempDir::new().unwrap(); // justification: test setup
        let path = dir.path().join("config.toml");

        // Expand tilde before saving — as callers are required to do.
        let raw = "~/my-recipes";
        let expanded = tilde_expand(raw).expect("tilde_expand should succeed");
        assert!(
            !expanded.to_string_lossy().contains('~'),
            "expanded path must not contain tilde"
        );

        Config::save(&path, &[expanded]).expect("save should succeed");

        let saved = fs::read_to_string(&path).unwrap(); // justification: reading back tempfile in test
        assert!(
            !saved.contains('~'),
            "tilde literal found on disk after save — crux 2 violation:\n{}",
            saved
        );
    }
}