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
//! Implementation of [`FsTree`].
use std::{
collections::BTreeMap,
ffi::OsStr,
fmt, io, mem,
ops::Index,
path::{Path, PathBuf},
};
use file_type_enum::FileType;
use crate::{
Error, Result,
iter::{Iter, NodesIter, PathsIter},
utils::{self, fs},
};
/// The children [Trie](https://en.wikipedia.org/wiki/Trie) type alias.
pub type TrieMap = BTreeMap<PathBuf, FsTree>;
/// A filesystem tree recursive type.
///
/// # Iterators:
///
/// See the [iterator module documentation](crate::iter).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FsTree {
/// A regular file.
Regular,
/// A directory, might have children `FsTree`s inside.
Directory(TrieMap),
/// Symbolic link, and it's target path (the link might be broken).
Symlink(PathBuf),
}
impl FsTree {
/// Creates an empty directory node.
///
/// This is an alias to `FsTree::Directory(Default::default())`.
///
/// ```
/// use fs_tree::{FsTree, TrieMap};
///
/// let result = FsTree::new_dir();
/// let expected = FsTree::Directory(TrieMap::new());
///
/// assert_eq!(result, expected);
/// ```
pub fn new_dir() -> Self {
Self::Directory(TrieMap::new())
}
/// Calculate the length by counting the leafs.
pub fn len_leafs(&self) -> usize {
if let Some(children) = self.children() {
children.values().map(Self::len_leafs).sum::<usize>()
} else if self.is_leaf() {
1
} else {
0
}
}
/// Calculate the length by counting all tree nodes, including the root.
pub fn len_all(&self) -> usize {
self.children()
.map(|children| children.values().map(Self::len_all).sum::<usize>())
.unwrap_or(0)
+ 1
}
/// Construct a `FsTree` by reading from `path`, follows symlinks.
///
/// Symlinks are resolved to their targets. If you want to preserve symlinks
/// in the tree, use [`symlink_read_at`] instead.
///
/// # Errors:
///
/// - If any IO error occurs.
/// - If any file has an unexpected file type.
///
/// [`symlink_read_at`]: FsTree::symlink_read_at
pub fn read_at(path: impl AsRef<Path>) -> Result<Self> {
Self::__read_at(path.as_ref(), true)
}
/// Construct a `FsTree` by reading from `path`, does not follow symlinks.
///
/// Symlinks appear as [`FsTree::Symlink`] nodes. If you want symlinks to be
/// resolved to their targets, use [`read_at`] instead.
///
/// # Errors:
///
/// - If any IO error occurs.
/// - If any file has an unexpected file type.
///
/// [`read_at`]: FsTree::read_at
pub fn symlink_read_at(path: impl AsRef<Path>) -> Result<Self> {
Self::__read_at(path.as_ref(), false)
}
fn __read_at(path: &Path, follow_symlinks: bool) -> Result<Self> {
let get_file_type = if follow_symlinks {
FileType::read_at
} else {
FileType::symlink_read_at
};
match get_file_type(path)? {
FileType::Regular => Ok(Self::Regular),
FileType::Directory => {
let mut children = TrieMap::new();
for entry in fs::read_dir(path)? {
let entry = entry?;
let entry_path = entry.path();
let node = Self::__read_at(&entry_path, follow_symlinks)?;
let stripped_file_path = entry_path
.strip_prefix(path)
.expect("Failed to strip prefix, expected to always succeed in Linux");
children.insert(stripped_file_path.into(), node);
}
Ok(Self::Directory(children))
},
FileType::Symlink => {
let target_path = utils::follow_symlink(path)?;
Ok(Self::Symlink(target_path))
},
other_type => Err(Error::UnexpectedFileType(other_type, path.to_path_buf())),
}
}
/// Construct a structural copy of this `FsTree` by reading files at the given path.
///
/// In other words, the returned tree is formed of all paths in `self` that are also found in
/// the given `path` (intersection), missing files are skipped and types might differ.
///
/// This function can be useful if you need to load a subtree from a huge folder and cannot
/// afford to load the whole folder, or if you just want to filter out every node outside of the
/// specified structure.
///
/// This function will make at maximum `self.len()` syscalls.
///
/// If you want symlink-awareness, check [`FsTree::symlink_read_structure_at`].
///
/// # Examples:
///
/// ```no_run
/// use fs_tree::FsTree;
///
/// fn dynamically_load_structure() -> FsTree {
/// # "
/// ...
/// # "; todo!();
/// }
///
/// let structure = dynamically_load_structure();
///
/// let new_tree = structure.read_structure_at("path_here").unwrap();
///
/// // It is guaranteed that every path in here is present in `structure`
/// for path in new_tree.paths() {
/// assert!(structure.get(path).is_some());
/// }
/// ```
///
/// # Errors:
///
/// - If an IO error happens, except [`io::ErrorKind::NotFound`]
///
/// [`io::ErrorKind::NotFound`]: std::io::ErrorKind::NotFound
pub fn read_structure_at(&self, path: impl AsRef<Path>) -> Result<Self> {
self.__read_structure_at(path.as_ref(), true)
}
/// Construct a structural copy of this `FsTree` by reading files at the given path.
///
/// In other words, the returned tree is formed of all paths in `self` that are also found in
/// the given `path` (intersection), missing files are skipped and types might differ.
///
/// This function can be useful if you need to load a subtree from a huge folder and cannot
/// afford to load the whole folder, or if you just want to filter out every node outside of the
/// specified structure.
///
/// This function will make at maximum `self.len()` syscalls.
///
/// If you don't want symlink-awareness, check [`FsTree::read_structure_at`].
///
/// # Examples:
///
/// ```no_run
/// use fs_tree::FsTree;
///
/// fn dynamically_load_structure() -> FsTree {
/// # "
/// ...
/// # "; todo!();
/// }
///
/// let structure = dynamically_load_structure();
///
/// let new_tree = structure.symlink_read_structure_at("path_here").unwrap();
///
/// // It is guaranteed that every path in here is present in `structure`
/// for path in new_tree.paths() {
/// assert!(structure.get(path).is_some());
/// }
/// ```
///
/// # Errors:
///
/// - If an IO error happens, except [`io::ErrorKind::NotFound`]
///
/// [`io::ErrorKind::NotFound`]: std::io::ErrorKind::NotFound
pub fn symlink_read_structure_at(&self, path: impl AsRef<Path>) -> Result<Self> {
self.__read_structure_at(path.as_ref(), false)
}
fn __read_structure_at(&self, folder: &Path, follow_symlinks: bool) -> Result<Self> {
let mut new_tree = FsTree::new_dir();
for relative_path in self.paths() {
// TODO: optimize this, instead of creating a PathBuf for each path,
// it's possible to use one mutable buffer with push + pop
let path = folder.join(&relative_path);
let get_file_type = if follow_symlinks {
FileType::read_at
} else {
FileType::symlink_read_at
};
let file_type = match get_file_type(&path) {
Ok(file_type) => file_type,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => return Err(err.into()),
};
let node = match file_type {
FileType::Regular => Self::Regular,
FileType::Directory => Self::new_dir(),
FileType::Symlink => {
let target_path = utils::follow_symlink(&path)?;
Self::Symlink(target_path)
},
_ => continue,
};
new_tree.insert(relative_path, node);
}
Ok(new_tree)
}
/// Construct a `FsTree` from path pieces.
///
/// Returns `None` if the input is empty.
///
/// Returned value can correspond to a regular file or directory, but not a symlink.
///
/// # Warning
///
/// The last piece is always a file, so inputs ending with `/`, like `Path::new("example/")` are
/// **NOT** parsed as directories.
///
/// For my usage cases it's OK, but open an issue if you think otherwise 👍.
///
/// # Examples:
///
/// ```
/// use fs_tree::{FsTree, tree};
///
/// let result = FsTree::from_path_text("a/b/c");
///
/// let expected = tree! {
/// a: [
/// b: [
/// c
/// ]
/// ]
/// };
///
/// // The expected tree
/// assert_eq!(result, expected);
///
/// // Nodes are nested
/// assert!(result.is_dir());
/// assert!(result["a"].is_dir());
/// assert!(result["a"]["b"].is_dir());
/// assert!(result["a"]["b"]["c"].is_regular());
/// ```
pub fn from_path_text(path: impl AsRef<Path>) -> Self {
Self::from_path_pieces(path.as_ref().iter())
}
/// Generic iterator version of [`from_path_text`](FsTree::from_path_text).
pub fn from_path_pieces<I, P>(path_iter: I) -> Self
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
let mut path_iter = path_iter.into_iter();
if let Some(popped_piece) = path_iter.next() {
let child = (popped_piece.into(), Self::from_path_pieces(path_iter));
Self::Directory(TrieMap::from([child]))
} else {
Self::Regular
}
}
/// Creates an iterator that yields `(&FsTree, PathBuf)`.
///
/// See iterator docs at the [`iter` module documentation](crate::iter).
pub fn iter(&self) -> Iter<'_> {
Iter::new(self)
}
/// Creates an iterator that yields `&FsTree`.
///
/// See iterator docs at the [`iter` module documentation](crate::iter).
pub fn nodes(&self) -> NodesIter<'_> {
NodesIter::new(self)
}
/// Creates an iterator that yields `PathBuf`.
///
/// See iterator docs at the [`iter` module documentation](crate::iter).
pub fn paths(&self) -> PathsIter<'_> {
PathsIter::new(self)
}
/// Returns `true` if `self` type matches `other` type.
pub fn is_same_type_as(&self, other: &Self) -> bool {
mem::discriminant(self) == mem::discriminant(other)
}
/// Returns `Ok(true)` if all nodes exist in the filesystem.
///
/// # Errors:
///
/// Similar to how [`Path::try_exists`] works, this function returns `false` if any IO error
/// occurred when checking [`std::fs::symlink_metadata`] (except [`io::ErrorKind::NotFound`]).
pub fn try_exists(&mut self) -> io::Result<bool> {
for path in self.paths() {
match fs::symlink_metadata(path) {
Ok(_) => continue,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error),
}
}
Ok(true)
}
/// Merge two trees.
///
/// On conflicts, nodes from `other` are ignored and `self` is kept unchanged.
///
/// For conflict checking, see [`conflicts_with`], in other words, if
/// [`conflicts_with`] returns `true`, then at least one file will be
/// ignored from `other` in the `merge` call.
///
/// [`conflicts_with`]: Self::conflicts_with
pub fn merge(self, other: Self) -> Self {
// let's merge the right (consuming) onto the left (mutating)
let mut left = self;
let right = other;
match (&mut left, right) {
// both a directory at the same path, try merging
(FsTree::Directory(left_children), FsTree::Directory(right_children)) => {
for (path, right_node) in right_children {
// if right node exists, remove, merge and re-add, otherwise, just add it
if let Some(left_node) = left_children.remove(&path) {
let new_node = left_node.merge(right_node);
left_children.insert(path, new_node);
} else {
left_children.insert(path, right_node);
}
}
},
(_, _) => { /* conflict, but nothing to do, don't mutate left side */ },
}
left
}
/// Checks for conflicts in case the two trees would be merged.
///
/// Rules to what a conflict is:
///
/// - Two files have the same path, but different type.
/// - Two symlinks at the same path point at a different target.
///
/// Note: directories with different children isn't considered a conflict.
///
/// Also see [`Self::merge`] docs.
pub fn conflicts_with(&self, other: &Self) -> bool {
match (self, other) {
(FsTree::Directory(self_children), FsTree::Directory(other_children)) => {
for (path, other_node) in other_children {
if let Some(self_node) = self_children.get(path.as_path())
&& self_node.conflicts_with(other_node)
{
return true;
}
}
},
(_, _) => return true,
}
false
}
/// Reference to children if `self.is_directory()`.
pub fn children(&self) -> Option<&TrieMap> {
match &self {
Self::Directory(children) => Some(children),
_ => None,
}
}
/// Mutable reference to children if `self.is_directory()`.
pub fn children_mut(&mut self) -> Option<&mut TrieMap> {
match self {
Self::Directory(children) => Some(children),
_ => None,
}
}
/// Reference to target path, if `self.is_symlink()`.
pub fn target(&self) -> Option<&Path> {
match &self {
Self::Symlink(target_path) => Some(target_path),
_ => None,
}
}
/// Mutable reference to target path, if `self.is_symlink()`.
pub fn target_mut(&mut self) -> Option<&mut PathBuf> {
match self {
Self::Symlink(target_path) => Some(target_path),
_ => None,
}
}
// /// Apply a closure for each direct child of this FsTree.
// ///
// /// Only 1 level deep.
// pub fn apply_to_children0(&mut self, f: impl FnMut(&mut Self)) {
// if let Some(children) = self.children_mut() {
// children.iter_mut().for_each(f);
// }
// }
// /// Apply a closure to all direct and indirect descendants inside of this structure.
// ///
// /// Calls recursively for all levels.
// pub fn apply_to_all_children1(&mut self, f: impl FnMut(&mut Self) + Copy) {
// if let Some(children) = self.children_mut() {
// children
// .iter_mut()
// .for_each(|x| x.apply_to_all_children1(f));
// children.iter_mut().for_each(f);
// }
// }
// /// Apply a closure to all direct and indirect descendants inside (including root).
// ///
// /// Calls recursively for all levels.
// pub fn apply_to_all(&mut self, mut f: impl FnMut(&mut Self) + Copy) {
// f(self);
// if let Some(children) = self.children_mut() {
// for child in children.iter_mut() {
// child.apply_to_all(f);
// }
// }
// }
/// Returns `true` if `self` is a leaf node.
///
/// A leaf node might be of any type, including directory, however, a
/// non-leaf node is always a directory.
pub fn is_leaf(&self) -> bool {
match self {
Self::Regular | Self::Symlink(_) => true,
Self::Directory(children) => children.is_empty(),
}
}
/// The variant string, useful for showing to user.
pub fn variant_str(&self) -> &'static str {
match self {
Self::Regular => "regular file",
Self::Directory(_) => "directory",
Self::Symlink(_) => "symlink",
}
}
/// Returns `true` if self matches the [`FsTree::Regular`] variant.
pub fn is_regular(&self) -> bool {
matches!(self, Self::Regular)
}
/// Returns `true` if self matches the [`FsTree::Directory`] variant.
pub fn is_dir(&self) -> bool {
matches!(self, Self::Directory(_))
}
/// Returns `true` if self matches the [`FsTree::Symlink`] variant.
pub fn is_symlink(&self) -> bool {
matches!(self, Self::Symlink(_))
}
// /// Generate a diff from two different trees.
// pub fn diff(&self, other: &Self) {
// if !self.has_same_type_as(other) {
// println!("Types differ! ");
// }
// let (self_children, other_children) = match (&self.file_type, &other.file_type) {
// (Self::Directory(self_children), Self::Directory(other_children)) => {
// (self_children, other_children)
// },
// _ => panic!(),
// };
// let mut lookup = self_children
// .iter()
// .map(|x| (&x.path, x))
// .collect::<HashMap<&PathBuf, &FsTree>>();
// for other_child in other_children {
// if let Some(self_child) = lookup.remove(&other_child.path) {
// if self_child.has_same_type_as(other_child) {
// if self_child.is_dir() {
// self_child.diff(other_child);
// }
// } else {
// println!(
// "File {:?} is a {} while file {:?} is a {}",
// self_child.path,
// self_child.file_type.file_type_display(),
// other_child.path,
// other_child.file_type.file_type_display(),
// );
// }
// } else {
// let path = &other_child.path;
// println!(
// "2Only in {:?}: {:?}",
// path.parent().unwrap(),
// path.file_name().unwrap()
// );
// }
// }
// for child_left in lookup.values() {
// let path = &child_left.path;
// println!(
// "1Only in {:?}: {:?}",
// path.parent().unwrap(),
// path.file_name().unwrap()
// );
// }
// }
/// Write the tree structure at the given folder path.
///
/// This method creates files, directories, and symlinks as defined by the
/// tree structure. When a path already exists, the behavior depends on the
/// node type:
///
/// - **Regular files**: If a regular file already exists at the path, it is
/// left unchanged. If a non-regular file exists, returns
/// [`Error::NotARegularFile`].
///
/// - **Directories**: If a directory already exists at the path, it is left
/// unchanged. If a non-directory exists, returns [`Error::NotADirectory`].
///
/// - **Symlinks**: If a symlink already exists and points to the expected
/// target, it is left unchanged. If a symlink exists but points to a
/// different target, returns [`Error::SymlinkTargetMismatch`]. If a
/// non-symlink exists, returns [`Error::NotASymlink`].
///
/// # Errors
///
/// - If the provided folder doesn't exist, or is not a directory.
/// - If a path conflict occurs (see above for conflict rules).
/// - If any other IO error occurs.
///
/// [`Error::NotARegularFile`]: crate::Error::NotARegularFile
/// [`Error::NotADirectory`]: crate::Error::NotADirectory
/// [`Error::NotASymlink`]: crate::Error::NotASymlink
/// [`Error::SymlinkTargetMismatch`]: crate::Error::SymlinkTargetMismatch
pub fn write_structure_at(&self, folder: impl AsRef<Path>) -> Result<()> {
let folder = folder.as_ref();
#[cfg(feature = "fs-err")]
let symlink_function = fs_err::os::unix::fs::symlink;
#[cfg(not(feature = "fs-err"))]
let symlink_function = std::os::unix::fs::symlink;
for (node, relative_path) in self.iter().skip(1) {
let path = folder.join(&relative_path);
match &node {
Self::Regular => {
if path.exists() {
if !path.is_file() {
return Err(Error::NotARegularFile(path));
}
} else {
fs::File::create(path)?;
}
},
Self::Directory(_) => {
if path.exists() {
if !path.is_dir() {
return Err(Error::NotADirectory(path));
}
} else {
fs::create_dir(path)?;
}
},
Self::Symlink(expected_target) => {
match FileType::symlink_read_at(&path) {
Ok(file_type) if file_type.is_symlink() => {
let actual_target = fs::read_link(&path)?;
if actual_target != *expected_target {
return Err(Error::SymlinkTargetMismatch {
path,
expected: expected_target.clone(),
found: actual_target,
});
}
},
Ok(_) => {
return Err(Error::NotASymlink(path));
},
Err(_) => {
symlink_function(expected_target, path)?;
},
}
},
}
}
Ok(())
}
/// Returns a reference to the node at the path, if any.
///
/// # Errors:
///
/// - Returns `None` if there is no node at the given path.
///
/// # Examples:
///
/// ```
/// use fs_tree::FsTree;
///
/// let root = FsTree::from_path_text("a/b/c");
///
/// // Indexing is relative from `root`, so `root` cannot be indexed.
/// assert_eq!(root, FsTree::from_path_text("a/b/c"));
/// assert_eq!(root["a"], FsTree::from_path_text("b/c"));
/// assert_eq!(root["a/b"], FsTree::from_path_text("c"));
/// assert_eq!(root["a"]["b"], FsTree::from_path_text("c"));
/// assert_eq!(root["a/b/c"], FsTree::Regular);
/// assert_eq!(root["a/b"]["c"], FsTree::Regular);
/// assert_eq!(root["a"]["b/c"], FsTree::Regular);
/// assert_eq!(root["a"]["b"]["c"], FsTree::Regular);
/// ```
pub fn get(&self, path: impl AsRef<Path>) -> Option<&Self> {
let path = path.as_ref();
// Split first piece from the rest
let (popped, path_rest) = {
let mut iter = path.iter();
let popped: Option<&Path> = iter.next().map(OsStr::as_ref);
(popped, iter.as_path())
};
// If path ended, we reached the desired node
let Some(popped) = popped else {
return Some(self);
};
// Corner case: if `.`, ignore it and call again with the rest
if popped == Path::new(".") {
return self.get(path_rest);
}
self.children()?
.get(popped)
.and_then(|child| child.get(path_rest))
}
/// Returns a mutable reference to the node at the path, if any.
///
/// This is the mutable version of [`FsTree::get`].
pub fn get_mut(&mut self, path: impl AsRef<Path>) -> Option<&mut Self> {
let path = path.as_ref();
// Split first piece from the rest
let (popped, path_rest) = {
let mut iter = path.iter();
let popped: Option<&Path> = iter.next().map(OsStr::as_ref);
(popped, iter.as_path())
};
// If path ended, we reached the desired node
let Some(popped) = popped else {
return Some(self);
};
// Corner case: if `.`, ignore it and call again with the rest
if popped == Path::new(".") {
return self.get_mut(path_rest);
}
self.children_mut()?
.get_mut(popped)
.and_then(|child| child.get_mut(path_rest))
}
/// Inserts a node at the given path.
///
/// # Panics:
///
/// - If there are no directories up to the path node in order to insert it.
/// - If path is empty.
pub fn insert(&mut self, path: impl AsRef<Path>, node: Self) {
use FsTree::*;
let mut iter = path.as_ref().iter();
let Some(node_name) = iter.next_back().map(Path::new) else {
*self = node;
return;
};
let mut tree = self;
// Traverse tree
for next in iter {
// Give a better error message than the one below
if !tree.is_dir() {
panic!(
"Failed to insert node, while traversing, one of the parent directories \
({next:?}) isn't a directory, but a {}",
tree.variant_str()
);
}
tree = if let Some(tree) = tree.get_mut(next) {
tree
} else {
panic!("Failed to insert node, parent directory {next:?} doesn't exist");
};
}
match tree {
Regular | Symlink(_) => {
panic!(
"Failed to insert node, parent directory is not a directory, but a {}",
tree.variant_str(),
);
},
Directory(children) => {
children.insert(node_name.into(), node);
},
}
}
}
#[cfg(feature = "libc-file-type")]
impl FsTree {
/// Returns the file type equivalent [`libc::mode_t`] value.
pub fn as_mode_t(&self) -> libc::mode_t {
match self {
Self::Regular => libc::S_IFREG,
Self::Directory(_) => libc::S_IFDIR,
Self::Symlink(_) => libc::S_IFCHR,
}
}
}
impl<P> Index<P> for FsTree
where
P: AsRef<Path>,
{
type Output = FsTree;
fn index(&self, path: P) -> &Self::Output {
self.get(path.as_ref())
.unwrap_or_else(|| panic!("no node found for path '{}'", path.as_ref().display()))
}
}
impl<'a> IntoIterator for &'a FsTree {
type Item = (&'a FsTree, PathBuf);
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl fmt::Display for FsTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut iter_next = {
let mut iter = self.iter();
move || iter.next().map(|(node, path)| (node, path, iter.depth()))
};
let mut previous_depth = 0;
while let Some((node, path, depth)) = iter_next() {
let is_first_element = path.as_os_str().is_empty();
if is_first_element {
match node {
FsTree::Regular => {
write!(f, "regular file")?;
return Ok(());
},
FsTree::Symlink(target) => {
write!(f, "symlink to {target:?}")?;
return Ok(());
},
FsTree::Directory(_) => {
// Open root brace
writeln!(f, "{{")?;
continue;
},
}
}
let indent = " ".repeat(depth);
// Close braces for directories that ended at shallower depths
while previous_depth > depth {
previous_depth -= 1;
let close_indent = " ".repeat(previous_depth);
writeln!(f, "{}}}", close_indent)?;
}
let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
write!(f, "{indent}\"{filename}\"")?;
match node {
FsTree::Regular => {
previous_depth = depth;
},
FsTree::Directory(_) => {
write!(f, " {{")?;
previous_depth = depth + 1;
},
FsTree::Symlink(target) => {
previous_depth = depth;
write!(f, " -> {target:?}")?;
},
}
writeln!(f)?;
}
// Close remaining open braces
while previous_depth > 1 {
previous_depth -= 1;
let close_indent = " ".repeat(previous_depth);
writeln!(f, "{}}}", close_indent)?;
}
// Close root brace
writeln!(f, "}}")
}
}
#[cfg(test)]
mod tests {
use std::{io, path::Path};
use pretty_assertions::{assert_eq, assert_ne};
use super::*;
use crate::tree;
fn testdir() -> io::Result<(tempfile::TempDir, &'static Path)> {
let dir = tempfile::tempdir()?;
let path = dir.path().to_path_buf().into_boxed_path();
Ok((dir, Box::leak(path)))
}
#[test]
fn test_len_all_counts_all_nodes_including_root() {
let tree = tree! {
file1
dir1: [
file2
file3
]
file4
};
assert_eq!(tree.len_all(), 6);
}
// #[test]
// fn test_diff() {
// let left = FsTree::from_path_text(".config/i3/file").unwrap();
// let right = FsTree::from_path_text(".config/i3/folder/file/oie").unwrap();
// left.diff(&right);
// panic!();
// }
#[test]
fn test_insert_basic() {
let mut tree = FsTree::new_dir();
let paths = ["a", "a/b", "a/b/c", "a/b/c/d", "a/b/c/d/e"];
for path in paths {
tree.insert(path, FsTree::new_dir());
}
tree.insert("a/b/c/d/e/f", FsTree::Regular);
let expected = tree! {
a: [ b: [ c: [ d: [ e: [ f ] ] ] ] ]
};
assert_eq!(tree, expected);
}
#[rustfmt::skip]
#[test]
fn test_insert_complete() {
let result = {
let mut tree = FsTree::new_dir();
tree.insert("config1", FsTree::Regular);
tree.insert("config2", FsTree::Regular);
tree.insert("outer_dir", FsTree::new_dir());
tree.insert("outer_dir/file1", FsTree::Regular);
tree.insert("outer_dir/file2", FsTree::Regular);
tree.insert("outer_dir/inner_dir", FsTree::new_dir());
tree.insert("outer_dir/inner_dir/inner1", FsTree::Regular);
tree.insert("outer_dir/inner_dir/inner2", FsTree::Regular);
tree.insert("outer_dir/inner_dir/inner3", FsTree::Regular);
tree.insert("outer_dir/inner_dir/inner_link", FsTree::Symlink("inner_target".into()));
tree.insert("link", FsTree::Symlink("target".into()));
tree.insert("config3", FsTree::Regular);
tree
};
let expected = tree! {
config1
config2
outer_dir: [
file1
file2
inner_dir: [
inner1
inner2
inner3
inner_link -> inner_target
]
]
link -> target
config3
};
assert_eq!(result, expected);
}
#[test]
fn test_write_structure_at() {
let (_dropper, test_dir) = testdir().unwrap();
let tree = tree! {
a: [
b: [
c
empty: []
link -> target
]
]
};
tree.write_structure_at(test_dir).unwrap();
let result = FsTree::symlink_read_at(test_dir).unwrap();
assert_eq!(result, tree);
}
#[test]
fn test_get() {
let tree = FsTree::from_path_text("a/b/c");
assert_eq!(tree["a"], FsTree::from_path_text("b/c"));
assert_eq!(tree["a/b"], FsTree::from_path_text("c"));
assert_eq!(tree["a"]["b"], FsTree::from_path_text("c"));
assert_eq!(tree["a/b/c"], FsTree::Regular);
assert_eq!(tree["a/b"]["c"], FsTree::Regular);
assert_eq!(tree["a"]["b/c"], FsTree::Regular);
assert_eq!(tree["a"]["b"]["c"], FsTree::Regular);
// Paths are relative, so empty path returns the node itself
assert_eq!(tree[""], tree);
assert_eq!(tree[""], tree[""]);
// "."s are ignored
assert_eq!(tree["."], tree[""]);
assert_eq!(tree["././"], tree["."]);
assert_eq!(tree["././."], tree);
assert_eq!(tree["./a/."]["././b/./."], FsTree::from_path_text("c"));
assert_eq!(tree["./a/./b"]["c/."], FsTree::Regular);
}
#[test]
fn test_merge_two_paths_with_partial_intersection() {
let left = FsTree::from_path_text(".config/i3/file");
let right = FsTree::from_path_text(".config/i3/folder/file");
assert!(!left.conflicts_with(&right));
let result = left.merge(right);
assert_eq!(
result,
tree! {
".config": [
i3: [
file
folder: [
file
]
]
]
}
);
}
#[test]
fn test_partial_eq_fails() {
let left = FsTree::from_path_text(".config/i3/a");
let right = FsTree::from_path_text(".config/i3/b");
assert_ne!(left, right);
}
#[test]
fn test_merge_disjoint_trees() {
let left = tree! { a };
let right = tree! { b };
assert!(!left.conflicts_with(&right));
let merged = left.merge(right);
assert_eq!(
merged,
tree! {
a
b
}
);
}
#[test]
fn test_merge_conflict_keeps_self() {
let left = tree! {
a
b -> c
link -> v1
};
let right = tree! {
a: []
b
link -> v2
};
assert!(left.conflicts_with(&right));
let merged = left.clone().merge(right);
assert_eq!(merged, left);
}
#[test]
fn test_merge_nested_directories() {
let left = tree! { dir: [a] };
let right = tree! { dir: [b] };
assert!(!left.conflicts_with(&right));
let merged = left.merge(right);
assert_eq!(
merged,
tree! {
dir: [
a
b
]
}
);
}
#[test]
fn test_conflicts_with() {
let left = tree! { a };
let right = tree! { b };
assert!(!left.conflicts_with(&right));
let left = tree! { file };
let right = tree! { file };
assert!(left.conflicts_with(&right));
let left = tree! { x };
let right = tree! { x: [] };
assert!(left.conflicts_with(&right));
let left = tree! { a -> b };
let right = tree! { a };
assert!(left.conflicts_with(&right));
let left = tree! { a -> b };
let right = tree! { a: [] };
assert!(left.conflicts_with(&right));
let left = tree! { a -> b };
let right = tree! { a -> c };
assert!(left.conflicts_with(&right));
let left = tree! { a -> c };
let right = tree! { b -> c };
assert!(!left.conflicts_with(&right));
}
#[test]
fn test_display_formatting() {
let regular_tree = FsTree::Regular;
let regular_expected = regular_tree.variant_str();
assert_eq!(regular_tree.to_string(), regular_expected);
assert_eq!(regular_tree.to_string(), "regular file");
let symlink_tree = FsTree::Symlink("b".into());
let symlink_expected = "symlink to \"b\"";
assert_eq!(symlink_tree.to_string(), symlink_expected);
let dir_tree = tree! {
a: [
b: [
b1
]
c: [
c1
c2
c3
c4
link -> target
d: [
d1
d2
]
]
]
a1
a2
};
let dir_expected = r#"{
"a" {
"b" {
"b1"
}
"c" {
"c1"
"c2"
"c3"
"c4"
"d" {
"d1"
"d2"
}
"link" -> "target"
}
}
"a1"
"a2"
}
"#;
assert_eq!(dir_tree.to_string(), dir_expected);
}
}