dotr-dear 2.0.1

A dotfiles manager as dear as a daughter.
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
use std::{fs, path::PathBuf};

use dotr_dear::{
    cli::{DeployArgs, ImportArgs, InitArgs, PrintVarsArgs, UpdateArgs, run_cli},
    config::Config,
    context::Context,
    package::get_pkg_name_and_rel_path,
    utils,
};

mod common;

// Test constants
const PLAYGROUND_DIR: &str = "tests/playground";
const NVIM_PATH: &str = "src/nvim/";
const BASHRC_PATH: &str = "src/.bashrc";
const ZSHRC_PATH: &str = "src/.zshrc";
const VIMRC_PATH: &str = "src/.vimrc";
const GITCONFIG_PATH: &str = "src/.gitconfig";
const TMUX_PATH: &str = "src/tmux/";
const ALACRITTY_PATH: &str = "src/config/alacritty/";

// Test fixture helper
struct TestFixture {
    cwd: PathBuf,
}

impl TestFixture {
    fn new() -> Self {
        let cwd = PathBuf::from(PLAYGROUND_DIR);
        // Ensure test files exist
        common::setup(&cwd);
        Self { cwd }
    }

    fn get_cli(&self, command: Option<dotr_dear::cli::Command>) -> dotr_dear::cli::Cli {
        dotr_dear::cli::Cli {
            command,
            working_dir: Some(PLAYGROUND_DIR.to_string()),
        }
    }

    fn init(&self) {
        run_cli(self.get_cli(Some(dotr_dear::cli::Command::Init(InitArgs {}))))
            .expect("Init failed");
    }

    fn import(&self, path: &str) {
        run_cli(
            self.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
                path: path.to_string(),
                ..Default::default()
            }))),
        )
        .expect("Import failed");
    }

    fn deploy(&self, packages: Option<Vec<String>>) {
        run_cli(
            self.get_cli(Some(dotr_dear::cli::Command::Deploy(DeployArgs {
                packages,
                profile: None,
                ignore_errors: false,
                clean: Some(false),
                dry_run: false,
                ..Default::default()
            }))),
        )
        .expect("Deploy failed");
    }

    fn update(&self, packages: Option<Vec<String>>) {
        run_cli(
            self.get_cli(Some(dotr_dear::cli::Command::Update(UpdateArgs {
                packages,
                profile: None,
                ignore_errors: false,
                clean: Some(false),
                dry_run: false,
            }))),
        )
        .expect("Update failed");
    }

    fn get_config(&self) -> Config {
        Config::from_path(&self.cwd).expect("Failed to load config")
    }

    fn get_package_name(&self, path: &str) -> String {
        let args = ImportArgs {
            path: path.to_string(),
            ..Default::default()
        };
        get_pkg_name_and_rel_path(&args, &self.cwd).unwrap().0
    }

    fn assert_file_exists(&self, path: &str, message: &str) {
        assert!(self.cwd.join(path).exists(), "{}", message);
    }

    fn assert_file_not_exists(&self, path: &str, message: &str) {
        assert!(!self.cwd.join(path).exists(), "{}", message);
    }

    fn assert_file_contains(&self, path: &str, content: &str, message: &str) {
        let file_path = self.cwd.join(path);
        let file_content = fs::read_to_string(&file_path)
            .unwrap_or_else(|_| panic!("Failed to read file: {}", path));
        assert!(file_content.contains(content), "{}", message);
    }

    fn write_file(&self, path: &str, content: &str) {
        let file_path = self.cwd.join(path);
        fs::write(file_path, content).unwrap_or_else(|_| panic!("Failed to write file: {}", path));
    }

    fn get_context_variables(&self) -> toml::Table {
        let config = self.get_config();
        let (mut ctx, _) =
            Context::new(&self.cwd, &config, &None, false).expect("Failed to create context");
        ctx.extend_variables(config.variables.clone());
        ctx.get_context_variables()
    }
}

impl Drop for TestFixture {
    fn drop(&mut self) {
        common::teardown(&self.cwd);
    }
}

#[test]
fn test_no_command() {
    let fixture = TestFixture::new();

    let _ = run_cli(fixture.get_cli(None));

    fixture.assert_file_not_exists("config.toml", "config.toml should not be created");
    fixture.assert_file_not_exists("dotfiles", "dotfiles directory should not be created");
}

#[test]
fn test_init_config() {
    let fixture = TestFixture::new();

    fixture.init();

    fixture.assert_file_exists("config.toml", "config.toml should be created");
    fixture.assert_file_exists("dotfiles", "dotfiles directory should be created");
    fixture.assert_file_exists(".gitignore", ".gitignore should be created");
    fixture.assert_file_contains(
        ".gitignore",
        ".uservariables.toml",
        ".gitignore should contain .uservariables.toml",
    );
}

