-
Notifications
You must be signed in to change notification settings - Fork 824
/
filesystem.rs
1705 lines (1510 loc) · 55.8 KB
/
filesystem.rs
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
//! This module contains the [`FileSystem`] type itself.
use super::*;
use crate::{DirEntry, FileType, FsError, Metadata, OpenOptions, ReadDir, Result};
use slab::Slab;
use std::collections::VecDeque;
use std::convert::identity;
use std::ffi::OsString;
use std::fmt;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
/// The in-memory file system!
///
/// It's a thin wrapper around [`FileSystemInner`]. This `FileSystem`
/// type can be cloned, it's a light copy of the `FileSystemInner`
/// (which is behind a `Arc` + `RwLock`.
#[derive(Clone, Default)]
pub struct FileSystem {
pub(super) inner: Arc<RwLock<FileSystemInner>>,
}
impl FileSystem {
pub fn new_open_options_ext(&self) -> &FileSystem {
self
}
pub fn union(&self, other: &Arc<dyn crate::FileSystem + Send + Sync>) {
// Iterate all the directories and files in the other filesystem
// and create references back to them in this filesystem
let mut remaining = VecDeque::new();
remaining.push_back(PathBuf::from("/"));
while let Some(next) = remaining.pop_back() {
if next
.file_name()
.map(|n| n.to_string_lossy().starts_with(".wh."))
.unwrap_or(false)
{
let rm = next.to_string_lossy();
let rm = &rm[".wh.".len()..];
let rm = PathBuf::from(rm);
let _ = crate::FileSystem::remove_dir(self, rm.as_path());
let _ = crate::FileSystem::remove_file(self, rm.as_path());
continue;
}
let _ = crate::FileSystem::create_dir(self, next.as_path());
let dir = match other.read_dir(next.as_path()) {
Ok(dir) => dir,
Err(_) => {
// TODO: propagate errors (except NotFound)
continue;
}
};
for sub_dir_res in dir {
let sub_dir = match sub_dir_res {
Ok(sub_dir) => sub_dir,
Err(_) => {
// TODO: propagate errors (except NotFound)
continue;
}
};
match sub_dir.file_type() {
Ok(t) if t.is_dir() => {
remaining.push_back(sub_dir.path());
}
Ok(t) if t.is_file() => {
if sub_dir.file_name().to_string_lossy().starts_with(".wh.") {
let rm = next.to_string_lossy();
let rm = &rm[".wh.".len()..];
let rm = PathBuf::from(rm);
let _ = crate::FileSystem::remove_dir(self, rm.as_path());
let _ = crate::FileSystem::remove_file(self, rm.as_path());
continue;
}
let _ = self
.new_open_options_ext()
.insert_arc_file(sub_dir.path(), other.clone());
}
_ => {}
}
}
}
}
pub fn mount(
&self,
path: PathBuf,
other: &Arc<dyn crate::FileSystem + Send + Sync>,
dst: PathBuf,
) -> Result<()> {
if crate::FileSystem::read_dir(self, path.as_path()).is_ok() {
return Err(FsError::AlreadyExists);
}
let (inode_of_parent, name_of_directory) = {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
// Canonicalize the path without checking the path exists,
// because it's about to be created.
let path = guard.canonicalize_without_inode(path.as_path())?;
// Check the path has a parent.
let parent_of_path = path.parent().ok_or(FsError::BaseNotDirectory)?;
// Check the directory name.
let name_of_directory = path
.file_name()
.ok_or(FsError::InvalidInput)?
.to_os_string();
// Find the parent inode.
let inode_of_parent = match guard.inode_of_parent(parent_of_path)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(..) => {
return Err(FsError::AlreadyExists);
}
};
(inode_of_parent, name_of_directory)
};
{
// Write lock.
let mut fs = self.inner.write().map_err(|_| FsError::Lock)?;
// Creating the directory in the storage.
let inode_of_directory = fs.storage.vacant_entry().key();
let real_inode_of_directory = fs.storage.insert(Node::ArcDirectory(ArcDirectoryNode {
inode: inode_of_directory,
name: name_of_directory,
fs: other.clone(),
path: dst,
metadata: {
let time = time();
Metadata {
ft: FileType {
dir: true,
..Default::default()
},
accessed: time,
created: time,
modified: time,
len: 0,
}
},
}));
assert_eq!(
inode_of_directory, real_inode_of_directory,
"new directory inode should have been correctly calculated",
);
// Adding the new directory to its parent.
fs.add_child_to_node(inode_of_parent, inode_of_directory)?;
}
Ok(())
}
}
impl crate::FileSystem for FileSystem {
fn read_dir(&self, path: &Path) -> Result<ReadDir> {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
// Canonicalize the path.
let (path, inode_of_directory) = guard.canonicalize(path)?;
let inode_of_directory = match inode_of_directory {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, path) => {
return fs.read_dir(path.as_path());
}
};
// Check it's a directory and fetch the immediate children as `DirEntry`.
let inode = guard.storage.get(inode_of_directory);
let children = match inode {
Some(Node::Directory(DirectoryNode { children, .. })) => children
.iter()
.filter_map(|inode| guard.storage.get(*inode))
.map(|node| DirEntry {
path: {
let mut entry_path = path.to_path_buf();
entry_path.push(node.name());
entry_path
},
metadata: Ok(node.metadata().clone()),
})
.collect(),
Some(Node::ArcDirectory(ArcDirectoryNode { fs, path, .. })) => {
return fs.read_dir(path.as_path());
}
_ => return Err(FsError::InvalidInput),
};
Ok(ReadDir::new(children))
}
fn create_dir(&self, path: &Path) -> Result<()> {
if self.read_dir(path).is_ok() {
return Err(FsError::AlreadyExists);
}
let (inode_of_parent, name_of_directory) = {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
// Canonicalize the path without checking the path exists,
// because it's about to be created.
let path = guard.canonicalize_without_inode(path)?;
// Check the path has a parent.
let parent_of_path = path.parent().ok_or(FsError::BaseNotDirectory)?;
// Check the directory name.
let name_of_directory = path
.file_name()
.ok_or(FsError::InvalidInput)?
.to_os_string();
// Find the parent inode.
let inode_of_parent = match guard.inode_of_parent(parent_of_path)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, mut path) => {
drop(guard);
path.push(name_of_directory);
return fs.create_dir(path.as_path());
}
};
(inode_of_parent, name_of_directory)
};
if self.read_dir(path).is_ok() {
return Err(FsError::AlreadyExists);
}
{
// Write lock.
let mut fs = self.inner.write().map_err(|_| FsError::Lock)?;
// Creating the directory in the storage.
let inode_of_directory = fs.storage.vacant_entry().key();
let real_inode_of_directory = fs.storage.insert(Node::Directory(DirectoryNode {
inode: inode_of_directory,
name: name_of_directory,
children: Vec::new(),
metadata: {
let time = time();
Metadata {
ft: FileType {
dir: true,
..Default::default()
},
accessed: time,
created: time,
modified: time,
len: 0,
}
},
}));
assert_eq!(
inode_of_directory, real_inode_of_directory,
"new directory inode should have been correctly calculated",
);
// Adding the new directory to its parent.
fs.add_child_to_node(inode_of_parent, inode_of_directory)?;
}
Ok(())
}
fn remove_dir(&self, path: &Path) -> Result<()> {
let (inode_of_parent, position, inode_of_directory) = {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
// Canonicalize the path.
let (path, _) = guard.canonicalize(path)?;
// Check the path has a parent.
let parent_of_path = path.parent().ok_or(FsError::BaseNotDirectory)?;
// Check the directory name.
let name_of_directory = path
.file_name()
.ok_or(FsError::InvalidInput)?
.to_os_string();
// Find the parent inode.
let inode_of_parent = match guard.inode_of_parent(parent_of_path)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, mut parent_path) => {
drop(guard);
parent_path.push(name_of_directory);
return fs.remove_dir(parent_path.as_path());
}
};
// Get the child index to remove in the parent node, in
// addition to the inode of the directory to remove.
let (position, inode_of_directory) = guard
.as_parent_get_position_and_inode_of_directory(
inode_of_parent,
&name_of_directory,
DirectoryMustBeEmpty::Yes,
)?;
(inode_of_parent, position, inode_of_directory)
};
let inode_of_directory = match inode_of_directory {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, path) => {
return fs.remove_dir(path.as_path());
}
};
{
// Write lock.
let mut fs = self.inner.write().map_err(|_| FsError::Lock)?;
// Remove the directory from the storage.
fs.storage.remove(inode_of_directory);
// Remove the child from the parent directory.
fs.remove_child_from_node(inode_of_parent, position)?;
}
Ok(())
}
fn rename(&self, from: &Path, to: &Path) -> Result<()> {
let name_of_to;
let (
(position_of_from, inode, inode_of_from_parent),
(inode_of_to_parent, name_of_to),
inode_dest,
) = {
// Read lock.
let fs = self.inner.read().map_err(|_| FsError::Lock)?;
let from = fs.canonicalize_without_inode(from)?;
let to = fs.canonicalize_without_inode(to)?;
// Check the paths have parents.
let parent_of_from = from.parent().ok_or(FsError::BaseNotDirectory)?;
let parent_of_to = to.parent().ok_or(FsError::BaseNotDirectory)?;
// Check the names.
let name_of_from = from
.file_name()
.ok_or(FsError::InvalidInput)?
.to_os_string();
name_of_to = to.file_name().ok_or(FsError::InvalidInput)?.to_os_string();
// Find the parent inodes.
let inode_of_from_parent = match fs.inode_of_parent(parent_of_from)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(..) => {
return Err(FsError::InvalidInput);
}
};
let inode_of_to_parent = match fs.inode_of_parent(parent_of_to)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(..) => {
return Err(FsError::InvalidInput);
}
};
// Find the inode of the dest file if it exists
let maybe_position_and_inode_of_file =
fs.as_parent_get_position_and_inode_of_file(inode_of_to_parent, &name_of_to)?;
// Get the child indexes to update in the parent nodes, in
// addition to the inode of the directory to update.
let (position_of_from, inode) = fs
.as_parent_get_position_and_inode(inode_of_from_parent, &name_of_from)?
.ok_or(FsError::EntryNotFound)?;
(
(position_of_from, inode, inode_of_from_parent),
(inode_of_to_parent, name_of_to),
maybe_position_and_inode_of_file,
)
};
let inode = match inode {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(..) => {
return Err(FsError::InvalidInput);
}
};
{
// Write lock.
let mut fs = self.inner.write().map_err(|_| FsError::Lock)?;
if let Some((position, inode_of_file)) = inode_dest {
// Remove the file from the storage.
match inode_of_file {
InodeResolution::Found(inode_of_file) => {
fs.storage.remove(inode_of_file);
}
InodeResolution::Redirect(..) => {
return Err(FsError::InvalidInput);
}
}
fs.remove_child_from_node(inode_of_to_parent, position)?;
}
// Update the file name, and update the modified time.
fs.update_node_name(inode, name_of_to)?;
// The parents are different. Let's update them.
if inode_of_from_parent != inode_of_to_parent {
// Remove the file from its parent, and update the
// modified time.
fs.remove_child_from_node(inode_of_from_parent, position_of_from)?;
// Add the file to its new parent, and update the modified
// time.
fs.add_child_to_node(inode_of_to_parent, inode)?;
}
// Otherwise, we need to at least update the modified time of the parent.
else {
let mut inode = fs.storage.get_mut(inode_of_from_parent);
match inode.as_mut() {
Some(Node::Directory(node)) => node.metadata.modified = time(),
Some(Node::ArcDirectory(node)) => node.metadata.modified = time(),
_ => return Err(FsError::UnknownError),
}
}
}
Ok(())
}
fn metadata(&self, path: &Path) -> Result<Metadata> {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
match guard.inode_of(path)? {
InodeResolution::Found(inode) => Ok(guard
.storage
.get(inode)
.ok_or(FsError::UnknownError)?
.metadata()
.clone()),
InodeResolution::Redirect(fs, path) => {
drop(guard);
fs.metadata(path.as_path())
}
}
}
fn remove_file(&self, path: &Path) -> Result<()> {
let (inode_of_parent, position, inode_of_file) = {
// Read lock.
let guard = self.inner.read().map_err(|_| FsError::Lock)?;
// Canonicalize the path.
let path = guard.canonicalize_without_inode(path)?;
// Check the path has a parent.
let parent_of_path = path.parent().ok_or(FsError::BaseNotDirectory)?;
// Check the file name.
let name_of_file = path
.file_name()
.ok_or(FsError::InvalidInput)?
.to_os_string();
// Find the parent inode.
let inode_of_parent = match guard.inode_of_parent(parent_of_path)? {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, mut parent_path) => {
parent_path.push(name_of_file);
return fs.remove_file(parent_path.as_path());
}
};
// Find the inode of the file if it exists, along with its position.
let maybe_position_and_inode_of_file =
guard.as_parent_get_position_and_inode_of_file(inode_of_parent, &name_of_file)?;
match maybe_position_and_inode_of_file {
Some((position, inode_of_file)) => (inode_of_parent, position, inode_of_file),
None => return Err(FsError::EntryNotFound),
}
};
let inode_of_file = match inode_of_file {
InodeResolution::Found(a) => a,
InodeResolution::Redirect(fs, path) => {
return fs.remove_file(path.as_path());
}
};
{
// Write lock.
let mut fs = self.inner.write().map_err(|_| FsError::Lock)?;
// Remove the file from the storage.
fs.storage.remove(inode_of_file);
// Remove the child from the parent directory.
fs.remove_child_from_node(inode_of_parent, position)?;
}
Ok(())
}
fn new_open_options(&self) -> OpenOptions {
OpenOptions::new(self)
}
}
impl fmt::Debug for FileSystem {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let fs: &FileSystemInner = &self.inner.read().unwrap();
fs.fmt(formatter)
}
}
/// The core of the file system. It contains a collection of `Node`s,
/// indexed by their respective `Inode` in a slab.
pub(super) struct FileSystemInner {
pub(super) storage: Slab<Node>,
}
#[derive(Debug)]
pub(super) enum InodeResolution {
Found(Inode),
Redirect(Arc<dyn crate::FileSystem + Send + Sync + 'static>, PathBuf),
}
impl InodeResolution {
#[allow(dead_code)]
pub fn unwrap(&self) -> Inode {
match self {
Self::Found(a) => *a,
Self::Redirect(..) => {
panic!("failed to unwrap the inode as the resolution is a redirect");
}
}
}
}
impl FileSystemInner {
/// Get the inode associated to a path if it exists.
pub(super) fn inode_of(&self, path: &Path) -> Result<InodeResolution> {
// SAFETY: The root node always exists, so it's safe to unwrap here.
let mut node = self.storage.get(ROOT_INODE).unwrap();
let mut components = path.components();
match components.next() {
Some(Component::RootDir) => {}
_ => return Err(FsError::BaseNotDirectory),
}
while let Some(component) = components.next() {
node = match node {
Node::Directory(DirectoryNode { children, .. }) => children
.iter()
.filter_map(|inode| self.storage.get(*inode))
.find(|node| node.name() == component.as_os_str())
.ok_or(FsError::EntryNotFound)?,
Node::ArcDirectory(ArcDirectoryNode {
fs, path: fs_path, ..
}) => {
let mut path = fs_path.clone();
path.push(PathBuf::from(component.as_os_str()));
for component in components.by_ref() {
path.push(PathBuf::from(component.as_os_str()));
}
return Ok(InodeResolution::Redirect(fs.clone(), path));
}
_ => return Err(FsError::BaseNotDirectory),
};
}
Ok(InodeResolution::Found(node.inode()))
}
/// Get the inode associated to a “parent path”. The returned
/// inode necessarily represents a directory.
pub(super) fn inode_of_parent(&self, parent_path: &Path) -> Result<InodeResolution> {
match self.inode_of(parent_path)? {
InodeResolution::Found(inode_of_parent) => {
// Ensure it is a directory.
match self.storage.get(inode_of_parent) {
Some(Node::Directory(DirectoryNode { .. })) => {
Ok(InodeResolution::Found(inode_of_parent))
}
Some(Node::ArcDirectory(ArcDirectoryNode { .. })) => {
Ok(InodeResolution::Found(inode_of_parent))
}
_ => Err(FsError::BaseNotDirectory),
}
}
InodeResolution::Redirect(fs, path) => Ok(InodeResolution::Redirect(fs, path)),
}
}
/// From the inode of a parent node (so, a directory), returns the
/// child index of `name_of_directory` along with its inode.
pub(super) fn as_parent_get_position_and_inode_of_directory(
&self,
inode_of_parent: Inode,
name_of_directory: &OsString,
directory_must_be_empty: DirectoryMustBeEmpty,
) -> Result<(usize, InodeResolution)> {
match self.storage.get(inode_of_parent) {
Some(Node::Directory(DirectoryNode { children, .. })) => children
.iter()
.enumerate()
.filter_map(|(nth, inode)| self.storage.get(*inode).map(|node| (nth, node)))
.find_map(|(nth, node)| match node {
Node::Directory(DirectoryNode {
inode,
name,
children,
..
}) if name.as_os_str() == name_of_directory => {
if directory_must_be_empty.no() || children.is_empty() {
Some(Ok((nth, InodeResolution::Found(*inode))))
} else {
Some(Err(FsError::DirectoryNotEmpty))
}
}
_ => None,
})
.ok_or(FsError::InvalidInput)
.and_then(identity), // flatten
Some(Node::ArcDirectory(ArcDirectoryNode {
fs, path: fs_path, ..
})) => {
let mut path = fs_path.clone();
path.push(name_of_directory);
Ok((0, InodeResolution::Redirect(fs.clone(), path)))
}
_ => Err(FsError::BaseNotDirectory),
}
}
/// From the inode of a parent node (so, a directory), returns the
/// child index of `name_of_file` along with its inode.
pub(super) fn as_parent_get_position_and_inode_of_file(
&self,
inode_of_parent: Inode,
name_of_file: &OsString,
) -> Result<Option<(usize, InodeResolution)>> {
match self.storage.get(inode_of_parent) {
Some(Node::Directory(DirectoryNode { children, .. })) => children
.iter()
.enumerate()
.filter_map(|(nth, inode)| self.storage.get(*inode).map(|node| (nth, node)))
.find_map(|(nth, node)| match node {
Node::File(FileNode { inode, name, .. })
| Node::ReadOnlyFile(ReadOnlyFileNode { inode, name, .. })
| Node::CustomFile(CustomFileNode { inode, name, .. })
| Node::ArcFile(ArcFileNode { inode, name, .. })
if name.as_os_str() == name_of_file =>
{
Some(Some((nth, InodeResolution::Found(*inode))))
}
_ => None,
})
.or(Some(None))
.ok_or(FsError::InvalidInput),
Some(Node::ArcDirectory(ArcDirectoryNode {
fs, path: fs_path, ..
})) => {
let mut path = fs_path.clone();
path.push(name_of_file);
Ok(Some((0, InodeResolution::Redirect(fs.clone(), path))))
}
_ => Err(FsError::BaseNotDirectory),
}
}
/// From the inode of a parent node (so, a directory), returns the
/// child index of `name_of` along with its inode, whatever the
/// type of inode is (directory or file).
fn as_parent_get_position_and_inode(
&self,
inode_of_parent: Inode,
name_of: &OsString,
) -> Result<Option<(usize, InodeResolution)>> {
match self.storage.get(inode_of_parent) {
Some(Node::Directory(DirectoryNode { children, .. })) => children
.iter()
.enumerate()
.filter_map(|(nth, inode)| self.storage.get(*inode).map(|node| (nth, node)))
.find_map(|(nth, node)| match node {
Node::File(FileNode { inode, name, .. })
| Node::Directory(DirectoryNode { inode, name, .. })
| Node::ReadOnlyFile(ReadOnlyFileNode { inode, name, .. })
| Node::CustomFile(CustomFileNode { inode, name, .. })
| Node::ArcFile(ArcFileNode { inode, name, .. })
if name.as_os_str() == name_of =>
{
Some(Some((nth, InodeResolution::Found(*inode))))
}
_ => None,
})
.or(Some(None))
.ok_or(FsError::InvalidInput),
Some(Node::ArcDirectory(ArcDirectoryNode {
fs, path: fs_path, ..
})) => {
let mut path = fs_path.clone();
path.push(name_of);
Ok(Some((0, InodeResolution::Redirect(fs.clone(), path))))
}
_ => Err(FsError::BaseNotDirectory),
}
}
/// Set a new name for the node represented by `inode`.
pub(super) fn update_node_name(&mut self, inode: Inode, new_name: OsString) -> Result<()> {
let node = self.storage.get_mut(inode).ok_or(FsError::UnknownError)?;
node.set_name(new_name);
node.metadata_mut().modified = time();
Ok(())
}
/// Add a child to a directory node represented by `inode`.
///
/// This function also updates the modified time of the directory.
///
/// # Safety
///
/// `inode` must represents an existing directory.
pub(super) fn add_child_to_node(&mut self, inode: Inode, new_child: Inode) -> Result<()> {
match self.storage.get_mut(inode) {
Some(Node::Directory(DirectoryNode {
children,
metadata: Metadata { modified, .. },
..
})) => {
children.push(new_child);
*modified = time();
Ok(())
}
_ => Err(FsError::UnknownError),
}
}
/// Remove the child at position `position` of a directory node
/// represented by `inode`.
///
/// This function also updates the modified time of the directory.
///
/// # Safety
///
/// `inode` must represents an existing directory.
pub(super) fn remove_child_from_node(&mut self, inode: Inode, position: usize) -> Result<()> {
match self.storage.get_mut(inode) {
Some(Node::Directory(DirectoryNode {
children,
metadata: Metadata { modified, .. },
..
})) => {
children.remove(position);
*modified = time();
Ok(())
}
_ => Err(FsError::UnknownError),
}
}
/// Canonicalize a path, i.e. try to resolve to a canonical,
/// absolute form of the path with all intermediate components
/// normalized:
///
/// * A path must starts with a root (`/`),
/// * A path can contain `..` or `.` components,
/// * A path must not contain a Windows prefix (`C:` or `\\server`),
/// * A normalized path exists in the file system.
pub(super) fn canonicalize(&self, path: &Path) -> Result<(PathBuf, InodeResolution)> {
let new_path = self.canonicalize_without_inode(path)?;
let inode = self.inode_of(&new_path)?;
Ok((new_path, inode))
}
/// Like `Self::canonicalize` but without returning the inode of
/// the path, which means that there is no guarantee that the path
/// exists in the file system.
pub(super) fn canonicalize_without_inode(&self, path: &Path) -> Result<PathBuf> {
let mut components = path.components();
match components.next() {
Some(Component::RootDir) => {}
_ => return Err(FsError::InvalidInput),
}
let mut new_path = PathBuf::with_capacity(path.as_os_str().len());
new_path.push("/");
for component in components {
match component {
// That's an error to get a `RootDir` a second time.
Component::RootDir => return Err(FsError::UnknownError),
// Nothing to do on `new_path`.
Component::CurDir => (),
// Pop the lastly inserted component on `new_path` if
// any, otherwise it's an error.
Component::ParentDir => {
if !new_path.pop() {
return Err(FsError::InvalidInput);
}
}
// A normal
Component::Normal(name) => {
new_path.push(name);
}
// We don't support Windows path prefix.
Component::Prefix(_) => return Err(FsError::InvalidInput),
}
}
Ok(new_path)
}
}
impl fmt::Debug for FileSystemInner {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
formatter,
"\n{inode:<8} {ty:<4} name",
inode = "inode",
ty = "type",
)?;
fn debug(
nodes: Vec<&Node>,
slf: &FileSystemInner,
formatter: &mut fmt::Formatter<'_>,
indentation: usize,
) -> fmt::Result {
for node in nodes {
writeln!(
formatter,
"{inode:<8} {ty:<4} {indentation_symbol:indentation_width$}{name}",
inode = node.inode(),
ty = match node {
Node::File { .. } => "file",
Node::ReadOnlyFile { .. } => "ro-file",
Node::ArcFile { .. } => "arc-file",
Node::CustomFile { .. } => "custom-file",
Node::Directory { .. } => "dir",
Node::ArcDirectory { .. } => "arc-dir",
},
name = node.name().to_string_lossy(),
indentation_symbol = " ",
indentation_width = indentation * 2 + 1,
)?;
if let Node::Directory(DirectoryNode { children, .. }) = node {
debug(
children
.iter()
.filter_map(|inode| slf.storage.get(*inode))
.collect(),
slf,
formatter,
indentation + 1,
)?;
}
}
Ok(())
}
debug(
vec![self.storage.get(ROOT_INODE).unwrap()],
self,
formatter,
0,
)
}
}
impl Default for FileSystemInner {
fn default() -> Self {
let time = time();
let mut slab = Slab::new();
slab.insert(Node::Directory(DirectoryNode {
inode: ROOT_INODE,
name: OsString::from("/"),
children: Vec::new(),
metadata: Metadata {
ft: FileType {
dir: true,
..Default::default()
},
accessed: time,
created: time,
modified: time,
len: 0,
},
}));
Self { storage: slab }
}
}
#[cfg(test)]
mod test_filesystem {
use crate::{mem_fs::*, DirEntry, FileSystem as FS, FileType, FsError};
macro_rules! path {
($path:expr) => {
std::path::Path::new($path)
};
(buf $path:expr) => {
std::path::PathBuf::from($path)
};
}
#[test]
fn test_new_filesystem() {
let fs = FileSystem::default();
let fs_inner = fs.inner.read().unwrap();
assert_eq!(fs_inner.storage.len(), 1, "storage has a root");
assert!(
matches!(
fs_inner.storage.get(ROOT_INODE),
Some(Node::Directory(DirectoryNode {
inode: ROOT_INODE,
name,
children,
..
})) if name == "/" && children.is_empty(),
),
"storage has a well-defined root",
);
}
#[test]
fn test_create_dir() {
let fs = FileSystem::default();
assert_eq!(
fs.create_dir(path!("/")),
Err(FsError::AlreadyExists),
"creating the root which already exists",
);
assert_eq!(fs.create_dir(path!("/foo")), Ok(()), "creating a directory",);
{
let fs_inner = fs.inner.read().unwrap();
assert_eq!(
fs_inner.storage.len(),
2,
"storage contains the new directory"
);
assert!(
matches!(
fs_inner.storage.get(ROOT_INODE),
Some(Node::Directory(DirectoryNode {
inode: ROOT_INODE,
name,
children,
..