dodot-lib 0.10.0

Core library for dodot dotfiles manager
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
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::datastore::{CommandRunner, DataStore};
use crate::fs::Fs;
use crate::paths::Pather;
use crate::Result;

/// [`DataStore`] implementation backed by the real filesystem.
///
/// State is stored as symlinks and sentinel files under the XDG data
/// directory. The double-link architecture works as follows:
///
/// ```text
/// ~/dotfiles/vim/vimrc                              (source)
///   -> ~/.local/share/dodot/packs/vim/symlink/vimrc (data link)
///     -> ~/.vimrc                                   (user link)
/// ```
pub struct FilesystemDataStore {
    fs: Arc<dyn Fs>,
    paths: Arc<dyn Pather>,
    runner: Arc<dyn CommandRunner>,
}

impl FilesystemDataStore {
    pub fn new(fs: Arc<dyn Fs>, paths: Arc<dyn Pather>, runner: Arc<dyn CommandRunner>) -> Self {
        Self { fs, paths, runner }
    }
}

impl DataStore for FilesystemDataStore {
    fn create_data_link(&self, pack: &str, handler: &str, source_file: &Path) -> Result<PathBuf> {
        let filename = source_file.file_name().ok_or_else(|| {
            crate::DodotError::Other(format!(
                "source file has no filename: {}",
                source_file.display()
            ))
        })?;

        let link_dir = self.paths.handler_data_dir(pack, handler);
        let link_path = link_dir.join(filename);

        self.fs.mkdir_all(&link_dir)?;

        // Idempotent: if the link already points to the correct source, skip.
        if self.fs.is_symlink(&link_path) {
            if let Ok(current_target) = self.fs.readlink(&link_path) {
                if current_target == source_file {
                    return Ok(link_path);
                }
            }
            // Wrong target — remove and re-create.
            self.fs.remove_file(&link_path)?;
        }

        self.fs.symlink(source_file, &link_path)?;
        Ok(link_path)
    }

    fn create_user_link(&self, datastore_path: &Path, user_path: &Path) -> Result<()> {
        // Create parent directory
        if let Some(parent) = user_path.parent() {
            self.fs.mkdir_all(parent)?;
        }

        // If something already exists at user_path, handle it
        if self.fs.is_symlink(user_path) {
            // Existing symlink — check if it's correct
            if let Ok(current_target) = self.fs.readlink(user_path) {
                if current_target == datastore_path {
                    return Ok(()); // Already correct
                }
            }
            // Wrong target — remove and re-create
            self.fs.remove_file(user_path)?;
        } else if self.fs.exists(user_path) {
            // Exists but is not a symlink — conflict
            return Err(crate::DodotError::SymlinkConflict {
                path: user_path.to_path_buf(),
            });
        }

        self.fs.symlink(datastore_path, user_path)
    }

    fn run_and_record(
        &self,
        pack: &str,
        handler: &str,
        executable: &str,
        arguments: &[String],
        sentinel: &str,
        force: bool,
    ) -> Result<()> {
        // Idempotent: skip if sentinel exists
        if !force && self.has_sentinel(pack, handler, sentinel)? {
            return Ok(());
        }

        // Run the command
        self.runner.run(executable, arguments)?;

        // Record sentinel
        let sentinel_dir = self.paths.handler_data_dir(pack, handler);
        self.fs.mkdir_all(&sentinel_dir)?;

        let sentinel_path = sentinel_dir.join(sentinel);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let content = format!("completed|{timestamp}");
        self.fs.write_file(&sentinel_path, content.as_bytes())
    }

    fn has_sentinel(&self, pack: &str, handler: &str, sentinel: &str) -> Result<bool> {
        let sentinel_path = self.paths.handler_data_dir(pack, handler).join(sentinel);
        Ok(self.fs.exists(&sentinel_path))
    }