#[test]
fn test_import_dots() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    let config = fixture.get_config();
    let nvim_package_name = fixture.get_package_name(NVIM_PATH);
    let bashrc_package_name = fixture.get_package_name(BASHRC_PATH);

    // Verify nvim package
    assert!(
        config.packages.contains_key(&nvim_package_name),
        "Config should contain the nvim package"
    );
    let nvim_package = config.packages.get(&nvim_package_name).unwrap();
    assert!(
        nvim_package.dest.ends_with(NVIM_PATH),
        "Package dest should match the imported path"
    );
    assert_eq!(
        nvim_package.src,
        format!("dotfiles/{}", nvim_package_name),
        "Package src should be correctly set"
    );

    // Verify bashrc package
    assert!(
        config.packages.contains_key(&bashrc_package_name),
        "Config should contain the bashrc package"
    );

    // Verify files are copied to dotfiles directory
    fixture.assert_file_exists(
        &format!("dotfiles/{}/init.lua", nvim_package_name),
        "nvim init.lua should be copied to dotfiles",
    );
}

#[test]
fn test_canonical_linking() {
    let fixture = TestFixture::new();

    let path_from_home = utils::resolve_path("~/.config", &fixture.cwd).unwrap();
    let path_from_root = utils::resolve_path("/Volumes/Repos/", &fixture.cwd).unwrap();
    let path_from_cwd = utils::resolve_path("src/nvim", &fixture.cwd).unwrap();

    assert!(path_from_home.is_absolute());
    assert!(path_from_root.is_absolute());
    assert!(path_from_cwd.is_absolute());
}

#[test]
fn test_deploy_all_packages() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    // Modify the source files to ensure deployment happens and backups are created
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");
    fixture.write_file("src/.bashrc", "# Modified bashrc\n");

    // Deploy all packages
    fixture.deploy(None);

    // Verify backups created (granular per-file backups)
    fixture.assert_file_exists(
        "src/nvim/init.lua.dotrbak",
        "nvim init.lua backup should exist",
    );
    fixture.assert_file_exists("src/.bashrc.dotrbak", "bashrc backup should exist");

    // Verify files deployed
    fixture.assert_file_exists("src/nvim/init.lua", "nvim init.lua should be deployed");
    fixture.assert_file_exists("src/.bashrc", "bashrc should be deployed");
}

#[test]
fn test_deploy_specific_package() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    // Modify nvim to ensure deployment happens
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");

    // Deploy only nvim
    let nvim_package_name = fixture.get_package_name(NVIM_PATH);
    fixture.deploy(Some(vec![nvim_package_name]));

    // Verify only nvim was deployed
    fixture.assert_file_exists(
        "src/nvim/init.lua.dotrbak",
        "nvim init.lua backup should exist",
    );
    fixture.assert_file_exists("src/nvim/init.lua", "nvim init.lua should be deployed");
    fixture.assert_file_not_exists(
        "src/.bashrc.dotrbak",
        "bashrc should NOT have been deployed",
    );
}

#[test]
fn test_deploy_multiple_specific_packages() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    // Modify files to ensure deployment happens
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");
    fixture.write_file("src/.bashrc", "# Modified bashrc\n");

    // Deploy both packages explicitly
    let nvim_package_name = fixture.get_package_name(NVIM_PATH);
    let bashrc_package_name = fixture.get_package_name(BASHRC_PATH);
    fixture.deploy(Some(vec![nvim_package_name, bashrc_package_name]));

    // Verify both were deployed
    fixture.assert_file_exists(
        "src/nvim/init.lua.dotrbak",
        "nvim init.lua backup should exist",
    );
    fixture.assert_file_exists("src/nvim/init.lua", "nvim init.lua should be deployed");
    fixture.assert_file_exists("src/.bashrc.dotrbak", "bashrc backup should exist");
    fixture.assert_file_exists("src/.bashrc", "bashrc should be deployed");
}

#[test]
fn test_update_specific_package() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    // Deploy all packages
    fixture.deploy(None);

    // Modify deployed files
    fixture.write_file("src/nvim/init.lua", "-- Modified nvim config\n");
    fixture.write_file("src/.bashrc", "# Modified bashrc\n");

    // Update only nvim
    let nvim_package_name = fixture.get_package_name(NVIM_PATH);
    fixture.update(Some(vec![nvim_package_name.clone()]));

    // Verify nvim was updated
    fixture.assert_file_contains(
        &format!("dotfiles/{}/init.lua", nvim_package_name),
        "Modified nvim config",
        "nvim config should be updated in dotfiles",
    );

    // Verify bashrc was NOT updated
    let bashrc_package_name = fixture.get_package_name(BASHRC_PATH);
    let bashrc_content = fs::read_to_string(
        fixture
            .cwd
            .join(format!("dotfiles/{}", bashrc_package_name)),
    )
    .expect("Failed to read bashrc");
    assert!(
        !bashrc_content.contains("Modified bashrc"),
        "bashrc should NOT be updated in dotfiles"
    );
}

