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
//! Virtual file system allows you to work with relative file paths in a convenient way.

use std::fs;
use std::io::{Error, ErrorKind, Result};
use std::path::{Component, Path, PathBuf};

use std::fs::DirEntry;

/// A reference to an virtual file system.
pub struct VirtualFileSystem {
    root: PathBuf,
}

impl VirtualFileSystem {
    /// Creates new `VirtualFileSystem`.
    ///
    /// `root` - base directory for VFS.
    /// A `root` path must exists; else return value will be `io::Error`.
    /// It will be normalized.
    pub fn try_new<P: AsRef<Path>>(root: P) -> Result<Self> {
        Path::new(root.as_ref())
            .canonicalize()
            .map(|path| Self { root: path })
    }

    /// Returns a root path.
    pub fn root(&self) -> PathBuf {
        self.root.clone()
    }

    /// Convert relative `path` to absolute.
    ///
    /// If `path` is absolute and starts with current `root`, then return it, else return `None`.
    /// If `path` is relative, then append it to the end of the current `root` and return joined path.
    pub fn absolute<P: AsRef<Path>>(&self, path: P) -> Option<PathBuf> {
        if path.as_ref().is_relative() {
            Some(Self::normalize(self.root.join(Self::native_path(path))))
        } else {
            let path_norm = Self::normalize(path.as_ref());
            if path_norm.starts_with(&self.root) {
                Some(path_norm)
            } else {
                None
            }
        }
    }

    /// Convert absolute `path` to relative.
    ///
    /// If `path` is relative, then normalize it and return.
    /// If `path` is equal to `root`, then return `.` (current).
    /// If `root` equals to `/foo/bar` and `path` equals to `/foo/bar/more`, then return `more`.
    pub fn relative<P: AsRef<Path>>(&self, path: P) -> Option<PathBuf> {
        let path = self.absolute(path)?;
        Some(Self::normalize(path.strip_prefix(&self.root).unwrap()))
    }

    /// Returns true if the path points at an existing entity.
    pub fn exists<P: AsRef<Path>>(&self, path: P) -> bool {
        if let Some(path) = self.absolute(path) {
            path.exists()
        } else {
            false
        }
    }

    /// Change current `root`.
    ///
    /// A `new_root` path may be absolute or relative.
    /// Return true if `root` was change.
    pub fn chroot<P: AsRef<Path>>(&mut self, new_root: P) -> bool {
        match self.absolute(new_root) {
            Some(path) => {
                self.root = path;
                true
            }
            None => false,
        }
    }