    fn remove_state(&self, pack: &str, handler: &str) -> Result<()> {
        let state_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&state_dir) {
            return Ok(());
        }
        self.fs.remove_dir_all(&state_dir)
    }

    fn has_handler_state(&self, pack: &str, handler: &str) -> Result<bool> {
        let state_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&state_dir) {
            return Ok(false);
        }
        let entries = self.fs.read_dir(&state_dir)?;
        Ok(!entries.is_empty())
    }

    fn list_pack_handlers(&self, pack: &str) -> Result<Vec<String>> {
        let pack_dir = self.paths.pack_data_dir(pack);
        if !self.fs.exists(&pack_dir) {
            return Ok(Vec::new());
        }
        let entries = self.fs.read_dir(&pack_dir)?;
        Ok(entries
            .into_iter()
            .filter(|e| e.is_dir)
            .map(|e| e.name)
            .collect())
    }

    fn list_handler_sentinels(&self, pack: &str, handler: &str) -> Result<Vec<String>> {
        let handler_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&handler_dir) {
            return Ok(Vec::new());
        }
        let entries = self.fs.read_dir(&handler_dir)?;
        Ok(entries
            .into_iter()
            .filter(|e| e.is_file)
            .map(|e| e.name)
            .collect())
    }

    fn sentinel_path(&self, pack: &str, handler: &str, sentinel: &str) -> PathBuf {
        self.paths.handler_data_dir(pack, handler).join(sentinel)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datastore::{CommandOutput, CommandRunner};
    use crate::testing::TempEnvironment;
    use std::sync::Mutex;

    /// Mock command runner that records calls and can be configured to
    /// succeed or fail.
    struct MockCommandRunner {
        calls: Mutex<Vec<String>>,
        should_fail: bool,
    }

    impl MockCommandRunner {
        fn new() -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
                should_fail: false,
            }
        }

        fn failing() -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
                should_fail: true,
            }
        }

        fn calls(&self) -> Vec<String> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl CommandRunner for MockCommandRunner {
        fn run(&self, executable: &str, arguments: &[String]) -> Result<CommandOutput> {
            let cmd_str = format!("{} {}", executable, arguments.join(" "));
            self.calls.lock().unwrap().push(cmd_str.trim().to_string());
            if self.should_fail {
                Err(crate::DodotError::CommandFailed {
                    command: cmd_str.trim().to_string(),
                    exit_code: 1,
                    stderr: "mock failure".to_string(),
                })
            } else {
                Ok(CommandOutput {
                    exit_code: 0,
                    stdout: String::new(),
                    stderr: String::new(),
                })
            }
        }
    }

    fn make_datastore(env: &TempEnvironment) -> (FilesystemDataStore, Arc<MockCommandRunner>) {
        let runner = Arc::new(MockCommandRunner::new());
        let ds = FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), runner.clone());
        (ds, runner)
    }

    // ── create_data_link ────────────────────────────────────────

    #[test]
    fn create_data_link_creates_symlink() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        let link_path = ds.create_data_link("vim", "symlink", &source).unwrap();

        // Link should be in the handler data dir
        assert_eq!(
            link_path,
            env.paths.handler_data_dir("vim", "symlink").join("vimrc")
        );

        // Link should point to source
        env.assert_symlink(&link_path, &source);
    }

    #[test]
    fn create_data_link_is_idempotent() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");

        let path1 = ds.create_data_link("vim", "symlink", &source).unwrap();
        let path2 = ds.create_data_link("vim", "symlink", &source).unwrap();

        assert_eq!(path1, path2);
        env.assert_symlink(&path1, &source);
    }

    #[test]
    fn create_data_link_replaces_wrong_target() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "v1")
            .file("vimrc-new", "v2")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source1 = env.dotfiles_root.join("vim/vimrc");
        let source2 = env.dotfiles_root.join("vim/vimrc-new");

        // Create initial link to source1
        let link_dir = env.paths.handler_data_dir("vim", "symlink");
        env.fs.mkdir_all(&link_dir).unwrap();
        // Manually create a link named "vimrc-new" pointing to source1 (wrong target)
        let wrong_link = link_dir.join("vimrc-new");
        env.fs.symlink(&source1, &wrong_link).unwrap();

        // Now create_data_link should fix it to point at source2
        let link_path = ds.create_data_link("vim", "symlink", &source2).unwrap();
        env.assert_symlink(&link_path, &source2);
    }

    // ── create_user_link ────────────────────────────────────────

    #[test]
    fn create_user_link_creates_symlink() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        // Create the datastore file so the symlink target exists
        env.fs.mkdir_all(datastore_path.parent().unwrap()).unwrap();
        env.fs.write_file(&datastore_path, b"link target").unwrap();

        ds.create_user_link(&datastore_path, &user_path).unwrap();

        env.assert_symlink(&user_path, &datastore_path);
    }

    #[test]
    fn create_user_link_is_idempotent() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        env.fs.mkdir_all(datastore_path.parent().unwrap()).unwrap();
        env.fs.write_file(&datastore_path, b"x").unwrap();

        ds.create_user_link(&datastore_path, &user_path).unwrap();
        ds.create_user_link(&datastore_path, &user_path).unwrap();

        env.assert_symlink(&user_path, &datastore_path);
    }

    #[test]
    fn create_user_link_conflict_with_regular_file() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        // Create a regular file at the user path
        env.fs.write_file(&user_path, b"existing content").unwrap();

        let err = ds
            .create_user_link(&datastore_path, &user_path)
            .unwrap_err();
        assert!(
            matches!(err, crate::DodotError::SymlinkConflict { .. }),
            "expected SymlinkConflict, got: {err}"
        );
    }

    #[test]
    fn create_user_link_replaces_wrong_symlink() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let wrong_target = env.data_dir.join("wrong");
        let correct_target = env.data_dir.join("correct");
        let user_path = env.home.join(".vimrc");

        env.fs.mkdir_all(&env.data_dir).unwrap();
        env.fs.write_file(&wrong_target, b"wrong").unwrap();
        env.fs.write_file(&correct_target, b"right").unwrap();

        // Create wrong symlink
        env.fs.symlink(&wrong_target, &user_path).unwrap();

        // Should fix it
        ds.create_user_link(&correct_target, &user_path).unwrap();
        env.assert_symlink(&user_path, &correct_target);
    }

    // ── Double-link chain ───────────────────────────────────────

    #[test]
    fn full_double_link_chain() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        let user_path = env.home.join(".vimrc");

        // Step 1: data link
        let datastore_path = ds.create_data_link("vim", "symlink", &source).unwrap();

        // Step 2: user link
        ds.create_user_link(&datastore_path, &user_path).unwrap();

        // Verify the full chain
        env.assert_double_link("vim", "symlink", "vimrc", &source, &user_path);

        // Reading through the chain should yield the original content
        let content = env.fs.read_to_string(&user_path).unwrap();
        assert_eq!(content, "set nocompatible");
    }

    // ── run_and_record / has_sentinel ───────────────────────────

    #[test]
    fn run_and_record_creates_sentinel() {
        let env = TempEnvironment::builder().build();
        let (ds, runner) = make_datastore(&env);

        assert!(!ds.has_sentinel("vim", "install", "install.sh-abc").unwrap());

        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["hello".into()],
            "install.sh-abc",
            false,
        )
        .unwrap();

        assert!(ds.has_sentinel("vim", "install", "install.sh-abc").unwrap());
        assert_eq!(runner.calls(), vec!["echo hello"]);

        // Sentinel file should contain "completed|..."
        let sentinel_path = env
            .paths
            .handler_data_dir("vim", "install")
            .join("install.sh-abc");
        let content = env.fs.read_to_string(&sentinel_path).unwrap();
        assert!(content.starts_with("completed|"), "got: {content}");
    }

    #[test]
    fn run_and_record_is_idempotent() {
        let env = TempEnvironment::builder().build();
        let (ds, runner) = make_datastore(&env);

        ds.run_and_record("vim", "install", "echo", &["first".into()], "s1", false)
            .unwrap();
        ds.run_and_record("vim", "install", "echo", &["second".into()], "s1", false)
            .unwrap();

        // Command only ran once
        assert_eq!(runner.calls(), vec!["echo first"]);
    }

    #[test]
    fn run_and_record_propagates_command_failure() {
        let env = TempEnvironment::builder().build();
        let runner = Arc::new(MockCommandRunner::failing());
        let ds = FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), runner);

        let err = ds
            .run_and_record("vim", "install", "bad-cmd", &[], "s1", false)
            .unwrap_err();

        assert!(
            matches!(err, crate::DodotError::CommandFailed { .. }),
            "expected CommandFailed, got: {err}"
        );

        // No sentinel should be created on failure
        assert!(!ds.has_sentinel("vim", "install", "s1").unwrap());
    }

    // ── remove_state ────────────────────────────────────────────

    #[test]
    fn remove_state_clears_handler_dir() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        ds.create_data_link("vim", "symlink", &source).unwrap();
        assert!(ds.has_handler_state("vim", "symlink").unwrap());

        ds.remove_state("vim", "symlink").unwrap();
        env.assert_no_handler_state("vim", "symlink");
    }

    #[test]
    fn remove_state_is_noop_when_no_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        // Should not error
        ds.remove_state("nonexistent", "handler").unwrap();
    }

    // ── has_handler_state ───────────────────────────────────────

    #[test]
    fn has_handler_state_false_when_no_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        assert!(!ds.has_handler_state("vim", "symlink").unwrap());
    }

    #[test]
    fn has_handler_state_false_when_empty_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let dir = env.paths.handler_data_dir("vim", "symlink");
        env.fs.mkdir_all(&dir).unwrap();

        assert!(!ds.has_handler_state("vim", "symlink").unwrap());
    }

    #[test]
    fn has_handler_state_true_when_entries_exist() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        ds.create_data_link("vim", "symlink", &source).unwrap();

        assert!(ds.has_handler_state("vim", "symlink").unwrap());
    }

    // ── list_pack_handlers ──────────────────────────────────────

    #[test]
    fn list_pack_handlers_returns_handler_dirs() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .file("aliases.sh", "y")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source1 = env.dotfiles_root.join("vim/vimrc");
        let source2 = env.dotfiles_root.join("vim/aliases.sh");
        ds.create_data_link("vim", "symlink", &source1).unwrap();
        ds.create_data_link("vim", "shell", &source2).unwrap();

        let mut handlers = ds.list_pack_handlers("vim").unwrap();
        handlers.sort();
        assert_eq!(handlers, vec!["shell", "symlink"]);
    }

    #[test]
    fn list_pack_handlers_empty_when_no_pack_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let handlers = ds.list_pack_handlers("nonexistent").unwrap();
        assert!(handlers.is_empty());
    }

    // ── list_handler_sentinels ──────────────────────────────────

    #[test]
    fn list_handler_sentinels_returns_file_names() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["a".into()],
            "install.sh-aaa",
            false,
        )
        .unwrap();
        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["b".into()],
            "install.sh-bbb",
            false,
        )
        .unwrap();

        let mut sentinels = ds.list_handler_sentinels("vim", "install").unwrap();
        sentinels.sort();
        assert_eq!(sentinels, vec!["install.sh-aaa", "install.sh-bbb"]);
    }

    #[test]
    fn list_handler_sentinels_empty_when_no_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinels = ds.list_handler_sentinels("vim", "install").unwrap();
        assert!(sentinels.is_empty());
    }

    // ── Object safety ───────────────────────────────────────────

    #[allow(dead_code)]
    fn assert_object_safe(_: &dyn DataStore) {}
}