#[test]
fn test_update_multiple_specific_packages() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);
    fixture.import(BASHRC_PATH);

    // Deploy all packages
    fixture.deploy(None);

    // Modify deployed files
    fixture.write_file("src/nvim/init.lua", "-- Updated nvim config\n");
    fixture.write_file("src/.bashrc", "# Updated bashrc\n");

    // Update both packages
    let nvim_package_name = fixture.get_package_name(NVIM_PATH);
    let bashrc_package_name = fixture.get_package_name(BASHRC_PATH);
    fixture.update(Some(vec![
        nvim_package_name.clone(),
        bashrc_package_name.clone(),
    ]));

    // Verify both were updated
    fixture.assert_file_contains(
        &format!("dotfiles/{}/init.lua", nvim_package_name),
        "Updated nvim config",
        "nvim config should be updated",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}", bashrc_package_name),
        "Updated bashrc",
        "bashrc should be updated",
    );
}

#[test]
fn test_deploy_nonexistent_package() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(NVIM_PATH);

    // Modify file to ensure deployment would happen if it were deployed
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");

    // Try to deploy a non-existent package - should fail
    let result = run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Deploy(DeployArgs {
            packages: Some(vec!["nonexistent_package".to_string()]),
            profile: None,
            ignore_errors: false,
            clean: Some(false),
            dry_run: false,
            ..Default::default()
        }))),
    );

    assert!(
        result.is_err(),
        "Deploy with nonexistent package should error"
    );
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention package not found"
    );

    // Verify nothing was deployed
    fixture.assert_file_not_exists(
        "src/nvim/init.lua.dotrbak",
        "No backup should be created for filtered out packages",
    );
}

#[test]
fn test_import_multiple_files() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(BASHRC_PATH);
    fixture.import(ZSHRC_PATH);
    fixture.import(VIMRC_PATH);
    fixture.import(GITCONFIG_PATH);

    let config = fixture.get_config();
    let bashrc_name = fixture.get_package_name(BASHRC_PATH);
    let zshrc_name = fixture.get_package_name(ZSHRC_PATH);
    let vimrc_name = fixture.get_package_name(VIMRC_PATH);
    let gitconfig_name = fixture.get_package_name(GITCONFIG_PATH);

    // Verify all packages exist in config
    assert!(config.packages.contains_key(&bashrc_name));
    assert!(config.packages.contains_key(&zshrc_name));
    assert!(config.packages.contains_key(&vimrc_name));
    assert!(config.packages.contains_key(&gitconfig_name));

    // Verify files are backed up
    fixture.assert_file_exists(
        &format!("dotfiles/{}", bashrc_name),
        "bashrc should be backed up",
    );
    fixture.assert_file_exists(
        &format!("dotfiles/{}", zshrc_name),
        "zshrc should be backed up",
    );
    fixture.assert_file_exists(
        &format!("dotfiles/{}", vimrc_name),
        "vimrc should be backed up",
    );
    fixture.assert_file_exists(
        &format!("dotfiles/{}", gitconfig_name),
        "gitconfig should be backed up",
    );

    // Verify content
    fixture.assert_file_contains(
        &format!("dotfiles/{}", bashrc_name),
        "Bashrc configuration",
        "bashrc content should match",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}", gitconfig_name),
        "Test User",
        "gitconfig content should match",
    );
}

#[test]
fn test_import_nested_directories() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(TMUX_PATH);
    fixture.import(ALACRITTY_PATH);

    let config = fixture.get_config();
    let tmux_name = fixture.get_package_name(TMUX_PATH);
    let alacritty_name = fixture.get_package_name(ALACRITTY_PATH);

    // Verify packages in config
    assert!(config.packages.contains_key(&tmux_name));
    assert!(config.packages.contains_key(&alacritty_name));

    // Verify directory contents are backed up
    fixture.assert_file_exists(
        &format!("dotfiles/{}/tmux.conf", tmux_name),
        "tmux.conf should be backed up",
    );
    fixture.assert_file_exists(
        &format!("dotfiles/{}/theme.conf", tmux_name),
        "theme.conf should be backed up",
    );
    fixture.assert_file_exists(
        &format!("dotfiles/{}/alacritty.yml", alacritty_name),
        "alacritty.yml should be backed up",
    );

    // Verify content
    fixture.assert_file_contains(
        &format!("dotfiles/{}/tmux.conf", tmux_name),
        "set -g mouse on",
        "tmux.conf content should match",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}/alacritty.yml", alacritty_name),
        "padding",
        "alacritty.yml content should match",
    );
}

