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
//! Auto-fix routines for validation warnings and errors.
//!
//! [`ValidationFixer`] owns all the "apply a fix for this warning" logic —
//! the dispatch hub is [`ValidationFixer::fix_warning`], which exhaustively
//! matches every [`super::types::ValidationWarning`] variant and delegates to
//! a per-variant helper. Callers that want to avoid knowing about variants at
//! all should go through `fix_warning` / `fix_error` / `fix_all`.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::error::Result;
use crate::fs::AsyncFileSystem;
use crate::link_parser::{self, LinkFormat};
use crate::path_utils::{normalize_sync_path, strip_workspace_root_prefix};
use crate::utils::path::relative_path_from_file_to_target;
use crate::workspace::Workspace;
use super::check::{canonicalize_link_value, expected_self_link};
use super::types::{
InvalidAttachmentRefKind, ValidationError, ValidationResult, ValidationWarning,
};
// ============================================================================
// ValidationFixer - Fix validation issues
// ============================================================================
/// Result of attempting to fix a validation issue.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub struct FixResult {
/// Whether the fix was successful.
pub success: bool,
/// Description of what was done (or why it failed).
pub message: String,
}
impl FixResult {
/// Create a successful fix result.
pub fn success(message: impl Into<String>) -> Self {
Self {
success: true,
message: message.into(),
}
}
/// Create a failed fix result.
pub fn failure(message: impl Into<String>) -> Self {
Self {
success: false,
message: message.into(),
}
}
}
/// Fixer for validation issues (async-first).
///
/// This struct provides methods to automatically fix validation errors and warnings.
pub struct ValidationFixer<FS: AsyncFileSystem> {
fs: FS,
link_format: LinkFormat,
root_path: Option<PathBuf>,
}
impl<FS: AsyncFileSystem> ValidationFixer<FS> {
/// Create a new fixer.
pub fn new(fs: FS) -> Self {
Self {
fs,
link_format: LinkFormat::default(),
root_path: None,
}
}
/// Create a new fixer with workspace link format support.
pub fn with_link_format(fs: FS, root_path: PathBuf, link_format: LinkFormat) -> Self {
Self {
fs,
link_format,
root_path: Some(root_path),
}
}
// ==================== Internal Frontmatter Helpers ====================
/// Get a frontmatter property from a file. Returns `None` if the file
/// doesn't exist, has no frontmatter, or the key is missing.
async fn get_frontmatter_property(
&self,
path: &Path,
key: &str,
) -> Option<crate::yaml_value::YamlValue> {
let content = self.fs.read_to_string(path).await.ok()?;
let parsed = crate::frontmatter::parse_or_empty(&content).ok()?;
crate::frontmatter::get_property(&parsed.frontmatter, key).cloned()
}
/// Set a frontmatter property in a file, creating the file (and
/// frontmatter block) if necessary.
async fn set_frontmatter_property(
&self,
path: &Path,
key: &str,
value: crate::yaml_value::YamlValue,
) -> Result<()> {
let (mut frontmatter, body) = match self.fs.read_to_string(path).await {
Ok(content) => {
let parsed = crate::frontmatter::parse_or_empty(&content)?;
(parsed.frontmatter, parsed.body)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
(indexmap::IndexMap::new(), String::new())
}
Err(e) => {
return Err(crate::error::DiaryxError::FileRead {
path: path.to_path_buf(),
source: e,
});
}
};
crate::frontmatter::set_property(&mut frontmatter, key, value);
let new_content = crate::frontmatter::serialize(&frontmatter, &body)?;
self.fs.write_file(path, &new_content).await.map_err(|e| {
crate::error::DiaryxError::FileWrite {
path: path.to_path_buf(),
source: e,
}
})
}
/// Remove a frontmatter property from a file. A missing file or missing
/// property is treated as a no-op.
async fn remove_frontmatter_property(&self, path: &Path, key: &str) -> Result<()> {
let Ok(content) = self.fs.read_to_string(path).await else {
return Ok(()); // File doesn't exist — nothing to remove.
};
let mut parsed = crate::frontmatter::parse_or_empty(&content)?;
if parsed.frontmatter.is_empty() {
return Ok(()); // No frontmatter or malformed block.
}
crate::frontmatter::remove_property(&mut parsed.frontmatter, key);
let new_content = crate::frontmatter::serialize(&parsed.frontmatter, &parsed.body)?;
self.fs.write_file(path, &new_content).await.map_err(|e| {
crate::error::DiaryxError::FileWrite {
path: path.to_path_buf(),
source: e,
}
})
}
// ==================== Link Format Helpers ====================
/// Get the canonical (workspace-relative) path for a filesystem path.
pub(super) fn get_canonical(&self, path: &Path) -> String {
let raw = if let Some(ref root) = self.root_path {
let path_string = path.to_string_lossy();
strip_workspace_root_prefix(&path_string, root)
.unwrap_or_else(|| path_string.to_string())
} else {
path.to_string_lossy().to_string()
};
normalize_sync_path(&raw)
}
/// Read title from a file's frontmatter, falling back to filename stem.
async fn resolve_title(&self, path: &Path) -> String {
if let Ok(content) = self.fs.read_to_string(path).await
&& let Ok(parsed) = crate::frontmatter::parse_or_empty(&content)
&& let Some(title) = crate::frontmatter::get_string(&parsed.frontmatter, "title")
{
return title.to_string();
}
path.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Untitled")
.to_string()
}
/// Format a link from one file to another using the configured link format.
/// Falls back to a plain relative path when no root_path is configured.
async fn format_link(&self, target: &Path, from: &Path) -> String {
if self.root_path.is_some() {
let target_canonical = self.get_canonical(target);
let from_canonical = self.get_canonical(from);
let title = self.resolve_title(target).await;
link_parser::format_link_with_format(
&target_canonical,
&title,
self.link_format,
&from_canonical,
)
} else {
relative_path_from_file_to_target(from, target)
}
}
async fn format_self_link(&self, file: &Path) -> String {
let canonical = self.get_canonical(file);
let title = self.resolve_title(file).await;
link_parser::format_link_with_format(&canonical, &title, self.link_format, &canonical)
}
// ==================== Fix Methods ====================
/// Fix a broken `part_of` reference by removing it.
pub async fn fix_broken_part_of(&self, file: &Path) -> FixResult {
match self.remove_frontmatter_property(file, "part_of").await {
Ok(_) => FixResult::success(format!("Removed broken part_of from {}", file.display())),
Err(e) => FixResult::failure(format!(
"Failed to remove part_of from {}: {}",
file.display(),
e
)),
}
}
/// Fix a broken `contents` reference by removing it from the index.
pub async fn fix_broken_contents_ref(&self, index: &Path, target: &str) -> FixResult {
match self.get_frontmatter_property(index, "contents").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| {
if let crate::yaml_value::YamlValue::String(s) = item {
s != target
} else {
true
}
})
.collect();
match self
.set_frontmatter_property(
index,
"contents",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed broken contents ref '{}' from {}",
target,
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update contents in {}: {}",
index.display(),
e
)),
}
}
_ => FixResult::failure(format!("Could not read contents from {}", index.display())),
}
}
/// Fix a broken `attachments` reference by removing it.
pub async fn fix_broken_attachment(&self, file: &Path, attachment: &str) -> FixResult {
match self.get_frontmatter_property(file, "attachments").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| {
if let crate::yaml_value::YamlValue::String(s) = item {
s != attachment
} else {
true
}
})
.collect();
let result = if filtered.is_empty() {
self.remove_frontmatter_property(file, "attachments").await
} else {
self.set_frontmatter_property(
file,
"attachments",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
};
match result {
Ok(_) => FixResult::success(format!(
"Removed broken attachment '{}' from {}",
attachment,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachments in {}: {}",
file.display(),
e
)),
}
}
_ => FixResult::failure(format!(
"Could not read attachments from {}",
file.display()
)),
}
}
/// Fix a non-portable path by replacing it with the normalized version.
pub async fn fix_non_portable_path(
&self,
file: &Path,
property: &str,
old_value: &str,
new_value: &str,
) -> FixResult {
match property {
"part_of" => {
match self
.set_frontmatter_property(
file,
"part_of",
crate::yaml_value::YamlValue::String(new_value.to_string()),
)
.await
{
Ok(_) => FixResult::success(format!(
"Normalized {} '{}' -> '{}' in {}",
property,
old_value,
new_value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update {} in {}: {}",
property,
file.display(),
e
)),
}
}
"contents" | "attachments" | "links" | "link_of" => {
match self.get_frontmatter_property(file, property).await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let updated: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.map(|item| {
if let crate::yaml_value::YamlValue::String(ref s) = item
&& s == old_value
{
return crate::yaml_value::YamlValue::String(
new_value.to_string(),
);
}
item
})
.collect();
match self
.set_frontmatter_property(
file,
property,
crate::yaml_value::YamlValue::Sequence(updated),
)
.await
{
Ok(_) => FixResult::success(format!(
"Normalized {} '{}' -> '{}' in {}",
property,
old_value,
new_value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update {} in {}: {}",
property,
file.display(),
e
)),
}
}
_ => FixResult::failure(format!(
"Could not read {} from {}",
property,
file.display()
)),
}
}
_ => FixResult::failure(format!("Unknown property: {}", property)),
}
}
/// Rename a file with a non-portable filename to a sanitized version.
pub async fn fix_non_portable_filename(
&self,
file: &Path,
suggested_filename: &str,
) -> FixResult {
let ws = Workspace::new(&self.fs);
match ws.rename_entry(file, suggested_filename).await {
Ok(new_path) => FixResult::success(format!(
"Renamed '{}' -> '{}'",
file.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default(),
new_path.display()
)),
Err(e) => FixResult::failure(format!("Failed to rename {}: {}", file.display(), e)),
}
}
/// Add an unlisted file to an index's contents.
pub async fn fix_unlisted_file(&self, index: &Path, file: &Path) -> FixResult {
let formatted = self.format_link(file, index).await;
match self.get_frontmatter_property(index, "contents").await {
Some(crate::yaml_value::YamlValue::Sequence(mut items)) => {
items.push(crate::yaml_value::YamlValue::String(formatted.clone()));
match self
.set_frontmatter_property(
index,
"contents",
crate::yaml_value::YamlValue::Sequence(items),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added '{}' to contents in {}",
formatted,
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update contents in {}: {}",
index.display(),
e
)),
}
}
None => {
// No contents yet, create it
match self
.set_frontmatter_property(
index,
"contents",
crate::yaml_value::YamlValue::Sequence(vec![
crate::yaml_value::YamlValue::String(formatted.clone()),
]),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added '{}' to new contents in {}",
formatted,
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to create contents in {}: {}",
index.display(),
e
)),
}
}
_ => FixResult::failure(format!("Could not read contents from {}", index.display())),
}
}
/// Derive the canonical attachment-note path for a binary asset.
///
/// The wrapper note lives next to the binary with `.md` appended so the
/// original extension stays visible (e.g. `photo.jpg` → `photo.jpg.md`).
fn attachment_wrapper_note_path(&self, binary: &Path) -> std::result::Result<PathBuf, String> {
let binary_filename = binary
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| format!("Cannot derive filename for binary {}", binary.display()))?;
let parent_dir = binary
.parent()
.ok_or_else(|| format!("Binary {} has no parent directory", binary.display()))?;
Ok(parent_dir.join(format!("{binary_filename}.md")))
}
/// Create a fresh markdown attachment note that wraps `binary`, with an
/// `attachment_of` backlink to `backlink_index` seeded at creation time.
///
/// Both auto-fixers that spawn wrapper notes (`fix_orphan_binary_file`
/// and `fix_invalid_attachment_ref`) go through this helper so the note
/// is immediately backlink-consistent — the user does not need a second
/// round of backlink autofixes to settle the workspace. The backlink is
/// formatted with the same `expected_self_link` helper the validator
/// uses when suggesting `MissingAttachmentBacklink` fixes, so the two
/// paths produce byte-identical values.
async fn create_attachment_wrapper_note(
&self,
binary: &Path,
note_path: &Path,
backlink_index: &Path,
) -> std::result::Result<(), String> {
let binary_filename = binary
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("attachment");
let self_link = self.format_self_link(note_path).await;
let attachment_link = self.format_attachment_link(binary, note_path).await;
let index_title = self.resolve_title(backlink_index).await;
let backlink = expected_self_link(
&self.get_canonical(backlink_index),
Some(&index_title),
Some(self.link_format),
);
let content = format!(
"---\ntitle: {title}\nlink: \"{self_link}\"\nattachment: \"{attachment_link}\"\nattachment_of:\n - \"{backlink}\"\n---\n",
title = binary_filename,
);
self.fs.write_file(note_path, &content).await.map_err(|e| {
format!(
"Failed to create attachment note {}: {}",
note_path.display(),
e
)
})
}
/// Wrap an orphan binary file in a markdown attachment note and add that
/// note to an index's `attachments` list.
///
/// Under the current attachment model, `attachments` must contain markdown
/// "attachment notes" — a note has an `attachment:` property pointing at
/// the binary asset. This fix creates such a note next to the binary (if
/// one doesn't already exist) and links the note — not the binary — into
/// the index.
pub async fn fix_orphan_binary_file(&self, index: &Path, file: &Path) -> FixResult {
let note_path = match self.attachment_wrapper_note_path(file) {
Ok(p) => p,
Err(msg) => return FixResult::failure(msg),
};
if !self.fs.exists(¬e_path).await
&& let Err(msg) = self
.create_attachment_wrapper_note(file, ¬e_path, index)
.await
{
return FixResult::failure(msg);
}
// Reference the NOTE (not the binary) from the index's attachments.
let note_link = self.format_link(¬e_path, index).await;
match self.get_frontmatter_property(index, "attachments").await {
Some(crate::yaml_value::YamlValue::Sequence(mut items)) => {
if !items.iter().any(
|v| matches!(v, crate::yaml_value::YamlValue::String(s) if s == ¬e_link),
) {
items.push(crate::yaml_value::YamlValue::String(note_link.clone()));
}
match self
.set_frontmatter_property(
index,
"attachments",
crate::yaml_value::YamlValue::Sequence(items),
)
.await
{
Ok(_) => FixResult::success(format!(
"Wrapped '{}' in attachment note and added to {}",
file.display(),
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachments in {}: {}",
index.display(),
e
)),
}
}
None => match self
.set_frontmatter_property(
index,
"attachments",
crate::yaml_value::YamlValue::Sequence(vec![
crate::yaml_value::YamlValue::String(note_link.clone()),
]),
)
.await
{
Ok(_) => FixResult::success(format!(
"Wrapped '{}' in attachment note and added to new attachments in {}",
file.display(),
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to create attachments in {}: {}",
index.display(),
e
)),
},
_ => FixResult::failure(format!(
"Could not read attachments from {}",
index.display()
)),
}
}
/// Migrate a legacy flat-format `attachments` entry (which points directly
/// at a binary asset) to the current attachment-note model.
///
/// The fix wraps the binary in a markdown attachment note next to it
/// (creating one if needed) and rewrites the source index's `attachments`
/// list entry to point at the new note. The resulting missing
/// `attachment_of` backlink on the note is handled by the existing
/// backlink autofix on a subsequent pass.
pub async fn fix_invalid_attachment_ref(
&self,
index: &Path,
target: &str,
binary: &Path,
) -> FixResult {
let note_path = match self.attachment_wrapper_note_path(binary) {
Ok(p) => p,
Err(msg) => return FixResult::failure(msg),
};
if !self.fs.exists(¬e_path).await
&& let Err(msg) = self
.create_attachment_wrapper_note(binary, ¬e_path, index)
.await
{
return FixResult::failure(msg);
}
let note_link = self.format_link(¬e_path, index).await;
match self.get_frontmatter_property(index, "attachments").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let mut replaced = false;
let mut rewritten: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.map(|item| match item {
crate::yaml_value::YamlValue::String(s) if s == target => {
replaced = true;
crate::yaml_value::YamlValue::String(note_link.clone())
}
other => other,
})
.collect();
if !replaced {
return FixResult::failure(format!(
"Could not find attachment entry '{}' in {}",
target,
index.display()
));
}
// Drop any duplicates of the new note link that may now exist.
let mut seen_note_link = false;
rewritten.retain(|item| match item {
crate::yaml_value::YamlValue::String(s) if s == ¬e_link => {
if seen_note_link {
false
} else {
seen_note_link = true;
true
}
}
_ => true,
});
match self
.set_frontmatter_property(
index,
"attachments",
crate::yaml_value::YamlValue::Sequence(rewritten),
)
.await
{
Ok(_) => FixResult::success(format!(
"Wrapped '{}' in attachment note and updated {}",
binary.display(),
index.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachments in {}: {}",
index.display(),
e
)),
}
}
_ => FixResult::failure(format!(
"Could not read attachments from {}",
index.display()
)),
}
}
/// Format a frontmatter `attachment:` link from a note to a binary asset.
/// Preserves the filename (with extension) as the link title so prettification
/// doesn't drop extensions like `.png`.
async fn format_attachment_link(&self, binary: &Path, from_note: &Path) -> String {
if self.root_path.is_some() {
let target_canonical = self.get_canonical(binary);
let from_canonical = self.get_canonical(from_note);
let title = binary
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&target_canonical)
.to_string();
link_parser::format_link_with_format(
&target_canonical,
&title,
self.link_format,
&from_canonical,
)
} else {
relative_path_from_file_to_target(from_note, binary)
}
}
/// Fix a missing `part_of` by setting it to point to the given index.
pub async fn fix_missing_part_of(&self, file: &Path, index: &Path) -> FixResult {
let formatted = self.format_link(index, file).await;
match self
.set_frontmatter_property(
file,
"part_of",
crate::yaml_value::YamlValue::String(formatted.clone()),
)
.await
{
Ok(_) => FixResult::success(format!(
"Set part_of to '{}' in {}",
formatted,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to set part_of in {}: {}",
file.display(),
e
)),
}
}
/// Fix a broken `links` reference by removing it.
pub async fn fix_broken_link_ref(&self, file: &Path, target: &str) -> FixResult {
match self.get_frontmatter_property(file, "links").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| match item {
crate::yaml_value::YamlValue::String(s) => s != target,
_ => true,
})
.collect();
if filtered.is_empty() {
match self.remove_frontmatter_property(file, "links").await {
Ok(_) => FixResult::success(format!(
"Removed broken link '{}' from {}",
target,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update links in {}: {}",
file.display(),
e
)),
}
} else {
match self
.set_frontmatter_property(
file,
"links",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed broken link '{}' from {}",
target,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update links in {}: {}",
file.display(),
e
)),
}
}
}
_ => FixResult::failure(format!("Could not read links from {}", file.display())),
}
}
/// Fix an invalid `link` by rewriting it to the canonical self-link.
pub async fn fix_invalid_self_link(&self, file: &Path) -> FixResult {
let formatted = self.format_self_link(file).await;
match self
.set_frontmatter_property(
file,
"link",
crate::yaml_value::YamlValue::String(formatted.clone()),
)
.await
{
Ok(_) => {
FixResult::success(format!("Set link to '{}' in {}", formatted, file.display()))
}
Err(e) => {
FixResult::failure(format!("Failed to set link in {}: {}", file.display(), e))
}
}
}
/// Fix a missing backlink by appending the suggested source link to `link_of`.
pub async fn fix_missing_backlink(&self, file: &Path, suggested: &str) -> FixResult {
match self.get_frontmatter_property(file, "link_of").await {
Some(crate::yaml_value::YamlValue::Sequence(mut items)) => {
items.push(crate::yaml_value::YamlValue::String(suggested.to_string()));
match self
.set_frontmatter_property(
file,
"link_of",
crate::yaml_value::YamlValue::Sequence(items),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added backlink '{}' to {}",
suggested,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update link_of in {}: {}",
file.display(),
e
)),
}
}
None => match self
.set_frontmatter_property(
file,
"link_of",
crate::yaml_value::YamlValue::Sequence(vec![
crate::yaml_value::YamlValue::String(suggested.to_string()),
]),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added backlink '{}' to {}",
suggested,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to create link_of in {}: {}",
file.display(),
e
)),
},
_ => FixResult::failure(format!("Could not read link_of from {}", file.display())),
}
}
/// Fix a stale backlink by removing it from `link_of`.
pub async fn fix_stale_backlink(&self, file: &Path, value: &str) -> FixResult {
match self.get_frontmatter_property(file, "link_of").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| match item {
crate::yaml_value::YamlValue::String(s) => s != value,
_ => true,
})
.collect();
if filtered.is_empty() {
match self.remove_frontmatter_property(file, "link_of").await {
Ok(_) => FixResult::success(format!(
"Removed stale backlink '{}' from {}",
value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update link_of in {}: {}",
file.display(),
e
)),
}
} else {
match self
.set_frontmatter_property(
file,
"link_of",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed stale backlink '{}' from {}",
value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update link_of in {}: {}",
file.display(),
e
)),
}
}
}
_ => FixResult::failure(format!("Could not read link_of from {}", file.display())),
}
}
/// Fix a missing attachment backlink by appending the suggested source
/// link to the attachment note's `attachment_of`.
pub async fn fix_missing_attachment_backlink(&self, file: &Path, suggested: &str) -> FixResult {
match self.get_frontmatter_property(file, "attachment_of").await {
Some(crate::yaml_value::YamlValue::Sequence(mut items)) => {
items.push(crate::yaml_value::YamlValue::String(suggested.to_string()));
match self
.set_frontmatter_property(
file,
"attachment_of",
crate::yaml_value::YamlValue::Sequence(items),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added attachment backlink '{}' to {}",
suggested,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachment_of in {}: {}",
file.display(),
e
)),
}
}
None => match self
.set_frontmatter_property(
file,
"attachment_of",
crate::yaml_value::YamlValue::Sequence(vec![
crate::yaml_value::YamlValue::String(suggested.to_string()),
]),
)
.await
{
Ok(_) => FixResult::success(format!(
"Added attachment backlink '{}' to {}",
suggested,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to create attachment_of in {}: {}",
file.display(),
e
)),
},
_ => FixResult::failure(format!(
"Could not read attachment_of from {}",
file.display()
)),
}
}
/// Fix a stale attachment backlink by removing it from `attachment_of`.
pub async fn fix_stale_attachment_backlink(&self, file: &Path, value: &str) -> FixResult {
match self.get_frontmatter_property(file, "attachment_of").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| match item {
crate::yaml_value::YamlValue::String(s) => s != value,
_ => true,
})
.collect();
if filtered.is_empty() {
match self
.remove_frontmatter_property(file, "attachment_of")
.await
{
Ok(_) => FixResult::success(format!(
"Removed stale attachment backlink '{}' from {}",
value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachment_of in {}: {}",
file.display(),
e
)),
}
} else {
match self
.set_frontmatter_property(
file,
"attachment_of",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed stale attachment backlink '{}' from {}",
value,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to update attachment_of in {}: {}",
file.display(),
e
)),
}
}
}
_ => FixResult::failure(format!(
"Could not read attachment_of from {}",
file.display()
)),
}
}
/// Dedupe a frontmatter list property, preserving the first occurrence of
/// each canonical value.
///
/// Duplicates are detected by canonical-link equivalence: if two entries
/// resolve to the same canonical path under the fixer's link format, only
/// the first is kept. Non-string entries pass through untouched.
pub async fn fix_duplicate_list_entry(&self, file: &Path, property: &str) -> FixResult {
let items = match self.get_frontmatter_property(file, property).await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => items,
_ => {
return FixResult::failure(format!(
"Could not read {} list from {}",
property,
file.display()
));
}
};
let file_canonical = self.get_canonical(file);
let link_format = Some(self.link_format);
let mut seen_canonical: std::collections::HashSet<String> =
std::collections::HashSet::new();
let original_len = items.len();
let mut deduped: Vec<crate::yaml_value::YamlValue> = Vec::with_capacity(original_len);
for item in items {
match &item {
crate::yaml_value::YamlValue::String(raw) => {
let canonical = canonicalize_link_value(raw, &file_canonical, link_format);
if seen_canonical.insert(canonical) {
deduped.push(item);
}
}
_ => deduped.push(item),
}
}
let removed = original_len - deduped.len();
if removed == 0 {
return FixResult::success(format!(
"No duplicates to remove from {} in {}",
property,
file.display()
));
}
match self
.set_frontmatter_property(
file,
property,
crate::yaml_value::YamlValue::Sequence(deduped),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed {removed} duplicate {property} entr{plural} from {}",
file.display(),
plural = if removed == 1 { "y" } else { "ies" },
)),
Err(e) => FixResult::failure(format!(
"Failed to update {} in {}: {}",
property,
file.display(),
e
)),
}
}
/// Fix a circular reference by removing a contents reference from a file.
///
/// This removes the specified reference from the file's `contents` array,
/// breaking the cycle.
pub async fn fix_circular_reference(
&self,
file: &Path,
contents_ref_to_remove: &str,
) -> FixResult {
match self.get_frontmatter_property(file, "contents").await {
Some(crate::yaml_value::YamlValue::Sequence(items)) => {
let filtered: Vec<crate::yaml_value::YamlValue> = items
.into_iter()
.filter(|item| {
if let crate::yaml_value::YamlValue::String(s) = item {
s != contents_ref_to_remove
} else {
true
}
})
.collect();
match self
.set_frontmatter_property(
file,
"contents",
crate::yaml_value::YamlValue::Sequence(filtered),
)
.await
{
Ok(_) => FixResult::success(format!(
"Removed circular reference '{}' from {}",
contents_ref_to_remove,
file.display()
)),
Err(e) => FixResult::failure(format!(
"Failed to remove circular reference from {}: {}",
file.display(),
e
)),
}
}
_ => FixResult::failure(format!("Could not read contents from {}", file.display())),
}
}
/// Fix a validation error.
pub async fn fix_error(&self, error: &ValidationError) -> FixResult {
match error {
ValidationError::BrokenPartOf { file, target: _ } => {
self.fix_broken_part_of(file).await
}
ValidationError::BrokenContentsRef { index, target } => {
self.fix_broken_contents_ref(index, target).await
}
ValidationError::BrokenAttachment { file, attachment } => {
self.fix_broken_attachment(file, attachment).await
}
ValidationError::BrokenLinkRef { file, target } => {
self.fix_broken_link_ref(file, target).await
}
}
}
/// Fix a validation warning.
///
/// Returns `None` if the warning type cannot be automatically fixed.
pub async fn fix_warning(&self, warning: &ValidationWarning) -> Option<FixResult> {
match warning {
ValidationWarning::NonPortablePath {
file,
property,
value,
suggested,
} => Some(
self.fix_non_portable_path(file, property, value, suggested)
.await,
),
ValidationWarning::OrphanBinaryFile {
file,
suggested_index,
} => {
if let Some(index) = suggested_index {
Some(self.fix_orphan_binary_file(index, file).await)
} else {
None
}
}
ValidationWarning::MissingPartOf {
file,
suggested_index,
} => {
if let Some(index) = suggested_index {
Some(self.fix_missing_part_of(file, index).await)
} else {
None
}
}
ValidationWarning::OrphanFile {
file,
suggested_index,
} => {
// Fix by adding the file to the nearest parent index's contents
if let Some(index) = suggested_index {
Some(self.fix_unlisted_file(index, file).await)
} else {
None
}
}
ValidationWarning::UnlinkedEntry {
path,
is_dir,
suggested_index,
index_file,
} => {
if let Some(index) = suggested_index {
if *is_dir {
// For directories, we need to link the index file inside, not the directory itself
if let Some(dir_index) = index_file {
Some(self.fix_unlisted_file(index, dir_index).await)
} else {
// Directory has no index file - can't auto-fix
None
}
} else {
// For files, add directly to contents
Some(self.fix_unlisted_file(index, path).await)
}
} else {
None
}
}
ValidationWarning::CircularReference {
suggested_file,
suggested_remove_part_of,
..
} => {
// Can auto-fix if we have a suggestion
if let (Some(file), Some(contents_ref)) = (suggested_file, suggested_remove_part_of)
{
Some(self.fix_circular_reference(file, contents_ref).await)
} else {
None
}
}
ValidationWarning::NonPortableFilename {
file,
suggested_filename,
..
} => Some(
self.fix_non_portable_filename(file, suggested_filename)
.await,
),
ValidationWarning::InvalidSelfLink { file, .. } => {
Some(self.fix_invalid_self_link(file).await)
}
ValidationWarning::MissingBacklink {
file, suggested, ..
} => Some(self.fix_missing_backlink(file, suggested).await),
ValidationWarning::StaleBacklink { file, value } => {
Some(self.fix_stale_backlink(file, value).await)
}
ValidationWarning::MissingAttachmentBacklink {
file, suggested, ..
} => Some(self.fix_missing_attachment_backlink(file, suggested).await),
ValidationWarning::StaleAttachmentBacklink { file, value } => {
Some(self.fix_stale_attachment_backlink(file, value).await)
}
ValidationWarning::DuplicateListEntry { file, property, .. } => {
Some(self.fix_duplicate_list_entry(file, property).await)
}
ValidationWarning::InvalidAttachmentRef {
file, target, kind, ..
} => match kind {
InvalidAttachmentRefKind::LegacyBinary { binary_path } => Some(
self.fix_invalid_attachment_ref(file, target, binary_path)
.await,
),
InvalidAttachmentRefKind::NotAttachmentNote
| InvalidAttachmentRefKind::UnparseableNote => None,
},
// These cannot be auto-fixed
ValidationWarning::MultipleIndexes { .. } => None,
ValidationWarning::InvalidContentsRef { .. } => None,
}
}
/// Attempt to fix all errors in a validation result.
///
/// Returns a list of fix results for each error.
pub async fn fix_all_errors(&self, result: &ValidationResult) -> Vec<FixResult> {
let mut fixes = Vec::new();
for error in &result.errors {
fixes.push(self.fix_error(error).await);
}
fixes
}
/// Attempt to fix all fixable warnings in a validation result.
///
/// Returns a list of fix results for warnings that could be fixed.
/// Warnings that cannot be auto-fixed are skipped.
pub async fn fix_all_warnings(&self, result: &ValidationResult) -> Vec<FixResult> {
let mut fixes = Vec::new();
for warning in &result.warnings {
if let Some(fix) = self.fix_warning(warning).await {
fixes.push(fix);
}
}
fixes
}
/// Attempt to fix all errors and fixable warnings in a validation result.
///
/// Returns a tuple of (error fix results, warning fix results).
pub async fn fix_all(&self, result: &ValidationResult) -> (Vec<FixResult>, Vec<FixResult>) {
(
self.fix_all_errors(result).await,
self.fix_all_warnings(result).await,
)
}
}