    /// Creates a new, empty directory at the provided path.
    pub fn create_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        match self.absolute(path) {
            Some(path) => {
                fs::create_dir(path)?;
                Ok(())
            }
            None => Err(Error::from(ErrorKind::NotFound)),
        }
    }

    /// Recursively create a directory and all of its parent components if they are missing.
    pub fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        match self.absolute(path) {
            Some(path) => {
                fs::create_dir_all(path)?;
                Ok(())
            }
            None => Err(Error::from(ErrorKind::NotFound)),
        }
    }

    /// Removes an existing, empty directory.
    pub fn remove_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        match self.absolute(path) {
            Some(path) => {
                fs::remove_dir(path)?;
                Ok(())
            }
            None => Err(Error::from(ErrorKind::NotFound)),
        }
    }

    /// Removes a directory at this path, after removing all its contents. Use carefully!
    pub fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        match self.absolute(path) {
            Some(path) => {
                fs::remove_dir_all(path)?;
                Ok(())
            }
            None => Err(Error::from(ErrorKind::NotFound)),
        }
    }

    /// Recursively traverses the contents of the directory and calls a callback for each item.
    pub fn visit_all(&self, cb: &dyn Fn(&DirEntry)) -> Result<()> {
        return recursive(&self.root, cb);

        fn recursive(dir: &Path, cb: &dyn Fn(&DirEntry)) -> Result<()> {
            if dir.is_dir() {
                for entry in fs::read_dir(dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.is_dir() {
                        recursive(&path, cb)?;
                    }
                    cb(&entry);
                }
            }
            Ok(())
        }
    }

    fn normalize<P: AsRef<Path>>(path: P) -> PathBuf {
        match path.as_ref().components().count() {
            0 => PathBuf::from("."),

            1 => PathBuf::from(path.as_ref()),

            _ => {
                let mut normalized = PathBuf::new();
                for component in path.as_ref().components() {
                    match component {
                        Component::CurDir => {}
                        Component::ParentDir => {
                            if normalized.components().count() == 0 {
                                normalized.push(component);
                            } else {
                                if normalized.components().last().unwrap() == Component::ParentDir {
                                    normalized.push(component);
                                } else if normalized.components().last().unwrap()
                                    != Component::RootDir
                                {
                                    normalized.pop();
                                }
                            }
                        }
                        _ => normalized.push(component),
                    }
                }
                normalized
            }
        }
    }

    /// Replaces the separator of path with the correct one for the given OS.
    fn native_path<P: AsRef<Path>>(path: P) -> PathBuf {
        let mut pb = PathBuf::new();
        for part in path.as_ref().components() {
            pb.push(part);
        }
        pb
    }
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::VirtualFileSystem;
    //use std::fs::DirEntry;

    const ROOT: &str = "tests/root";

    fn new_vfs() -> VirtualFileSystem {
        VirtualFileSystem::try_new(ROOT).unwrap()
    }

    fn cur_dir() -> PathBuf {
        Path::new(ROOT).canonicalize().unwrap()
    }

    #[test]
    fn normalize_ok() {
        assert_eq!(VirtualFileSystem::normalize(""), PathBuf::from("."));
        assert_eq!(VirtualFileSystem::normalize("."), PathBuf::from("."));
        assert_eq!(VirtualFileSystem::normalize(".."), PathBuf::from(".."));
        assert_eq!(VirtualFileSystem::normalize("../."), PathBuf::from(".."));
        assert_eq!(
            VirtualFileSystem::normalize("../.."),
            PathBuf::from("../..")
        );
        assert_eq!(
            VirtualFileSystem::normalize("../../.."),
            PathBuf::from("../../..")
        );
        assert_eq!(
            VirtualFileSystem::normalize(".././.."),
            PathBuf::from("../..")
        );
        assert_eq!(VirtualFileSystem::normalize("./dir"), PathBuf::from("dir"));
        assert_eq!(
            VirtualFileSystem::normalize("../dir"),
            PathBuf::from("../dir")
        );
        assert_eq!(
            VirtualFileSystem::normalize("../dir/.."),
            PathBuf::from("..")
        );
        assert_eq!(
            VirtualFileSystem::normalize("./first/second/.."),
            PathBuf::from("first")
        );
        assert_eq!(
            VirtualFileSystem::normalize("first/./second"),
            PathBuf::from("first/second")
        );
        #[cfg(windows)]
        {
            assert_eq!(
                VirtualFileSystem::normalize(r"\\?\C:\"),
                PathBuf::from(r"\\?\C:\")
            );
            assert_eq!(
                VirtualFileSystem::normalize(r"\\?\C:\."),
                PathBuf::from(r"\\?\C:\")
            );
            assert_eq!(
                VirtualFileSystem::normalize(cur_dir().join(r"more\..")),
                PathBuf::from(cur_dir())
            );
        }
    }

    #[test]
    fn root_ok() {
        let vfs = new_vfs();
        assert_eq!(vfs.root, cur_dir());
        assert_eq!(vfs.root(), cur_dir());
    }

    #[test]
    fn absolute_ok() {
        let vfs = new_vfs();
        assert_eq!(vfs.absolute(".").unwrap(), cur_dir());
        assert_eq!(vfs.absolute("more").unwrap(), cur_dir().join("more"));
        assert_eq!(
            vfs.absolute(cur_dir().join("more")).unwrap(),
            cur_dir().join("more")
        );
        #[cfg(unix)]
        assert_eq!(vfs.absolute(PathBuf::from("/other/absolute")), None);
        #[cfg(windows)]
        {
            assert_eq!(vfs.absolute(PathBuf::from(r"F:\other\absolute")), None);
            assert_eq!(vfs.absolute("more/example.txt").unwrap(), cur_dir().join(r"more\example.txt"));
        }
    }

    #[test]
    fn relative_ok() {
        let vfs = new_vfs();
        assert_eq!(
            vfs.relative("./relative").unwrap(),
            PathBuf::from("relative")
        );
        assert_eq!(vfs.relative(cur_dir()).unwrap(), PathBuf::from("."));
        assert_eq!(
            vfs.relative(cur_dir().join("more")).unwrap(),
            PathBuf::from("more")
        );
        #[cfg(unix)]
        assert_eq!(vfs.relative(PathBuf::from("/other/absolute")), None);
        #[cfg(windows)]
        {
            assert_eq!(vfs.relative(PathBuf::from(r"F:\other\absolute")), None);
            assert_eq!(vfs.relative("tests/root").unwrap(), PathBuf::from("tests\\root"));
            assert_eq!(vfs.relative(cur_dir().join("more/other")).unwrap(), PathBuf::from(r"more\other"));
        }
    }

    #[test]
    fn exists_ok() {
        let vfs = new_vfs();
        #[cfg(unix)]
        assert!(vfs.exists("more/example.txt"));
        #[cfg(windows)]
        {
            assert!(vfs.exists(r"more\example.txt"));
            assert!(vfs.exists("more/example.txt"));
        }

        assert!(!vfs.exists("foo"));
    }

    #[test]
    fn chroot_ok() {
        let mut vfs = new_vfs();

        // new root == old root
        assert!(vfs.chroot("."));
        assert_eq!(vfs.root, cur_dir());

        // new root relative
        assert!(vfs.chroot("more"));
        assert_eq!(vfs.root, cur_dir().join("more"));

        // new root absolute
        #[cfg(unix)]
        assert!(vfs.chroot("../.."));
        #[cfg(windows)]
        assert!(vfs.chroot(r"..\.."));

        assert_eq!(vfs.root, cur_dir().parent().unwrap());
    }

    #[test]
    fn create_dir_ok() {
        let vfs = new_vfs();
        vfs.create_dir("new_dir").unwrap();
        assert!(vfs.exists("new_dir"));
        vfs.remove_dir("new_dir").unwrap();
    }

    #[test]
    fn remove_dir_ok() {
        let vfs = new_vfs();
        vfs.create_dir("new_dir").unwrap();
        assert!(vfs.exists("new_dir"));
        vfs.remove_dir("new_dir").unwrap();
        assert!(!vfs.exists("new_dir"));
    }

    #[test]
    fn create_dir_all_ok() {
        let vfs = new_vfs();
        #[cfg(unix)]
        {
            vfs.create_dir_all("new1/new2").unwrap();
            assert!(vfs.exists("new1/new2"));
            vfs.remove_dir_all("new1/new2").unwrap();
        }
        #[cfg(windows)]
        {
            vfs.create_dir_all(r"new1\new2").unwrap();
            assert!(vfs.exists(r"new1\new2"));
            vfs.remove_dir_all(r"new1\new2").unwrap();

            vfs.create_dir_all("new1/new2").unwrap();
            assert!(vfs.exists("new1/new2"));
            vfs.remove_dir_all("new1/new2").unwrap();
        }
    }

    #[test]
    fn remove_dir_all_ok() {
        let vfs = new_vfs();
        #[cfg(unix)]
        {
            vfs.create_dir_all("new1/new2").unwrap();
            assert!(vfs.exists("new1/new2"));
            vfs.remove_dir_all("new1/new2").unwrap();
            vfs.remove_dir_all("new1").unwrap();
            assert!(!vfs.exists("new1/new2"));
            assert!(!vfs.exists("new1"));
        }
        #[cfg(windows)]
        {
            vfs.create_dir_all(r"new1\new2").unwrap();
            assert!(vfs.exists(r"new1\new2"));
            vfs.remove_dir_all(r"new1\new2").unwrap();
            vfs.remove_dir_all("new1").unwrap();
            assert!(!vfs.exists(r"new1\new2"));
            assert!(!vfs.exists("new1"));
        }
    }

    //    #[test]
    //    fn visit_all_ok() {
    //        let vfs = VirtualFileSystem::try_new(r"C:\dev\Exercism").unwrap();
    //        vfs.visit_all(&|entry: &DirEntry| {
    //            println!("{:?}", entry.path());
    //        }).unwrap();
    //    }
}