#[test]
fn test_deploy_all_file_types() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(BASHRC_PATH);
    fixture.import(ZSHRC_PATH);
    fixture.import(NVIM_PATH);
    fixture.import(TMUX_PATH);

    // Modify files to ensure deployment happens
    fixture.write_file("src/.bashrc", "# Modified bashrc\n");
    fixture.write_file("src/.zshrc", "# Modified zshrc\n");
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");
    fixture.write_file("src/tmux/tmux.conf", "# Modified tmux.conf\n");
    fixture.write_file("src/tmux/theme.conf", "# Modified theme.conf\n");

    // Deploy all packages
    fixture.deploy(None);

    // Verify file backups created
    fixture.assert_file_exists("src/.bashrc.dotrbak", "bashrc backup should exist");
    fixture.assert_file_exists("src/.zshrc.dotrbak", "zshrc backup should exist");

    // Verify directory backups created (granular per-file)
    fixture.assert_file_exists(
        "src/nvim/init.lua.dotrbak",
        "nvim init.lua backup should exist",
    );
    fixture.assert_file_exists(
        "src/tmux/tmux.conf.dotrbak",
        "tmux.conf backup should exist",
    );
    fixture.assert_file_exists(
        "src/tmux/theme.conf.dotrbak",
        "theme.conf backup should exist",
    );

    // Verify deployed files exist
    fixture.assert_file_exists("src/.bashrc", "bashrc should be deployed");
    fixture.assert_file_exists("src/.zshrc", "zshrc should be deployed");
    fixture.assert_file_exists("src/nvim/init.lua", "nvim init.lua should be deployed");
    fixture.assert_file_exists("src/tmux/tmux.conf", "tmux.conf should be deployed");
    fixture.assert_file_exists("src/tmux/theme.conf", "theme.conf should be deployed");
}

#[test]
fn test_update_preserves_changes() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(VIMRC_PATH);
    fixture.import(TMUX_PATH);

    // Deploy
    fixture.deploy(None);

    // Modify deployed files
    fixture.write_file(
        "src/.vimrc",
        "\" Updated vimrc\nset number\nset relativenumber\n",
    );
    fixture.write_file("src/tmux/tmux.conf", "# Updated tmux\nset -g mouse off\n");

    // Update all
    fixture.update(None);

    let vimrc_name = fixture.get_package_name(VIMRC_PATH);
    let tmux_name = fixture.get_package_name(TMUX_PATH);

    // Verify updates in dotfiles
    fixture.assert_file_contains(
        &format!("dotfiles/{}", vimrc_name),
        "Updated vimrc",
        "vimrc should be updated",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}", vimrc_name),
        "relativenumber",
        "vimrc should contain new content",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}/tmux.conf", tmux_name),
        "Updated tmux",
        "tmux.conf should be updated",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}/tmux.conf", tmux_name),
        "mouse off",
        "tmux.conf should contain modified content",
    );
}

#[test]
fn test_deploy_preserves_directory_structure() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.import(ALACRITTY_PATH);

    // Modify file to ensure deployment happens
    fixture.write_file(
        "src/config/alacritty/alacritty.yml",
        "# Modified alacritty\n",
    );

    // Deploy
    let alacritty_name = fixture.get_package_name(ALACRITTY_PATH);
    fixture.deploy(Some(vec![alacritty_name]));

    // Verify backup was created (granular per-file)
    fixture.assert_file_exists(
        "src/config/alacritty/alacritty.yml.dotrbak",
        "alacritty.yml backup should exist",
    );

    // Verify deployed with correct structure
    fixture.assert_file_exists(
        "src/config/alacritty/alacritty.yml",
        "alacritty.yml should be deployed",
    );

    // Verify content
    fixture.assert_file_contains(
        "src/config/alacritty/alacritty.yml",
        "window:",
        "deployed file should have correct content",
    );
}

#[test]
fn test_mixed_files_and_directories() {
    let fixture = TestFixture::new();

    fixture.init();

    // Import mix of files and directories
    fixture.import(BASHRC_PATH);
    fixture.import(GITCONFIG_PATH);
    fixture.import(NVIM_PATH);
    fixture.import(TMUX_PATH);

    let config = fixture.get_config();

    // Should have 4 packages
    assert_eq!(config.packages.len(), 4, "Should have 4 packages");

    // Modify files to ensure deployment happens
    fixture.write_file("src/.bashrc", "# Modified bashrc\n");
    fixture.write_file("src/.gitconfig", "# Modified gitconfig\n");
    fixture.write_file("src/nvim/init.lua", "-- Modified init.lua\n");
    fixture.write_file("src/tmux/theme.conf", "# Modified theme.conf\n");

    // Deploy all
    fixture.deploy(None);

    // Verify all deployed correctly
    fixture.assert_file_exists("src/.bashrc", "bashrc deployed");
    fixture.assert_file_exists("src/.gitconfig", "gitconfig deployed");
    fixture.assert_file_exists("src/nvim/init.lua", "nvim/init.lua deployed");
    fixture.assert_file_exists("src/tmux/tmux.conf", "tmux/tmux.conf deployed");

    // Modify and update only directories
    fixture.write_file("src/nvim/init.lua", "-- Modified nvim\n");
    fixture.write_file("src/tmux/theme.conf", "# Modified theme\n");

    let nvim_name = fixture.get_package_name(NVIM_PATH);
    let tmux_name = fixture.get_package_name(TMUX_PATH);
    fixture.update(Some(vec![nvim_name.clone(), tmux_name.clone()]));

    // Verify only specified packages updated
    fixture.assert_file_contains(
        &format!("dotfiles/{}/init.lua", nvim_name),
        "Modified nvim",
        "nvim should be updated",
    );
    fixture.assert_file_contains(
        &format!("dotfiles/{}/theme.conf", tmux_name),
        "Modified theme",
        "tmux theme should be updated",
    );
}

