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
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
use crate::utils::BackupManager;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, error, info, warn};
/// Current version of the symlinks.json file format.
/// Increment this when making breaking changes to the schema.
const CURRENT_VERSION: u32 = 1;
/// Represents a symlink operation (create or remove)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymlinkOperation {
/// Source file in the profile folder (e.g., ~/.config/dotstate/storage/Personal-Mac/.zshrc)
pub source: PathBuf,
/// Target symlink location in home directory (e.g., ~/.zshrc)
pub target: PathBuf,
/// Backup of the original file if it existed
pub backup: Option<PathBuf>,
/// Status of this operation
pub status: OperationStatus,
/// When this operation was performed
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum OperationStatus {
Success,
Failed(String),
Skipped(String),
RolledBack,
}
/// Report of a profile switch operation
#[derive(Debug)]
pub struct SwitchReport {
/// Symlinks that were removed (old profile)
pub removed: Vec<SymlinkOperation>,
/// Symlinks that were created (new profile)
pub created: Vec<SymlinkOperation>,
/// Any errors that occurred
pub errors: Vec<(PathBuf, String)>,
/// Whether a rollback was performed
pub rollback_performed: bool,
}
/// Preview of what would happen during a switch
#[derive(Debug)]
/// Preview of what would happen during a profile switch (dry run)
#[allow(dead_code)] // Kept for potential future use in CLI or programmatic access
pub struct SwitchPreview {
/// Symlinks that will be removed
pub will_remove: Vec<PathBuf>,
/// Symlinks that will be created
pub will_create: Vec<(PathBuf, PathBuf)>, // (target, source)
/// Files that exist and aren't our symlinks (potential conflicts)
pub conflicts: Vec<PathBuf>,
}
/// Tracked symlink information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackedSymlink {
pub target: PathBuf,
pub source: PathBuf,
pub created_at: DateTime<Utc>,
pub backup: Option<PathBuf>,
}
/// Tracking data for all symlinks we manage
#[derive(Debug, Serialize, Deserialize)]
pub struct SymlinkTracking {
pub version: u32,
pub active_profile: String,
pub symlinks: Vec<TrackedSymlink>,
}
impl Default for SymlinkTracking {
fn default() -> Self {
Self {
version: CURRENT_VERSION,
active_profile: String::new(),
symlinks: Vec::new(),
}
}
}
impl SymlinkTracking {
// ==================== Migration Methods ====================
/// Run all necessary migrations to bring tracking to current version.
fn migrate(mut tracking: Self) -> Result<Self> {
if tracking.version == 0 {
tracking = Self::migrate_v0_to_v1(tracking)?;
}
// Future migrations:
// if tracking.version == 1 { tracking = Self::migrate_v1_to_v2(tracking)?; }
Ok(tracking)
}
/// Migrate from v0 (no version field) to v1.
/// This is a no-op migration that just sets the version field.
fn migrate_v0_to_v1(mut tracking: Self) -> Result<Self> {
debug!("Migrating symlinks.json v0 -> v1");
tracking.version = 1;
Ok(tracking)
}
}
/// Manages symlinks for dotfile profiles
pub struct SymlinkManager {
/// Path to the dotfiles repository
repo_path: PathBuf,
/// Path to the tracking file
tracking_file: PathBuf,
/// Current tracking data
pub tracking: SymlinkTracking,
/// Whether backups are enabled
backup_enabled: bool,
/// Backup manager for centralized backups
backup_manager: Option<BackupManager>,
/// Current backup session directory (if backups are enabled and session started)
backup_session: Option<PathBuf>,
}
impl SymlinkManager {
/// Create a new `SymlinkManager`
pub fn new(repo_path: PathBuf) -> Result<Self> {
Self::new_with_backup(repo_path, true)
}
/// Create a new `SymlinkManager` with backup settings
pub fn new_with_backup(repo_path: PathBuf, backup_enabled: bool) -> Result<Self> {
let config_dir = crate::utils::get_config_dir();
Self::new_with_config_dir(repo_path, backup_enabled, config_dir)
}
/// Create a new `SymlinkManager` with a custom config directory.
///
/// This is primarily used for testing to avoid polluting the real user's
/// config directory with test data.
pub fn new_with_config_dir(
repo_path: PathBuf,
backup_enabled: bool,
config_dir: PathBuf,
) -> Result<Self> {
// Ensure config directory exists
if !config_dir.exists() {
fs::create_dir_all(&config_dir).context("Failed to create config directory")?;
}
let tracking_file = config_dir.join("symlinks.json");
// Load existing tracking data or create new
let mut tracking: SymlinkTracking = if tracking_file.exists() {
let data =
fs::read_to_string(&tracking_file).context("Failed to read tracking file")?;
serde_json::from_str(&data).context("Failed to parse tracking file")?
} else {
SymlinkTracking::default()
};
// Migrate if needed
if tracking_file.exists() && tracking.version < CURRENT_VERSION {
let old_version = tracking.version;
info!(
"Migrating symlinks.json from v{} to v{}",
old_version, CURRENT_VERSION
);
tracking = SymlinkTracking::migrate(tracking)?;
// Backup, save, cleanup
let tracking_json =
serde_json::to_string_pretty(&tracking).context("Failed to serialize tracking")?;
super::migrate_file(&tracking_file, old_version, "json", || {
fs::write(&tracking_file, &tracking_json).context("Failed to write tracking file")
})?;
}
let backup_manager = if backup_enabled {
Some(BackupManager::new()?)
} else {
None
};
Ok(Self {
repo_path,
tracking_file,
tracking,
backup_enabled,
backup_manager,
backup_session: None,
})
}
/// Activate a profile by creating all its symlinks
pub fn activate_profile(
&mut self,
profile_name: &str,
files: &[String],
) -> Result<Vec<SymlinkOperation>> {
let resolved =
crate::utils::profile_manifest::ResolvedFile::from_files(profile_name, files);
self.activate_resolved(profile_name, &resolved)
}
/// Activate a profile using resolved files from inheritance chain.
///
/// Unlike `activate_profile`, this method accepts files that may come from
/// different profile directories (due to inheritance). Each `ResolvedFile`
/// specifies which profile folder (or "common") contains the file.
///
/// # Arguments
/// * `profile_name` - The active profile name (for tracking)
/// * `resolved_files` - Files resolved from the inheritance chain, each with
/// a `source_profile` indicating which directory to read from
pub fn activate_resolved(
&mut self,
profile_name: &str,
resolved_files: &[crate::utils::profile_manifest::ResolvedFile],
) -> Result<Vec<SymlinkOperation>> {
let home_dir = crate::utils::get_home_dir();
self.activate_resolved_with_home(profile_name, resolved_files, &home_dir)
}
fn activate_resolved_with_home(
&mut self,
profile_name: &str,
resolved_files: &[crate::utils::profile_manifest::ResolvedFile],
home_dir: &Path,
) -> Result<Vec<SymlinkOperation>> {
info!(
"Activating profile '{}' with {} resolved files (inheritance)",
profile_name,
resolved_files.len()
);
// Create backup session if backups are enabled
if self.backup_enabled {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
info!("Created backup session: {:?}", self.backup_session);
}
}
let mut operations = Vec::new();
for resolved in resolved_files {
let source = self
.repo_path
.join(&resolved.source_profile)
.join(&resolved.relative_path);
let target = home_dir.join(&resolved.relative_path);
let operation = self.create_symlink(&source, &target, &resolved.relative_path)?;
operations.push(operation);
}
// Update tracking
self.tracking.active_profile = profile_name.to_string();
for op in &operations {
if matches!(
op.status,
OperationStatus::Success | OperationStatus::Skipped(_)
) {
let already_tracked = self.tracking.symlinks.iter().any(|s| s.target == op.target);
if !already_tracked {
self.tracking.symlinks.push(TrackedSymlink {
target: op.target.clone(),
source: op.source.clone(),
created_at: op.timestamp,
backup: op.backup.clone(),
});
}
}
}
self.save_tracking()?;
info!(
"Profile activated with inheritance: {} ({} symlinks)",
profile_name,
operations.len()
);
Ok(operations)
}
/// Deactivate a profile by removing its symlinks
pub fn deactivate_profile(&mut self, profile_name: &str) -> Result<Vec<SymlinkOperation>> {
self.deactivate_profile_with_restore(profile_name, true)
}
/// Deactivate all symlinks, optionally restoring original files.
///
/// This deactivates the ENTIRE app - all profile symlinks AND common file symlinks.
/// Useful for temporarily disabling dotstate or as a pre-uninstall step.
///
/// When `restore_files` is true, each symlink is replaced with a copy of the file
/// from the repository, making it appear as if dotstate was never installed.
pub fn deactivate_profile_with_restore(
&mut self,
_profile_name: &str, // Kept for API compatibility, but we deactivate ALL symlinks
restore_files: bool,
) -> Result<Vec<SymlinkOperation>> {
info!(
"Deactivating all symlinks (restore_files: {})",
restore_files
);
let mut operations = Vec::new();
// Deactivate ALL tracked symlinks (profile + common)
let all_symlinks: Vec<_> = self.tracking.symlinks.clone();
for symlink in all_symlinks {
debug!("Removing symlink: {:?}", symlink.target);
let operation = if restore_files {
self.remove_symlink_with_restore(&symlink)?
} else {
self.remove_symlink_completely(&symlink)?
};
operations.push(operation);
}
// Also scan for and remove untracked common file symlinks
// (These might exist from before tracking was implemented)
// We need to recursively walk the common directory for nested paths like .config/atuin/config.toml
let common_path = self.repo_path.join("common");
if common_path.exists() {
let home_dir = crate::utils::get_home_dir();
// Recursively collect all files in common directory
fn collect_common_files(dir: &Path, base: &Path, files: &mut Vec<PathBuf>) {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
// Recurse into subdirectories
collect_common_files(&path, base, files);
} else {
// Add file with relative path from common
if let Ok(relative) = path.strip_prefix(base) {
files.push(relative.to_path_buf());
}
}
}
}
}
let mut common_files = Vec::new();
collect_common_files(&common_path, &common_path, &mut common_files);
for relative_path in common_files {
let target_path = home_dir.join(&relative_path);
// Check if this is a symlink pointing to our common folder
if target_path.is_symlink() {
if let Ok(link_target) = fs::read_link(&target_path) {
let resolved = if link_target.is_absolute() {
link_target
} else if let Some(parent) = target_path.parent() {
parent.join(&link_target)
} else {
link_target
};
if resolved.starts_with(&common_path) {
// Check if we already processed this in tracked symlinks
let already_processed =
operations.iter().any(|op| op.target == target_path);
if !already_processed {
info!("Found untracked common symlink: {:?}", target_path);
let tracked = TrackedSymlink {
target: target_path.clone(),
source: common_path.join(&relative_path),
created_at: Utc::now(),
backup: None,
};
let operation = if restore_files {
self.remove_symlink_with_restore(&tracked)?
} else {
self.remove_symlink_completely(&tracked)?
};
operations.push(operation);
}
}
}
}
}
}
// Clear all tracking
self.tracking.symlinks.clear();
self.tracking.active_profile.clear();
self.save_tracking()?;
info!(
"Deactivated all symlinks ({} symlinks removed)",
operations.len()
);
Ok(operations)
}
/// Switch from one profile to another
pub fn switch_profile(
&mut self,
from: &str,
to: &str,
to_files: &[String],
) -> Result<SwitchReport> {
info!("Switching profile: {} -> {}", from, to);
let mut report = SwitchReport {
removed: Vec::new(),
created: Vec::new(),
errors: Vec::new(),
rollback_performed: false,
};
// Step 1: Deactivate old profile WITHOUT restoring files
// We don't restore because we're about to activate a new profile
// which will either create new symlinks or leave files unmanaged
match self.deactivate_profile_with_restore(from, false) {
Ok(ops) => report.removed = ops,
Err(e) => {
error!("Failed to deactivate profile {}: {}", from, e);
report.errors.push((PathBuf::from(from), e.to_string()));
return Ok(report);
}
}
// Step 2: Activate new profile
match self.activate_profile(to, to_files) {
Ok(ops) => report.created = ops,
Err(e) => {
error!("Failed to activate profile {}: {}", to, e);
report.errors.push((PathBuf::from(to), e.to_string()));
// Attempt rollback - reactivate the old profile
// Note: We don't have access to the old profile's files here,
// so rollback is limited. The caller should handle this better.
warn!("Attempting rollback to profile: {}", from);
// Rollback requires the profile's file list, which we don't have here
// This is a limitation - rollback should be handled at a higher level
report.rollback_performed = false;
report.errors.push((
PathBuf::from("rollback"),
format!(
"Rollback not fully supported - profile '{from}' may need manual reactivation"
),
));
}
}
Ok(report)
}
/// Preview what would happen during a switch (dry run)
#[allow(dead_code)]
pub fn preview_switch(
&self,
from: &str,
to: &str,
to_files: &[String],
) -> Result<SwitchPreview> {
let profile_path = self.repo_path.join(from);
let new_profile_path = self.repo_path.join(to);
let home_dir = crate::utils::get_home_dir();
// What will be removed
let will_remove: Vec<_> = self
.tracking
.symlinks
.iter()
.filter(|s| s.source.starts_with(&profile_path))
.map(|s| s.target.clone())
.collect();
// What will be created
let mut will_create = Vec::new();
let mut conflicts = Vec::new();
for file in to_files {
let source = new_profile_path.join(file);
let target = home_dir.join(file);
will_create.push((target.clone(), source));
// Check for conflicts
if target.exists() && !self.is_our_symlink(&target)? {
conflicts.push(target);
}
}
Ok(SwitchPreview {
will_remove,
will_create,
conflicts,
})
}
/// Check if a path is a symlink that we created (points to our repo)
fn is_our_symlink(&self, path: &Path) -> Result<bool> {
if !path.exists() && path.symlink_metadata().is_err() {
return Ok(false);
}
// Check if it's a symlink
let metadata = path
.symlink_metadata()
.context("Failed to read symlink metadata")?;
if !metadata.is_symlink() {
return Ok(false);
}
// First check: is it tracked?
if self.tracking.symlinks.iter().any(|s| s.target == path) {
return Ok(true);
}
// Second check: does it point to our repo?
// This catches untracked symlinks that were created before tracking was implemented
if let Ok(link_target) = fs::read_link(path) {
let resolved = if link_target.is_absolute() {
link_target
} else if let Some(parent) = path.parent() {
parent.join(&link_target)
} else {
link_target
};
if resolved.starts_with(&self.repo_path) {
return Ok(true);
}
}
Ok(false)
}
/// Create a symlink, backing up any existing file
fn create_symlink(
&self,
source: &Path,
target: &Path,
relative_name: &str,
) -> Result<SymlinkOperation> {
let timestamp = Utc::now();
info!("Creating symlink: {:?} -> {:?}", target, source);
// Check if source exists
if !source.exists() {
warn!("Cannot create symlink: source does not exist: {:?}", source);
return Ok(SymlinkOperation {
source: source.to_path_buf(),
target: target.to_path_buf(),
backup: None,
status: OperationStatus::Failed("Source file does not exist".to_string()),
timestamp,
});
}
debug!("Source exists: {:?}", source);
let mut backup_path = None;
// Handle existing target (file, directory, or symlink)
if target.symlink_metadata().is_ok() {
// Check if it's a symlink first
if let Ok(metadata) = target.symlink_metadata() {
if metadata.is_symlink() {
// It's a symlink - check if it points to the right place
if let Ok(existing_target) = fs::read_link(target) {
// Normalize paths for comparison (handle relative vs absolute)
let existing_normalized = if existing_target.is_absolute() {
existing_target.canonicalize().unwrap_or(existing_target)
} else {
// Relative symlink - resolve relative to target's parent
if let Some(parent) = target.parent() {
parent
.join(&existing_target)
.canonicalize()
.unwrap_or_else(|_| parent.join(&existing_target))
} else {
existing_target
}
};
let source_normalized =
source.canonicalize().unwrap_or(source.to_path_buf());
if existing_normalized == source_normalized {
// Already points to the right place, skip
debug!("Symlink already exists and points to correct location: {:?} -> {:?}", target, source);
return Ok(SymlinkOperation {
source: source.to_path_buf(),
target: target.to_path_buf(),
backup: None,
status: OperationStatus::Skipped(
"Symlink already exists and points to correct location"
.to_string(),
),
timestamp,
});
}
// Symlink points to wrong place - try to resolve and backup the actual file
// if it exists, then remove the symlink
if existing_normalized.exists() {
// Try to canonicalize, but if it fails (orphaned symlink), use the path as-is
let resolved = existing_normalized
.canonicalize()
.unwrap_or(existing_normalized);
if resolved.exists() {
// The symlink points to an existing file - back it up
if let Some(ref session) = self.backup_session {
if let Some(ref backup_mgr) = self.backup_manager {
match backup_mgr.backup_path(
session,
&resolved,
relative_name,
) {
Ok(backup) => backup_path = Some(backup),
Err(e) => {
warn!("Failed to backup file pointed to by symlink {:?}: {}", target, e);
// Continue anyway - we'll still remove the symlink
}
}
}
}
}
}
}
// Remove the symlink (whether we backed up or not)
fs::remove_file(target).with_context(|| {
format!("Failed to remove existing symlink: {target:?}")
})?;
} else if metadata.is_file() || metadata.is_dir() {
// It's a real file or directory, back it up
if let Some(ref session) = self.backup_session {
if let Some(ref backup_mgr) = self.backup_manager {
match backup_mgr.backup_path(session, target, relative_name) {
Ok(backup) => backup_path = Some(backup),
Err(e) => {
warn!("Failed to backup {:?}: {}", target, e);
// Continue anyway - we'll still remove/replace the file
}
}
}
}
if metadata.is_dir() {
fs::remove_dir_all(target).with_context(|| {
format!("Failed to remove existing directory: {target:?}")
})?;
} else {
fs::remove_file(target).with_context(|| {
format!("Failed to remove existing file: {target:?}")
})?;
}
}
}
}
// Create parent directories if needed
if let Some(parent) = target.parent() {
if !parent.exists() {
debug!("Creating parent directory for symlink: {:?}", parent);
fs::create_dir_all(parent).context("Failed to create parent directories")?;
info!("Created parent directory: {:?}", parent);
}
}
// Create the symlink
#[cfg(unix)]
{
debug!("Creating Unix symlink: {:?} -> {:?}", target, source);
std::os::unix::fs::symlink(source, target)
.with_context(|| format!("Failed to create symlink: {target:?} -> {source:?}"))?;
}
#[cfg(windows)]
{
debug!("Creating Windows symlink: {:?} -> {:?}", target, source);
std::os::windows::fs::symlink_file(source, target).with_context(|| {
format!("Failed to create symlink: {:?} -> {:?}", target, source)
})?;
}
info!("Successfully created symlink: {:?} -> {:?}", target, source);
if let Some(ref backup) = backup_path {
debug!("Backup available at: {:?}", backup);
}
Ok(SymlinkOperation {
source: source.to_path_buf(),
target: target.to_path_buf(),
backup: backup_path,
status: OperationStatus::Success,
timestamp,
})
}
/// Remove a symlink, restoring backup if it exists, or copying from repo if no backup
fn remove_symlink_with_restore(&self, tracked: &TrackedSymlink) -> Result<SymlinkOperation> {
let timestamp = Utc::now();
info!("Removing symlink: {:?}", tracked.target);
// Check if the symlink still exists
if !tracked.target.exists() && tracked.target.symlink_metadata().is_err() {
debug!(
"Symlink does not exist, skipping removal: {:?}",
tracked.target
);
return Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Skipped("Symlink does not exist".to_string()),
timestamp,
});
}
// Verify it's still our symlink
if !self.is_our_symlink(&tracked.target)? {
warn!(
"Target is not our symlink, skipping removal: {:?}",
tracked.target
);
return Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Skipped("Not our symlink".to_string()),
timestamp,
});
}
// Remove the symlink
debug!("Removing symlink: {:?}", tracked.target);
fs::remove_file(&tracked.target).context("Failed to remove symlink")?;
info!("Removed symlink: {:?}", tracked.target);
// Restore from repo source first (source of truth)
// Only fall back to backup if repo file doesn't exist
// Errors during restore are warnings, not failures - the symlink was still removed
let restored = 'restore: {
if tracked.source.exists() {
info!(
"Restoring from repo source: {:?} -> {:?}",
tracked.source, tracked.target
);
// Create parent directories if needed
if let Some(parent) = tracked.target.parent() {
if !parent.exists() {
debug!("Creating parent directory for restored file: {:?}", parent);
if let Err(e) = fs::create_dir_all(parent) {
warn!("Failed to create parent directory {:?}: {}", parent, e);
break 'restore false;
}
}
}
// Copy file or directory from repo (source of truth)
match tracked.source.metadata() {
Ok(metadata) => {
if metadata.is_dir() {
debug!(
"Restoring directory from repo: {:?} -> {:?}",
tracked.source, tracked.target
);
match crate::file_manager::copy_dir_all(
&tracked.source,
&tracked.target,
) {
Ok(()) => {
info!("Restored directory from repo: {:?}", tracked.target);
true
}
Err(e) => {
warn!(
"Failed to restore directory {:?}: {}",
tracked.target, e
);
false
}
}
} else {
let file_size = metadata.len();
debug!(
"Restoring file from repo ({} bytes): {:?} -> {:?}",
file_size, tracked.source, tracked.target
);
match fs::copy(&tracked.source, &tracked.target) {
Ok(_) => {
info!("Restored file from repo: {:?}", tracked.target);
true
}
Err(e) => {
warn!("Failed to restore file {:?}: {}", tracked.target, e);
false
}
}
}
}
Err(e) => {
warn!("Failed to read metadata for {:?}: {}", tracked.source, e);
false
}
}
} else {
// Repo file doesn't exist - try backup as last resort
if let Some(backup) = &tracked.backup {
if backup.exists() {
warn!(
"Repo file {:?} not found, restoring from backup {:?}",
tracked.source, backup
);
// Restore from backup (last resort)
debug!(
"Restoring from backup: {:?} -> {:?}",
backup, tracked.target
);
match fs::rename(backup, &tracked.target) {
Ok(()) => {
info!("Restored from backup: {:?}", tracked.target);
true
}
Err(e) => {
warn!("Failed to restore from backup {:?}: {}", backup, e);
false
}
}
} else {
false
}
} else {
false
}
}
};
if !restored {
warn!(
"Could not restore {:?}: repo file doesn't exist, has errors, or no backup available",
tracked.target
);
}
Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Success,
timestamp,
})
}
/// Remove a symlink completely without restoring any files
fn remove_symlink_completely(&self, tracked: &TrackedSymlink) -> Result<SymlinkOperation> {
let timestamp = Utc::now();
// Check if the symlink still exists
if !tracked.target.exists() && tracked.target.symlink_metadata().is_err() {
return Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Skipped("Symlink does not exist".to_string()),
timestamp,
});
}
// Verify it's still our symlink
if !self.is_our_symlink(&tracked.target)? {
return Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Skipped("Not our symlink".to_string()),
timestamp,
});
}
// Remove the symlink (no restore)
fs::remove_file(&tracked.target).context("Failed to remove symlink")?;
Ok(SymlinkOperation {
source: tracked.source.clone(),
target: tracked.target.clone(),
backup: tracked.backup.clone(),
status: OperationStatus::Success,
timestamp,
})
}
/// Remove a symlink, restoring backup if it exists (legacy method, calls `remove_symlink_with_restore`)
fn remove_symlink(&self, tracked: &TrackedSymlink) -> Result<SymlinkOperation> {
self.remove_symlink_with_restore(tracked)
}
/// Rollback to a previous profile state
///
/// This is a simplified rollback that attempts to reactivate the specified profile.
/// In a real scenario, we'd need to restore the exact state from before the switch attempt.
///
/// # Arguments
/// * `profile_name` - Name of the profile to rollback to
/// * `files` - List of files that should be synced for this profile
///
/// # Returns
/// * `Ok(())` if rollback was successful
/// * `Err` if rollback failed
///
/// # Note
/// This function is currently not used because rollback requires the profile's file list,
/// which is not available at the point where rollback would be needed.
#[allow(dead_code)]
fn rollback_to_profile(&mut self, profile_name: &str, files: &[String]) -> Result<()> {
warn!("Rollback functionality is simplified - manual intervention may be needed");
self.activate_profile(profile_name, files)?;
Ok(())
}
/// Save tracking data to disk.
/// Uses atomic write (temp file + rename) to prevent corruption on crash.
pub fn save_tracking(&self) -> Result<()> {
let json = serde_json::to_string_pretty(&self.tracking)
.context("Failed to serialize tracking data")?;
let temp_path = self.tracking_file.with_extension("json.tmp");
// Ensure config directory exists
if let Some(parent) = self.tracking_file.parent() {
fs::create_dir_all(parent).context("Failed to create config directory")?;
}
// Write to temp file first
fs::write(&temp_path, &json).context("Failed to write temp tracking file")?;
// Atomic rename (on POSIX systems)
fs::rename(&temp_path, &self.tracking_file)
.context("Failed to rename temp tracking file")?;
debug!("Tracking data saved to: {:?}", self.tracking_file);
Ok(())
}
/// Get the currently active profile name
/// Get the currently active profile name
#[allow(dead_code)] // Kept for potential future use in CLI or programmatic access
#[must_use]
pub fn get_active_profile(&self) -> Option<&str> {
if self.tracking.active_profile.is_empty() {
None
} else {
Some(&self.tracking.active_profile)
}
}
/// Get all tracked symlinks
/// Get all tracked symlinks
#[allow(dead_code)] // Kept for potential future use in CLI or programmatic access
#[must_use]
pub fn get_tracked_symlinks(&self) -> &[TrackedSymlink] {
&self.tracking.symlinks
}
/// Rename a profile and update all associated symlinks
/// This updates the source paths in the tracking file and recreates symlinks
/// to point to the new profile folder location
pub fn rename_profile(
&mut self,
old_name: &str,
new_name: &str,
) -> Result<Vec<SymlinkOperation>> {
info!("Renaming profile: {} -> {}", old_name, new_name);
let old_profile_path = self.repo_path.join(old_name);
let new_profile_path = self.repo_path.join(new_name);
let mut operations = Vec::new();
// Find all symlinks for this profile
let profile_symlinks: Vec<_> = self
.tracking
.symlinks
.iter()
.filter(|s| s.source.starts_with(&old_profile_path))
.cloned()
.collect();
if profile_symlinks.is_empty() {
// No symlinks to update, but still update active_profile name if needed
if self.tracking.active_profile == old_name {
self.tracking.active_profile = new_name.to_string();
self.save_tracking()?;
}
return Ok(operations);
}
// Update each symlink
for symlink in &profile_symlinks {
// Calculate new source path
let relative_path = match symlink.source.strip_prefix(&old_profile_path) {
Ok(path) => path,
Err(e) => {
error!(
"Failed to get relative path from {:?}: {}",
symlink.source, e
);
continue;
}
};
let new_source = new_profile_path.join(relative_path);
// Get relative name for create_symlink (e.g., ".zshrc" from "/path/to/repo/old/.zshrc")
let relative_name = relative_path.to_string_lossy().to_string();
// Remove old symlink
let remove_op = self.remove_symlink(symlink)?;
operations.push(remove_op);
// Create new symlink pointing to new source
let create_op = self.create_symlink(&new_source, &symlink.target, &relative_name)?;
operations.push(create_op);
}
// Update tracking: remove old entries and add new ones
self.tracking
.symlinks
.retain(|s| !s.source.starts_with(&old_profile_path));
// Add updated entries
for symlink in &profile_symlinks {
let relative_path = match symlink.source.strip_prefix(&old_profile_path) {
Ok(path) => path,
Err(e) => {
error!(
"Failed to get relative path from {:?}: {}",
symlink.source, e
);
continue;
}
};
let new_source = new_profile_path.join(relative_path);
self.tracking.symlinks.push(TrackedSymlink {
target: symlink.target.clone(),
source: new_source,
created_at: symlink.created_at,
backup: symlink.backup.clone(),
});
}
// Update active profile name if this was the active profile
if self.tracking.active_profile == old_name {
self.tracking.active_profile = new_name.to_string();
}
self.save_tracking()?;
info!(
"Profile renamed: {} -> {} ({} symlinks updated)",
old_name,
new_name,
profile_symlinks.len()
);
Ok(operations)
}
/// Add a single symlink to an existing profile.
///
/// This is more efficient than calling `activate_profile` with a single file,
/// as it doesn't need to iterate or create unnecessary data structures.
///
/// # Arguments
///
/// * `profile_name` - Name of the profile
/// * `relative_path` - Path relative to home directory (e.g., ".zshrc")
///
/// # Returns
///
/// The symlink operation result
pub fn add_symlink_to_profile(
&mut self,
profile_name: &str,
relative_path: &str,
) -> Result<SymlinkOperation> {
let profile_path = self.repo_path.join(profile_name);
let source = profile_path.join(relative_path);
let home_dir = crate::utils::get_home_dir();
let target = home_dir.join(relative_path);
info!(
"Adding symlink to profile {}: {} -> {:?}",
profile_name, relative_path, source
);
// Create backup session if backups are enabled and not already created
if self.backup_enabled && self.backup_session.is_none() {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
debug!("Created backup session: {:?}", self.backup_session);
}
}
// Create the symlink
let operation = self.create_symlink(&source, &target, relative_path)?;
// Update tracking if successful
if matches!(operation.status, OperationStatus::Success) {
self.tracking.symlinks.push(TrackedSymlink {
target: operation.target.clone(),
source: operation.source.clone(),
created_at: operation.timestamp,
backup: operation.backup.clone(),
});
// Update active profile if not set
if self.tracking.active_profile.is_empty() {
self.tracking.active_profile = profile_name.to_string();
}
self.save_tracking()?;
info!("Successfully added symlink for {}", relative_path);
}
Ok(operation)
}
/// Ensure all files in a profile have their symlinks created.
///
/// This is an efficient "reconciliation" method that only creates symlinks for files
/// that are missing them. It's perfect for after pulling changes from remote, where
/// new files may have been added but their symlinks don't exist locally yet.
///
/// Unlike `activate_profile`, this does NOT remove any existing symlinks - it only
/// adds missing ones.
///
/// # Arguments
///
/// * `profile_name` - Name of the profile
/// * `files` - List of files that should have symlinks (relative paths)
///
/// # Returns
///
/// A tuple of (`created_count`, `skipped_count`, errors)
pub fn ensure_profile_symlinks(
&mut self,
profile_name: &str,
files: &[String],
) -> Result<(usize, usize, Vec<String>)> {
let resolved =
crate::utils::profile_manifest::ResolvedFile::from_files(profile_name, files);
self.ensure_resolved_symlinks(profile_name, &resolved)
}
/// Ensure all resolved files have their symlinks created.
///
/// Like `ensure_profile_symlinks` but works with `ResolvedFile` entries
/// that may come from different profile directories due to inheritance.
/// Only creates missing symlinks; does NOT remove existing ones.
pub fn ensure_resolved_symlinks(
&mut self,
profile_name: &str,
resolved_files: &[crate::utils::profile_manifest::ResolvedFile],
) -> Result<(usize, usize, Vec<String>)> {
info!(
"Ensuring resolved symlinks for profile '{}' ({} files)",
profile_name,
resolved_files.len()
);
let home_dir = crate::utils::get_home_dir();
let mut created_count = 0;
let mut skipped_count = 0;
let mut errors = Vec::new();
// Create backup session if backups are enabled
if self.backup_enabled && self.backup_session.is_none() {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
debug!("Created backup session: {:?}", self.backup_session);
}
}
for resolved in resolved_files {
let source = self
.repo_path
.join(&resolved.source_profile)
.join(&resolved.relative_path);
let target = home_dir.join(&resolved.relative_path);
// Check if source exists in repo
if !source.exists() {
debug!("Source file does not exist in repo, skipping: {:?}", source);
skipped_count += 1;
continue;
}
// Check if symlink already exists and points to the right place
if let Ok(metadata) = target.symlink_metadata() {
if metadata.is_symlink() {
if let Ok(existing_target) = fs::read_link(&target) {
let existing_normalized = if existing_target.is_absolute() {
existing_target.canonicalize().unwrap_or(existing_target)
} else if let Some(parent) = target.parent() {
parent
.join(&existing_target)
.canonicalize()
.unwrap_or_else(|_| parent.join(&existing_target))
} else {
existing_target
};
let source_normalized = source.canonicalize().unwrap_or(source.clone());
if existing_normalized == source_normalized {
debug!(
"Symlink already exists and is correct, skipping: {:?}",
target
);
skipped_count += 1;
continue;
}
}
} else {
errors.push(format!(
"File exists at {} (not a symlink)",
resolved.relative_path
));
continue;
}
}
// Symlink doesn't exist or is incorrect - create it
match self.create_symlink(&source, &target, &resolved.relative_path) {
Ok(operation) => {
if matches!(operation.status, OperationStatus::Success) {
self.tracking.symlinks.push(TrackedSymlink {
target: operation.target.clone(),
source: operation.source.clone(),
created_at: operation.timestamp,
backup: operation.backup.clone(),
});
if self.tracking.active_profile.is_empty() {
self.tracking.active_profile = profile_name.to_string();
}
created_count += 1;
info!("Created symlink for {}", resolved.relative_path);
} else {
warn!(
"Failed to create symlink for {}: {:?}",
resolved.relative_path, operation.status
);
errors.push(format!(
"Failed to create symlink for {}",
resolved.relative_path
));
}
}
Err(e) => {
error!(
"Error creating symlink for {}: {}",
resolved.relative_path, e
);
errors.push(format!("Error for {}: {e}", resolved.relative_path));
}
}
}
if created_count > 0 {
self.save_tracking()?;
}
info!(
"Resolved symlink reconciliation complete: {} created, {} skipped, {} errors",
created_count,
skipped_count,
errors.len()
);
Ok((created_count, skipped_count, errors))
}
/// Remove a specific symlink from tracking without affecting other symlinks.
///
/// This is a surgical operation that only updates the tracking data for a single file,
/// unlike `deactivate_profile` which removes all symlinks for a profile.
///
/// # Arguments
///
/// * `profile_name` - Name of the profile
/// * `relative_path` - Path relative to home directory (e.g., ".zshrc")
///
/// # Returns
///
/// Result indicating success or failure
pub fn remove_symlink_from_tracking(
&mut self,
profile_name: &str,
relative_path: &str,
) -> Result<()> {
let profile_path = self.repo_path.join(profile_name);
let source_path = profile_path.join(relative_path);
debug!(
"Removing symlink from tracking: profile={}, path={}",
profile_name, relative_path
);
// Remove the specific symlink from tracking
let initial_count = self.tracking.symlinks.len();
self.tracking.symlinks.retain(|s| s.source != source_path);
let removed_count = initial_count - self.tracking.symlinks.len();
if removed_count > 0 {
info!(
"Removed {} symlink(s) from tracking for {}",
removed_count, relative_path
);
self.save_tracking()?;
} else {
debug!(
"No symlink found in tracking for {} (may have already been removed)",
relative_path
);
}
Ok(())
}
// ============================================================================
// Common File Methods - For files shared across all profiles
// ============================================================================
/// Add a symlink for a common file (shared across all profiles).
///
/// Common files are stored in the "common" folder at the repository root
/// and are symlinked regardless of which profile is active.
///
/// # Arguments
///
/// * `relative_path` - Path relative to home directory (e.g., ".gitconfig")
///
/// # Returns
///
/// The symlink operation result
pub fn add_common_symlink(&mut self, relative_path: &str) -> Result<SymlinkOperation> {
let common_path = self.repo_path.join("common");
let source = common_path.join(relative_path);
let home_dir = crate::utils::get_home_dir();
let target = home_dir.join(relative_path);
info!("Adding common symlink: {} -> {:?}", relative_path, source);
// Ensure common directory exists
if !common_path.exists() {
fs::create_dir_all(&common_path).context("Failed to create common directory")?;
}
// Create backup session if backups are enabled and not already created
if self.backup_enabled && self.backup_session.is_none() {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
debug!("Created backup session: {:?}", self.backup_session);
}
}
// Create the symlink
let operation = self.create_symlink(&source, &target, relative_path)?;
// Update tracking if successful
if matches!(operation.status, OperationStatus::Success) {
self.tracking.symlinks.push(TrackedSymlink {
target: operation.target.clone(),
source: operation.source.clone(),
created_at: operation.timestamp,
backup: operation.backup.clone(),
});
self.save_tracking()?;
info!("Successfully added common symlink for {}", relative_path);
}
Ok(operation)
}
/// Remove a symlink for a common file and restore original if exists.
///
/// # Arguments
///
/// * `relative_path` - Path relative to home directory (e.g., ".gitconfig")
///
/// # Returns
///
/// The symlink operation result
pub fn remove_common_symlink(&mut self, relative_path: &str) -> Result<SymlinkOperation> {
let common_path = self.repo_path.join("common");
let source_path = common_path.join(relative_path);
info!("Removing common symlink: {}", relative_path);
// Find the tracked symlink
let symlink = self
.tracking
.symlinks
.iter()
.find(|s| s.source == source_path)
.cloned();
let operation = if let Some(tracked) = symlink {
self.remove_symlink_with_restore(&tracked)?
} else {
// Not tracked, but try to remove if it exists
let home_dir = crate::utils::get_home_dir();
let target = home_dir.join(relative_path);
if target.symlink_metadata().is_ok() {
fs::remove_file(&target)
.with_context(|| format!("Failed to remove symlink: {target:?}"))?;
}
SymlinkOperation {
source: source_path.clone(),
target,
backup: None,
status: OperationStatus::Success,
timestamp: Utc::now(),
}
};
// Remove from tracking
self.tracking.symlinks.retain(|s| s.source != source_path);
self.save_tracking()?;
Ok(operation)
}
/// Remove a common symlink from tracking only (without touching the actual symlink).
///
/// # Arguments
///
/// * `relative_path` - Path relative to home directory
pub fn remove_common_symlink_from_tracking(&mut self, relative_path: &str) -> Result<()> {
let common_path = self.repo_path.join("common");
let source_path = common_path.join(relative_path);
debug!(
"Removing common symlink from tracking: path={}",
relative_path
);
let initial_count = self.tracking.symlinks.len();
self.tracking.symlinks.retain(|s| s.source != source_path);
let removed_count = initial_count - self.tracking.symlinks.len();
if removed_count > 0 {
info!(
"Removed {} common symlink(s) from tracking for {}",
removed_count, relative_path
);
self.save_tracking()?;
}
Ok(())
}
/// Ensure all common files have their symlinks created.
///
/// This is an efficient "reconciliation" method for common files.
///
/// # Arguments
///
/// * `files` - List of common files that should have symlinks (relative paths)
///
/// # Returns
///
/// A tuple of (`created_count`, `skipped_count`, errors)
pub fn ensure_common_symlinks(
&mut self,
files: &[String],
) -> Result<(usize, usize, Vec<String>)> {
info!("Ensuring common symlinks ({} files)", files.len());
let common_path = self.repo_path.join("common");
let home_dir = crate::utils::get_home_dir();
let mut created_count = 0;
let mut skipped_count = 0;
let mut errors = Vec::new();
// Create backup session if backups are enabled
if self.backup_enabled && self.backup_session.is_none() {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
debug!("Created backup session: {:?}", self.backup_session);
}
}
for relative_path in files {
let source = common_path.join(relative_path);
let target = home_dir.join(relative_path);
// Check if source exists in repo
if !source.exists() {
debug!("Common source file does not exist, skipping: {:?}", source);
skipped_count += 1;
continue;
}
// Check if symlink already exists and points to the right place
if target.symlink_metadata().is_ok() {
if let Ok(metadata) = target.symlink_metadata() {
if metadata.is_symlink() {
if let Ok(existing_target) = fs::read_link(&target) {
let existing_normalized = if existing_target.is_absolute() {
existing_target.canonicalize().unwrap_or(existing_target)
} else if let Some(parent) = target.parent() {
parent
.join(&existing_target)
.canonicalize()
.unwrap_or_else(|_| parent.join(&existing_target))
} else {
existing_target
};
let source_normalized = source.canonicalize().unwrap_or(source.clone());
if existing_normalized == source_normalized {
debug!(
"Common symlink already exists and is correct, skipping: {:?}",
target
);
skipped_count += 1;
continue;
}
}
} else {
errors.push(format!("File exists at {relative_path} (not a symlink)"));
continue;
}
}
}
// Create the symlink
match self.create_symlink(&source, &target, relative_path) {
Ok(op) => {
if matches!(op.status, OperationStatus::Success) {
created_count += 1;
self.tracking.symlinks.push(TrackedSymlink {
target: op.target,
source: op.source,
created_at: op.timestamp,
backup: op.backup,
});
}
}
Err(e) => {
errors.push(format!(
"Failed to create common symlink for {relative_path}: {e}"
));
}
}
}
if created_count > 0 {
self.save_tracking()?;
}
info!(
"Common symlinks: {} created, {} skipped, {} errors",
created_count,
skipped_count,
errors.len()
);
Ok((created_count, skipped_count, errors))
}
/// Activate all common files by creating their symlinks.
///
/// # Arguments
///
/// * `files` - List of common files to activate
///
/// # Returns
///
/// List of symlink operations
pub fn activate_common_files(&mut self, files: &[String]) -> Result<Vec<SymlinkOperation>> {
info!("Activating common files ({} files)", files.len());
let common_path = self.repo_path.join("common");
// Ensure common directory exists
if !common_path.exists() {
fs::create_dir_all(&common_path).context("Failed to create common directory")?;
}
// Create backup session if backups are enabled
if self.backup_enabled && self.backup_session.is_none() {
if let Some(ref backup_mgr) = self.backup_manager {
self.backup_session = Some(backup_mgr.create_backup_session()?);
}
}
let mut operations = Vec::new();
let home_dir = crate::utils::get_home_dir();
for file in files {
let source = common_path.join(file);
let target = home_dir.join(file);
let operation = self.create_symlink(&source, &target, file)?;
// Track both Success AND Skipped (Skipped = symlink already correct, still ours)
if matches!(
operation.status,
OperationStatus::Success | OperationStatus::Skipped(_)
) {
// Check if already tracked (avoid duplicates)
let already_tracked = self
.tracking
.symlinks
.iter()
.any(|s| s.target == operation.target);
if !already_tracked {
self.tracking.symlinks.push(TrackedSymlink {
target: operation.target.clone(),
source: operation.source.clone(),
created_at: operation.timestamp,
backup: operation.backup.clone(),
});
}
}
operations.push(operation);
}
self.save_tracking()?;
info!("Activated {} common files", operations.len());
Ok(operations)
}
/// Check if a symlink is for a common file.
///
/// # Arguments
///
/// * `source_path` - The source path of the symlink
///
/// # Returns
///
/// True if the symlink is for a common file
#[must_use]
pub fn is_common_symlink(&self, source_path: &Path) -> bool {
let common_path = self.repo_path.join("common");
source_path.starts_with(&common_path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
fn setup_test_env() -> (TempDir, SymlinkManager) {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().join("dotstate");
let config_dir = temp_dir.path().join("config"); // Isolated config directory
fs::create_dir_all(&repo_path).unwrap();
fs::create_dir_all(&config_dir).unwrap();
// Use isolated config directory to avoid polluting real user config
let manager = SymlinkManager::new_with_config_dir(repo_path, false, config_dir).unwrap();
(temp_dir, manager)
}
#[test]
fn test_create_symlink_manager() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().join("dotstate");
fs::create_dir_all(&repo_path).unwrap();
// Disable backups to avoid issues with home directory in CI
let manager = SymlinkManager::new_with_backup(repo_path.clone(), false);
assert!(manager.is_ok());
}
#[test]
fn test_activate_profile() {
let (temp_dir, mut manager) = setup_test_env();
// Create a profile directory with a file
let profile_path = temp_dir.path().join("dotstate/test-profile");
fs::create_dir_all(&profile_path).unwrap();
let test_file = profile_path.join(".testrc");
File::create(&test_file)
.unwrap()
.write_all(b"test content")
.unwrap();
// Track the symlink target for cleanup
let symlink_target = temp_dir.path().join(".testrc");
// Activate profile
let resolved = vec![crate::utils::profile_manifest::ResolvedFile {
relative_path: ".testrc".to_string(),
source_profile: "test-profile".to_string(),
}];
let result =
manager.activate_resolved_with_home("test-profile", &resolved, temp_dir.path());
assert!(result.is_ok(), "activate_profile error: {:?}", result.err());
let operations = result.unwrap();
assert_eq!(operations.len(), 1);
assert!(matches!(operations[0].status, OperationStatus::Success));
// Cleanup: remove the symlink created in the home directory
let _ = fs::remove_file(&symlink_target);
}
// More tests would go here...
}