dotm-rs 2.4.0

Dotfile manager with composable roles, templates, and host-specific overrides
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
use dotm::scanner::EntryKind;
use dotm::state::{DeployEntry, DeployState};
use std::path::PathBuf;
use tempfile::TempDir;

#[test]
fn state_save_includes_version() {
    let dir = TempDir::new().unwrap();
    let mut state = DeployState::new(dir.path());
    state.record(DeployEntry {
        target: PathBuf::from("/home/user/.bashrc"),
        staged: None,
        source: PathBuf::from("/source/.bashrc"),
        content_hash: "abc".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "shell".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    let raw = std::fs::read_to_string(dir.path().join("dotm-state.json")).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
    assert_eq!(parsed["version"], 3);
}

#[test]
fn state_loads_unversioned_as_v1_and_migrates() {
    let dir = TempDir::new().unwrap();
    let v1_json = r#"{"entries":[]}"#;
    std::fs::create_dir_all(dir.path()).unwrap();
    std::fs::write(dir.path().join("dotm-state.json"), v1_json).unwrap();

    let state = DeployState::load(dir.path()).unwrap();
    assert!(state.entries().is_empty());
    state.save().unwrap();
    let raw = std::fs::read_to_string(dir.path().join("dotm-state.json")).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
    assert_eq!(parsed["version"], 3);
}

#[test]
fn state_errors_on_future_version() {
    let dir = TempDir::new().unwrap();
    let future_json = r#"{"version":999,"entries":[]}"#;
    std::fs::create_dir_all(dir.path()).unwrap();
    std::fs::write(dir.path().join("dotm-state.json"), future_json).unwrap();

    let result = DeployState::load(dir.path());
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("newer version"));
}

#[test]
fn update_entry_hash_changes_hash() {
    let dir = TempDir::new().unwrap();
    let mut state = DeployState::new(dir.path());
    state.record(DeployEntry {
        target: PathBuf::from("/t"),
        staged: None,
        source: PathBuf::from("/src"),
        content_hash: "old_hash".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.update_entry_hash(0, "new_hash".to_string());
    assert_eq!(state.entries()[0].content_hash, "new_hash");
}

#[test]
fn save_and_load_new_state() {
    let dir = TempDir::new().unwrap();
    let mut state = DeployState::new(dir.path());
    state.record(DeployEntry {
        target: PathBuf::from("/home/user/.bashrc"),
        staged: None,
        source: PathBuf::from("/home/user/dotfiles/packages/shell/.bashrc"),
        content_hash: "abc123".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "shell".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.record(DeployEntry {
        target: PathBuf::from("/home/user/.config/app.conf"),
        staged: None,
        source: PathBuf::from("/home/user/dotfiles/packages/configs/.config/app.conf##host.myhost"),
        content_hash: "def456".to_string(),
        original_hash: None,
        kind: EntryKind::Override,
        package: "configs".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    let loaded = DeployState::load(dir.path()).unwrap();
    let entries = loaded.entries();
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0].package, "shell");
    assert_eq!(entries[0].kind, EntryKind::Base);
    assert_eq!(entries[0].content_hash, "abc123");
    assert_eq!(entries[1].package, "configs");
    assert_eq!(entries[1].kind, EntryKind::Override);
}

#[test]
fn load_nonexistent_returns_empty() {
    let dir = TempDir::new().unwrap();
    let state = DeployState::load(dir.path()).unwrap();
    assert!(state.entries().is_empty());
}

#[test]
fn undeploy_removes_target() {
    let target_dir = TempDir::new().unwrap();
    let source_dir = TempDir::new().unwrap();

    let source_path = source_dir.path().join(".bashrc");
    std::fs::write(&source_path, "content").unwrap();

    let target_path = target_dir.path().join(".bashrc");
    std::os::unix::fs::symlink(&source_path, &target_path).unwrap();

    let state_dir = TempDir::new().unwrap();
    let mut state = DeployState::new(state_dir.path());
    state.record(DeployEntry {
        target: target_path.clone(),
        staged: None,
        source: source_path.clone(),
        content_hash: "hash".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "shell".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    let removed = state.undeploy(None, state_dir.path()).unwrap();
    assert_eq!(removed, 1);
    assert!(!target_path.exists());
    // Source should still exist (it's the dotfile source, not staged)
    assert!(source_path.exists());
}

#[test]
fn check_entry_status_detects_modified_copy() {
    let target_dir = TempDir::new().unwrap();

    let target_path = target_dir.path().join("test.conf");
    std::fs::write(&target_path, "original content").unwrap();
    let original_hash = dotm::hash::hash_content(b"original content");

    let state_dir = TempDir::new().unwrap();
    let state = DeployState::new(state_dir.path());

    let entry = DeployEntry {
        target: target_path.clone(),
        staged: None,
        source: PathBuf::from("/source/test.conf"),
        content_hash: original_hash,
        original_hash: None,
        kind: EntryKind::Template,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    };

    assert!(state.check_entry_status(&entry).is_ok());

    // Modify the target file
    std::fs::write(&target_path, "modified content").unwrap();
    assert!(state.check_entry_status(&entry).is_modified());
}

#[test]
fn check_entry_status_symlink_ok_when_pointing_to_source() {
    let source_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    let source_path = source_dir.path().join("test.conf");
    std::fs::write(&source_path, "content").unwrap();

    let target_path = target_dir.path().join("test.conf");
    std::os::unix::fs::symlink(&source_path, &target_path).unwrap();

    let state_dir = TempDir::new().unwrap();
    let state = DeployState::new(state_dir.path());

    let entry = DeployEntry {
        target: target_path,
        staged: None,
        source: source_path,
        content_hash: dotm::hash::hash_content(b"content"),
        original_hash: None,
        kind: EntryKind::Base,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    };

    assert!(state.check_entry_status(&entry).is_ok());
}

#[test]
fn check_entry_status_symlink_missing_when_pointing_elsewhere() {
    let source_dir = TempDir::new().unwrap();
    let other_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    let source_path = source_dir.path().join("test.conf");
    std::fs::write(&source_path, "content").unwrap();

    let other_path = other_dir.path().join("other.conf");
    std::fs::write(&other_path, "other").unwrap();

    let target_path = target_dir.path().join("test.conf");
    std::os::unix::fs::symlink(&other_path, &target_path).unwrap();

    let state_dir = TempDir::new().unwrap();
    let state = DeployState::new(state_dir.path());

    let entry = DeployEntry {
        target: target_path,
        staged: None,
        source: source_path,
        content_hash: dotm::hash::hash_content(b"content"),
        original_hash: None,
        kind: EntryKind::Base,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    };

    assert!(state.check_entry_status(&entry).is_missing());
}

#[test]
fn check_entry_status_detects_missing() {
    let state_dir = TempDir::new().unwrap();
    let state = DeployState::new(state_dir.path());

    let entry = DeployEntry {
        target: PathBuf::from("/nonexistent/target"),
        staged: None,
        source: PathBuf::from("irrelevant"),
        content_hash: "hash".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    };

    assert!(state.check_entry_status(&entry).is_missing());
}

#[test]
fn undeploy_cleans_empty_target_directories() {
    let source_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    let source_path = source_dir.path().join("file.conf");
    std::fs::write(&source_path, "content").unwrap();

    let target_parent = target_dir.path().join(".config/nested");
    std::fs::create_dir_all(&target_parent).unwrap();
    let target_path = target_parent.join("file.conf");
    std::os::unix::fs::symlink(&source_path, &target_path).unwrap();

    let state_dir = TempDir::new().unwrap();
    let mut state = DeployState::new(state_dir.path());
    state.record(DeployEntry {
        target: target_path.clone(),
        staged: None,
        source: source_path,
        content_hash: "hash".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "test".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    state.undeploy(None, state_dir.path()).unwrap();
    assert!(!target_path.exists());
    assert!(
        !target_parent.exists(),
        "empty target parent should be cleaned up"
    );
}

#[test]
fn restore_error_propagates_over_save_error() {
    let state_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    // Create a target that will fail to restore (parent dir doesn't exist
    // and we'll make it so it can't be created)
    let impossible_target = PathBuf::from("/nonexistent-root-dir/impossible/target");

    let mut state = DeployState::new(state_dir.path());
    state.record(DeployEntry {
        target: impossible_target.clone(),
        staged: None,
        source: PathBuf::from("/source"),
        content_hash: "hash".to_string(),
        original_hash: Some("orig_hash".to_string()),
        kind: EntryKind::Override,
        package: "failing_pkg".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    // Add another package so filter is meaningful
    state.record(DeployEntry {
        target: target_dir.path().join("other.conf"),
        staged: None,
        source: PathBuf::from("/source2"),
        content_hash: "hash2".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "other_pkg".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    // Store an "original" so restore tries to write it back
    state
        .store_original("orig_hash", b"original content")
        .unwrap();
    state.save().unwrap();

    // Reload and attempt filtered restore — the restore will fail because
    // it can't write to /nonexistent-root-dir/...
    let mut loaded = DeployState::load(state_dir.path()).unwrap();

    // Make state dir read-only (no write) so save() fails, but keep execute for reading subdirs
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(state_dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap();

    let result = loaded.restore(Some("failing_pkg"));

    // Restore permissions for cleanup
    let _ = std::fs::set_permissions(state_dir.path(), std::fs::Permissions::from_mode(0o755));

    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    // The error should be about restore failure (loading original or writing target),
    // not the save failure (temp state file)
    assert!(
        err_msg.contains("original content") || err_msg.contains("failed to restore"),
        "expected restore error, got: {err_msg}"
    );
}

#[test]
fn restore_writes_back_original_content() {
    let target_dir = TempDir::new().unwrap();
    let temp_base = TempDir::new().unwrap();
    // Use a state_dir path that contains ".dotm" to skip migration
    let state_dir = temp_base.path().join(".dotm");
    std::fs::create_dir_all(&state_dir).unwrap();

    let target_path = target_dir.path().join("test.conf");

    // Simulate pre-dotm state: target has original content
    let original_content = b"original config content";
    let original_hash = dotm::hash::hash_content(original_content);

    // Write deployed content (overwritten by dotm)
    std::fs::write(&target_path, "deployed by dotm").unwrap();

    let mut state = DeployState::new(&state_dir);

    // Store original backup
    state
        .store_original(&original_hash, original_content)
        .unwrap();

    // Record the deployed entry with original_hash
    state.record(DeployEntry {
        target: target_path.clone(),
        staged: None,
        source: PathBuf::from("/source/test.conf"),
        content_hash: dotm::hash::hash_content(b"deployed by dotm"),
        original_hash: Some(original_hash),
        kind: EntryKind::Override,
        package: "test_pkg".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    // Restore
    let mut loaded = DeployState::load(&state_dir).unwrap();
    let count = loaded.restore(None).unwrap();

    assert_eq!(count, 1);
    let restored_content = std::fs::read(&target_path).unwrap();
    assert_eq!(
        restored_content, original_content,
        "restored content should match original"
    );
}

#[test]
fn restore_unfiltered_saves_partial_progress_on_error() {
    let target_dir = TempDir::new().unwrap();
    let state_dir = TempDir::new().unwrap();
    let state_path = state_dir.path().join(".dotm");
    std::fs::create_dir(&state_path).unwrap();

    // Create a restorable file
    let good_target = target_dir.path().join("good.conf");
    std::fs::write(&good_target, "deployed").unwrap();

    let mut state = DeployState::new(&state_path);

    // Entry 1: will restore successfully (no original_hash → just remove)
    state.record(DeployEntry {
        target: good_target.clone(),
        staged: None,
        source: PathBuf::from("/source/good.conf"),
        content_hash: "hash1".to_string(),
        original_hash: None,
        kind: EntryKind::Base,
        package: "pkg_a".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });

    // Entry 2: will fail (original_hash but no stored original content)
    state.record(DeployEntry {
        target: PathBuf::from("/nonexistent-root-dir/bad.conf"),
        staged: None,
        source: PathBuf::from("/source/bad.conf"),
        content_hash: "hash2".to_string(),
        original_hash: Some("missing_orig".to_string()),
        kind: EntryKind::Override,
        package: "pkg_b".to_string(),
        owner: None,
        group: None,
        mode: None,
        original_owner: None,
        original_group: None,
        original_mode: None,
    });
    state.save().unwrap();

    let mut loaded = DeployState::load(&state_path).unwrap();
    let result = loaded.restore(None);
    assert!(result.is_err());

    // Reload state — only the failed entry should remain
    let reloaded = DeployState::load(&state_path).unwrap();
    assert_eq!(
        reloaded.entries().len(),
        1,
        "partial progress: successfully-restored entries should be removed from state"
    );
    assert_eq!(reloaded.entries()[0].package, "pkg_b");
}