#[test]
fn test_print_vars_empty() {
    let fixture = TestFixture::new();

    fixture.init();

    // Print vars should show environment variables including HOME
    let _ = run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::PrintVars(PrintVarsArgs {
            profile: None,
        }))),
    );

    // Verify that Context has HOME environment variable
    let ctx_vars = fixture.get_context_variables();
    assert!(
        ctx_vars.contains_key("HOME"),
        "HOME environment variable should be present"
    );
}

#[test]
fn test_print_vars_with_custom_variables() {
    let fixture = TestFixture::new();

    fixture.init();

    // Add custom variables to config using the Config API
    let mut config = fixture.get_config();
    config
        .variables
        .insert("EDITOR".to_string(), toml::Value::String("vim".to_string()));
    config.variables.insert(
        "SHELL".to_string(),
        toml::Value::String("/bin/zsh".to_string()),
    );
    config.variables.insert(
        "USER_EMAIL".to_string(),
        toml::Value::String("test@example.com".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // Print vars should show custom variables
    let _ = run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::PrintVars(PrintVarsArgs {
            profile: None,
        }))),
    );

    // Verify config contains variables
    let config = fixture.get_config();
    assert_eq!(
        config.variables.get("EDITOR"),
        Some(&toml::Value::String("vim".to_string()))
    );
    assert_eq!(
        config.variables.get("SHELL"),
        Some(&toml::Value::String("/bin/zsh".to_string()))
    );
    assert_eq!(
        config.variables.get("USER_EMAIL"),
        Some(&toml::Value::String("test@example.com".to_string()))
    );

    // Verify that environment variables like HOME are still present in Context
    let ctx_vars = fixture.get_context_variables();
    assert!(
        ctx_vars.contains_key("HOME"),
        "HOME environment variable should be present in Context"
    );
}

#[test]
fn test_variables_persist_after_save() {
    let fixture = TestFixture::new();

    fixture.init();

    // Add variables manually
    let mut config = fixture.get_config();
    config.variables.insert(
        "TEST_VAR".to_string(),
        toml::Value::String("test_value".to_string()),
    );
    config.variables.insert(
        "ANOTHER_VAR".to_string(),
        toml::Value::String("another_value".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload config and verify variables persist
    let reloaded_config = fixture.get_config();
    assert_eq!(
        reloaded_config.variables.get("TEST_VAR"),
        Some(&toml::Value::String("test_value".to_string()))
    );
    assert_eq!(
        reloaded_config.variables.get("ANOTHER_VAR"),
        Some(&toml::Value::String("another_value".to_string()))
    );
}

#[test]
fn test_home_variable_always_present() {
    let fixture = TestFixture::new();

    fixture.init();

    // Context should have environment variables including HOME
    let ctx_vars = fixture.get_context_variables();

    // HOME should always be present in context
    assert!(ctx_vars.contains_key("HOME"));

    // HOME should be a valid path
    let home = ctx_vars.get("HOME").expect("HOME variable not found");
    if let toml::Value::String(s) = home {
        assert!(!s.is_empty());
    } else {
        panic!("HOME should be a string value");
    }
}

#[test]
fn test_variables_with_special_characters() {
    let fixture = TestFixture::new();

    fixture.init();

    // Add variables with special characters using Config API
    let mut config = fixture.get_config();
    config.variables.insert(
        "PATH".to_string(),
        toml::Value::String("/usr/local/bin:/usr/bin:/bin".to_string()),
    );
    config.variables.insert(
        "PS1".to_string(),
        toml::Value::String("[\\u@\\h \\W]$ ".to_string()),
    );
    config.variables.insert(
        "COMPLEX_VAR".to_string(),
        toml::Value::String("value with spaces and $pecial ch@rs".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    let config = fixture.get_config();
    assert_eq!(
        config.variables.get("PATH"),
        Some(&toml::Value::String(
            "/usr/local/bin:/usr/bin:/bin".to_string()
        ))
    );
    assert_eq!(
        config.variables.get("PS1"),
        Some(&toml::Value::String("[\\u@\\h \\W]$ ".to_string()))
    );
    assert_eq!(
        config.variables.get("COMPLEX_VAR"),
        Some(&toml::Value::String(
            "value with spaces and $pecial ch@rs".to_string()
        ))
    );
}

#[test]
fn test_variables_do_not_interfere_with_packages() {
    let fixture = TestFixture::new();

    fixture.init();

    // Add variables
    let mut config = fixture.get_config();
    config.variables.insert(
        "MY_VAR".to_string(),
        toml::Value::String("my_value".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // Import packages
    fixture.import(BASHRC_PATH);
    fixture.import(NVIM_PATH);

    // Reload and verify both variables and packages exist
    let config = fixture.get_config();
    assert_eq!(
        config.variables.get("MY_VAR"),
        Some(&toml::Value::String("my_value".to_string()))
    );
    assert_eq!(config.packages.len(), 2);

    let bashrc_name = fixture.get_package_name(BASHRC_PATH);
    let nvim_name = fixture.get_package_name(NVIM_PATH);
    assert!(config.packages.contains_key(&bashrc_name));
    assert!(config.packages.contains_key(&nvim_name));
}

#[test]
fn test_config_variables_override_environment_variables() {
    let fixture = TestFixture::new();

    fixture.init();

    // Get the original HOME from environment
    let original_home = std::env::var("HOME").expect("HOME should be set in environment");

    // Override HOME in config with a custom value
    let custom_home = "/custom/home/path";
    let mut config = fixture.get_config();
    config.variables.insert(
        "HOME".to_string(),
        toml::Value::String(custom_home.to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload config and verify HOME is overridden
    let reloaded_config = fixture.get_config();
    assert_eq!(
        reloaded_config.variables.get("HOME"),
        Some(&toml::Value::String(custom_home.to_string())),
        "Config HOME should override environment HOME"
    );
    assert_ne!(
        reloaded_config.variables.get("HOME"),
        Some(&toml::Value::String(original_home.clone())),
        "Config HOME should be different from environment HOME"
    );

    // Create context and verify that config variables take precedence
    let ctx_vars = fixture.get_context_variables();

    assert_eq!(
        ctx_vars.get("HOME"),
        Some(&toml::Value::String(custom_home.to_string())),
        "Context should use config HOME over environment HOME"
    );
}

#[test]
fn test_nested_variables_simple() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create nested variable structure
    let mut config = fixture.get_config();
    let mut database_config = toml::map::Map::new();
    database_config.insert(
        "host".to_string(),
        toml::Value::String("localhost".to_string()),
    );
    database_config.insert("port".to_string(), toml::Value::Integer(5432));
    database_config.insert("name".to_string(), toml::Value::String("mydb".to_string()));

    config
        .variables
        .insert("database".to_string(), toml::Value::Table(database_config));
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload and verify nested structure
    let reloaded_config = fixture.get_config();
    let db_var = reloaded_config.variables.get("database");
    assert!(db_var.is_some(), "database variable should exist");

    if let Some(toml::Value::Table(db_table)) = db_var {
        assert_eq!(
            db_table.get("host"),
            Some(&toml::Value::String("localhost".to_string()))
        );
        assert_eq!(db_table.get("port"), Some(&toml::Value::Integer(5432)));
        assert_eq!(
            db_table.get("name"),
            Some(&toml::Value::String("mydb".to_string()))
        );
    } else {
        panic!("database should be a table");
    }
}

#[test]
fn test_nested_variables_deep() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create deeply nested structure
    let mut config = fixture.get_config();

    // Build: app.server.config.port
    let mut port_config = toml::map::Map::new();
    port_config.insert("http".to_string(), toml::Value::Integer(8080));
    port_config.insert("https".to_string(), toml::Value::Integer(8443));

    let mut server_config = toml::map::Map::new();
    server_config.insert(
        "host".to_string(),
        toml::Value::String("0.0.0.0".to_string()),
    );
    server_config.insert("ports".to_string(), toml::Value::Table(port_config));

    let mut app_config = toml::map::Map::new();
    app_config.insert("name".to_string(), toml::Value::String("myapp".to_string()));
    app_config.insert("server".to_string(), toml::Value::Table(server_config));

    config
        .variables
        .insert("app".to_string(), toml::Value::Table(app_config));
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload and verify deep nesting
    let reloaded_config = fixture.get_config();
    let app_var = reloaded_config.variables.get("app");
    assert!(app_var.is_some(), "app variable should exist");

    if let Some(toml::Value::Table(app_table)) = app_var {
        assert_eq!(
            app_table.get("name"),
            Some(&toml::Value::String("myapp".to_string()))
        );

        if let Some(toml::Value::Table(server_table)) = app_table.get("server") {
            assert_eq!(
                server_table.get("host"),
                Some(&toml::Value::String("0.0.0.0".to_string()))
            );

            if let Some(toml::Value::Table(ports_table)) = server_table.get("ports") {
                assert_eq!(ports_table.get("http"), Some(&toml::Value::Integer(8080)));
                assert_eq!(ports_table.get("https"), Some(&toml::Value::Integer(8443)));
            } else {
                panic!("ports should be a table");
            }
        } else {
            panic!("server should be a table");
        }
    } else {
        panic!("app should be a table");
    }
}

#[test]
fn test_nested_variables_with_arrays() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create nested structure with arrays
    let mut config = fixture.get_config();

    let hosts = vec![
        toml::Value::String("server1.example.com".to_string()),
        toml::Value::String("server2.example.com".to_string()),
        toml::Value::String("server3.example.com".to_string()),
    ];

    let mut cluster_config = toml::map::Map::new();
    cluster_config.insert(
        "name".to_string(),
        toml::Value::String("production".to_string()),
    );
    cluster_config.insert("hosts".to_string(), toml::Value::Array(hosts));
    cluster_config.insert("replicas".to_string(), toml::Value::Integer(3));

    config
        .variables
        .insert("cluster".to_string(), toml::Value::Table(cluster_config));
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload and verify arrays in nested structures
    let reloaded_config = fixture.get_config();
    let cluster_var = reloaded_config.variables.get("cluster");
    assert!(cluster_var.is_some(), "cluster variable should exist");

    if let Some(toml::Value::Table(cluster_table)) = cluster_var {
        assert_eq!(
            cluster_table.get("name"),
            Some(&toml::Value::String("production".to_string()))
        );
        assert_eq!(
            cluster_table.get("replicas"),
            Some(&toml::Value::Integer(3))
        );

        if let Some(toml::Value::Array(hosts_array)) = cluster_table.get("hosts") {
            assert_eq!(hosts_array.len(), 3);
            assert_eq!(
                hosts_array[0],
                toml::Value::String("server1.example.com".to_string())
            );
            assert_eq!(
                hosts_array[1],
                toml::Value::String("server2.example.com".to_string())
            );
            assert_eq!(
                hosts_array[2],
                toml::Value::String("server3.example.com".to_string())
            );
        } else {
            panic!("hosts should be an array");
        }
    } else {
        panic!("cluster should be a table");
    }
}

#[test]
fn test_nested_variables_mixed_types() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create nested structure with mixed types
    let mut config = fixture.get_config();

    let mut settings = toml::map::Map::new();
    settings.insert("debug".to_string(), toml::Value::Boolean(true));
    settings.insert("timeout".to_string(), toml::Value::Float(30.5));
    settings.insert("retries".to_string(), toml::Value::Integer(3));
    settings.insert(
        "endpoint".to_string(),
        toml::Value::String("https://api.example.com".to_string()),
    );

    config
        .variables
        .insert("settings".to_string(), toml::Value::Table(settings));
    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload and verify mixed types
    let reloaded_config = fixture.get_config();
    let settings_var = reloaded_config.variables.get("settings");
    assert!(settings_var.is_some(), "settings variable should exist");

    if let Some(toml::Value::Table(settings_table)) = settings_var {
        assert_eq!(
            settings_table.get("debug"),
            Some(&toml::Value::Boolean(true))
        );
        assert_eq!(
            settings_table.get("timeout"),
            Some(&toml::Value::Float(30.5))
        );
        assert_eq!(
            settings_table.get("retries"),
            Some(&toml::Value::Integer(3))
        );
        assert_eq!(
            settings_table.get("endpoint"),
            Some(&toml::Value::String("https://api.example.com".to_string()))
        );
    } else {
        panic!("settings should be a table");
    }
}

#[test]
fn test_nested_variables_print() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create nested variable structure for print test
    let mut config = fixture.get_config();

    let mut api_config = toml::map::Map::new();
    api_config.insert(
        "key".to_string(),
        toml::Value::String("secret123".to_string()),
    );
    api_config.insert("timeout".to_string(), toml::Value::Integer(30));

    config
        .variables
        .insert("api".to_string(), toml::Value::Table(api_config));
    config.variables.insert(
        "version".to_string(),
        toml::Value::String("1.0.0".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // Test that print-vars works with nested variables
    let _ = run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::PrintVars(PrintVarsArgs {
            profile: None,
        }))),
    );

    // Verify the nested structure is preserved
    let reloaded_config = fixture.get_config();
    assert!(reloaded_config.variables.contains_key("api"));
    assert!(reloaded_config.variables.contains_key("version"));
}

#[test]
fn test_nested_variables_do_not_interfere_with_flat_variables() {
    let fixture = TestFixture::new();

    fixture.init();

    // Mix flat and nested variables
    let mut config = fixture.get_config();

    // Flat variables
    config
        .variables
        .insert("EDITOR".to_string(), toml::Value::String("vim".to_string()));
    config.variables.insert(
        "SHELL".to_string(),
        toml::Value::String("/bin/bash".to_string()),
    );

    // Nested variable
    let mut db_config = toml::map::Map::new();
    db_config.insert(
        "host".to_string(),
        toml::Value::String("localhost".to_string()),
    );
    db_config.insert("port".to_string(), toml::Value::Integer(3306));
    config
        .variables
        .insert("database".to_string(), toml::Value::Table(db_config));

    config.save(&fixture.cwd).expect("Failed to save config");

    // Reload and verify both flat and nested coexist
    let reloaded_config = fixture.get_config();

    // Check flat variables
    assert_eq!(
        reloaded_config.variables.get("EDITOR"),
        Some(&toml::Value::String("vim".to_string()))
    );
    assert_eq!(
        reloaded_config.variables.get("SHELL"),
        Some(&toml::Value::String("/bin/bash".to_string()))
    );

    // Check nested variable
    if let Some(toml::Value::Table(db_table)) = reloaded_config.variables.get("database") {
        assert_eq!(
            db_table.get("host"),
            Some(&toml::Value::String("localhost".to_string()))
        );
        assert_eq!(db_table.get("port"), Some(&toml::Value::Integer(3306)));
    } else {
        panic!("database should be a table");
    }
}

#[test]
fn test_import_with_custom_name() {
    let fixture = TestFixture::new();
    fixture.init();

    // Import with custom name
    run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
            path: BASHRC_PATH.to_string(),
            name: Some("custom_bashrc".to_string()),
            profile: None,
            ..Default::default()
        }))),
    )
    .expect("Import with custom name failed");

    let config = fixture.get_config();

    // Should use custom name with f_ prefix
    assert!(
        config.packages.contains_key("f_custom_bashrc"),
        "Package should use custom name"
    );
    assert!(
        !config.packages.contains_key("f_bashrc"),
        "Package should not use default name"
    );
}

#[test]
fn test_import_directory_with_custom_name() {
    let fixture = TestFixture::new();
    fixture.init();

    // Import directory with custom name
    run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
            path: NVIM_PATH.to_string(),
            name: Some("my_nvim_config".to_string()),
            profile: None,
            ..Default::default()
        }))),
    )
    .expect("Import directory with custom name failed");

    let config = fixture.get_config();

    // Should use custom name with d_ prefix for directory
    assert!(
        config.packages.contains_key("d_my_nvim_config"),
        "Directory package should use custom name with d_ prefix"
    );
    assert!(
        !config.packages.contains_key("d_nvim"),
        "Package should not use default name"
    );
}

#[test]
fn test_custom_name_replaces_special_characters() {
    let fixture = TestFixture::new();
    fixture.init();

    // Import with custom name containing special characters
    run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
            path: BASHRC_PATH.to_string(),
            name: Some("my-config.v2".to_string()),
            profile: None,
            ..Default::default()
        }))),
    )
    .expect("Import with special chars in name failed");

    let config = fixture.get_config();

    // Special characters should be replaced with underscores
    assert!(
        config.packages.contains_key("f_my_config_v2"),
        "Special characters should be replaced"
    );
}

#[test]
fn test_custom_name_with_profile() {
    let fixture = TestFixture::new();
    fixture.init();

    // Import with custom name and profile
    run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
            path: BASHRC_PATH.to_string(),
            name: Some("work_bashrc".to_string()),
            profile: Some("work".to_string()),
            ..Default::default()
        }))),
    )
    .expect("Import with custom name and profile failed");

    let config = fixture.get_config();

    // Should use custom name
    assert!(
        config.packages.contains_key("f_work_bashrc"),
        "Package should use custom name"
    );

    // Should be added to profile dependencies
    let profile = config.profiles.get("work").expect("Profile should exist");
    assert!(
        profile.dependencies.contains(&"f_work_bashrc".to_string()),
        "Profile should contain package with custom name"
    );
}

#[test]
fn test_deploy_package_with_custom_name() {
    let fixture = TestFixture::new();
    fixture.init();

    // Import with custom name
    run_cli(
        fixture.get_cli(Some(dotr_dear::cli::Command::Import(ImportArgs {
            path: BASHRC_PATH.to_string(),
            name: Some("mybash".to_string()),
            profile: None,
            ..Default::default()
        }))),
    )
    .expect("Import failed");

    // Modify file to trigger deployment
    let bashrc_content = fs::read_to_string(fixture.cwd.join("src/.bashrc")).unwrap();
    fs::write(
        fixture.cwd.join("src/.bashrc"),
        format!("# Modified\n{}", bashrc_content),
    )
    .unwrap();

    // Deploy using custom package name
    fixture.deploy(Some(vec!["f_mybash".to_string()]));

    // Verify deployment
    fixture.assert_file_exists("src/.bashrc", "File should be deployed");
}