about summary refs log tree commit diff
path: root/src/filesystem.rs
blob: 3d9cd9951322a67772ac51eb0d0dd84d5586e47e (plain)
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
use anyhow::{Context, Result};
use std::{
    fs::{self, DirEntry, File, OpenOptions},
    io::{self, Read, Seek, Write},
    path::{Path, PathBuf},
};

pub trait Fs {
    type File;
    type Entry: FsEntry;

    fn create_file(&self, path: &Path) -> Result<Self::File>;
    fn delete_file(&self, path: &Path) -> Result<()>;
    fn open_readable_file(&self, path: &Path) -> Result<Self::File>;
    fn open_writable_file(&self, path: &Path) -> Result<Self::File>;

    fn create_directory(&self, path: &Path) -> Result<()>;
    fn read_directory(&self, path: &Path) -> Result<Vec<Self::Entry>>;
    fn delete_directory(&self, path: &Path) -> Result<()>;

    fn write_to_file(&self, file: &mut Self::File, buffer: Vec<u8>) -> Result<()>;
    fn read_from_file(&self, file: &mut Self::File) -> Result<Vec<u8>>;

    fn path_exists(&self, path: &Path) -> bool;
}

pub trait FsEntry {
    fn path(&self) -> PathBuf;
    fn is_directory(&self) -> Result<bool>;
}

pub struct FsImpl {}

impl Fs for FsImpl {
    type File = File;
    type Entry = DirEntry;

    fn create_file(&self, path: &Path) -> Result<Self::File> {
        if let Some(parent_path) = path.parent() {
            if !parent_path.exists() {
                fs::create_dir_all(parent_path)?;
            }
        }

        OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .open(path)
            .with_context(|| format!("Failed creating '{}'.", path.display()))
    }

    fn delete_file(&self, path: &Path) -> Result<()> {
        fs::remove_file(path)?;
        Ok(())
    }

    fn open_readable_file(&self, path: &Path) -> Result<Self::File> {
        File::open(path)
            .with_context(|| format!("Failed opening '{}' for reading.", path.display()))
    }

    fn open_writable_file(&self, path: &Path) -> Result<Self::File> {
        OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .with_context(|| {
                format!(
                    "Failed opening '{}' for reading and writing.",
                    path.display()
                )
            })
    }

    fn create_directory(&self, path: &Path) -> Result<()> {
        fs::create_dir_all(path)
            .with_context(|| format!("Failed creating directory '{}'.", path.display()))
    }

    fn read_directory(&self, path: &Path) -> Result<Vec<Self::Entry>> {
        let result: io::Result<_> = fs::read_dir(path)?.collect();
        result.with_context(|| format!("Failed reading directory {}", path.display()))
    }

    fn delete_directory(&self, path: &Path) -> Result<()> {
        fs::remove_dir_all(path)
            .with_context(|| format!("Failed deleting directory '{}'.", path.display()))
    }

    fn write_to_file(&self, file: &mut Self::File, buffer: Vec<u8>) -> Result<()> {
        file.rewind()?;
        file.set_len(0)?;
        file.write_all(&buffer)?;
        Ok(())
    }

    fn read_from_file(&self, file: &mut Self::File) -> Result<Vec<u8>> {
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        Ok(buffer)
    }

    fn path_exists(&self, path: &Path) -> bool {
        path.exists()
    }
}

impl FsEntry for DirEntry {
    fn path(&self) -> PathBuf {
        self.path()
    }

    fn is_directory(&self) -> Result<bool> {
        let file_type = self.file_type()?;
        Ok(file_type.is_dir())
    }
}

// TODO: This will be used for tests. Write them.
#[allow(dead_code)]
#[cfg(test)]
pub mod mock {
    use anyhow::{anyhow, Result};
    use std::{
        collections::{hash_map, HashMap, HashSet},
        path::{Path, PathBuf},
        sync::{Arc, Mutex, MutexGuard},
    };

    use super::{Fs, FsEntry};

    pub struct FsMock {
        state: Arc<Mutex<FsState>>,
    }

    impl FsMock {
        pub fn new() -> Self {
            let state = FsState {
                entries: HashMap::new(),
            };

            FsMock {
                state: Arc::new(Mutex::new(state)),
            }
        }

        pub fn set_state(&mut self, new_state: FsState) {
            let mut state = self.state.lock().expect("FsMock state lock poisoned.");
            *state = new_state;
        }

        pub fn assert_match(&self, expected_state: FsState) {
            let diff = expected_state.diff(&self.state());
            if !diff.is_empty() {
                panic!(
                    "Mock filesystem state does not match the expected state:\n {}",
                    diff.join("\n")
                )
            }
        }

        fn state(&self) -> MutexGuard<FsState> {
            self.state.lock().expect("FsMock state lock poisoned.")
        }
    }

    impl<'fs> Fs for FsMock {
        type File = FileMock;

        type Entry = EntryMock;

        fn create_file(&self, path: &Path) -> Result<Self::File> {
            let mut state = self.state();
            if let Some(file) = state.get_or_create_file(path) {
                Ok(file)
            } else {
                if state.is_directory(path) {
                    Err(anyhow!(
                        "The file '{}' can't be opened or created, because it is a directory.",
                        path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The file '{}' can't be opened or created, because one of it's parent paths which have to be created is occupied.",
                        path.display()
                    ))
                }
            }
        }

        fn delete_file(&self, path: &Path) -> Result<()> {
            let mut state = self.state();
            if state.delete_if_file(path) {
                Ok(())
            } else {
                if state.is_directory(path) {
                    Err(anyhow!(
                        "The file '{}' can't be deleted because it is a directory.",
                        path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The file '{}' can't be deleted because it doesn't exist.",
                        path.display()
                    ))
                }
            }
        }

        fn open_readable_file(&self, path: &Path) -> Result<Self::File> {
            let state = self.state();
            if let Some(file) = state.get_file_for_reading(path) {
                Ok(file)
            } else {
                if state.is_directory(path) {
                    Err(anyhow!(
                        "The file '{}' can't be opened for reading because it is a directory.",
                        path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The file '{}' can't be opened for reading because it doesn't exist.",
                        path.display()
                    ))
                }
            }
        }

        fn open_writable_file(&self, path: &Path) -> Result<Self::File> {
            let state = self.state();
            if let Some(file) = state.get_file(path) {
                Ok(file)
            } else {
                if state.is_directory(path) {
                    Err(anyhow!("The file '{}' can't be opened for reading and writing because it is a directory.", path.display()))
                } else {
                    Err(anyhow!("The file '{}' can't be opened for reading and writing because it doesn't exist.", path.display()))
                }
            }
        }

        fn create_directory(&self, path: &Path) -> Result<()> {
            let mut state = self.state();
            if state.create_directory(path) {
                Ok(())
            } else {
                if state.is_directory(path) {
                    Err(anyhow!(
                        "The directory '{}' can't be created because it already exists.",
                        path.display()
                    ))
                } else if state.is_file(path) {
                    Err(anyhow!("The directory '{}' can't be created because there is a file with the same path.", path.display()))
                } else {
                    Err(anyhow!(
                        "The directory '{}' can't be opened or created, because one of it's parent paths which have to be created is occupied.",
                        path.display()
                    ))
                }
            }
        }

        fn read_directory(&self, path: &Path) -> Result<Vec<Self::Entry>> {
            let state = self.state();
            if let Some(entries) = state.get_entries_if_directory(path) {
                Ok(entries)
            } else {
                if state.is_file(path) {
                    Err(anyhow!(
                        "The directory '{}' can't be read because it is a file.",
                        path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The directory '{}' can't be read because it doesn't exist.",
                        path.display()
                    ))
                }
            }
        }

        fn delete_directory(&self, path: &Path) -> Result<()> {
            let mut state = self.state();
            if state.delete_if_directory(path) {
                Ok(())
            } else {
                if state.is_file(path) {
                    Err(anyhow!(
                        "The directory '{}' can't be deleted because it is a file.",
                        path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The directory '{}' can't be deleted because it doesn't exist.",
                        path.display()
                    ))
                }
            }
        }

        fn write_to_file(&self, file: &mut Self::File, buffer: Vec<u8>) -> Result<()> {
            let mut state = self.state();
            if file.writable {
                if state.write_to_if_file(&file.path, buffer) {
                    Ok(())
                } else {
                    if state.is_directory(&file.path) {
                        Err(anyhow!(
                            "The file '{}' can't be written to because it is a directory.",
                            file.path.display()
                        ))
                    } else {
                        Err(anyhow!(
                            "The file '{}' can't be written to because it doesn't exist.",
                            file.path.display()
                        ))
                    }
                }
            } else {
                Err(anyhow!(
                    "The file '{}' is not writable.",
                    file.path.display()
                ))
            }
        }

        fn read_from_file(&self, file: &mut Self::File) -> Result<Vec<u8>> {
            let state = self.state();
            if let Some(content) = state.get_content_if_file(&file.path) {
                Ok(content)
            } else {
                if state.is_directory(&file.path) {
                    Err(anyhow!(
                        "The file '{}' can't be read from because it is a directory.",
                        file.path.display()
                    ))
                } else {
                    Err(anyhow!(
                        "The file '{}' can't be read from because it doesn't exist.",
                        file.path.display()
                    ))
                }
            }
        }

        fn path_exists(&self, path: &Path) -> bool {
            self.state().exists(path)
        }
    }

    pub struct FsState {
        entries: HashMap<PathBuf, EntryMock>,
    }

    impl FsState {
        pub fn new(entries: Vec<EntryMock>) -> Self {
            let mut map = HashMap::new();
            for entry in entries {
                map.insert(entry.path(), entry);
            }

            Self { entries: map }
        }

        fn diff(&self, other: &Self) -> Vec<String> {
            let mut differences = Vec::new();

            let mut keys = HashSet::new();
            keys.extend(self.entries.keys());
            keys.extend(other.entries.keys());

            for path in keys {
                match (self.entries.get(path), other.entries.get(path)) {
                    (Some(own_entry), Some(other_entry)) => match own_entry {
                        EntryMock::File(own_file) => {
                            if let EntryMock::File(other_file) = other_entry {
                                if own_file.content != other_file.content {
                                    differences.push(format!(
                                        "The contents of the file '{}' do not match.
                                    Excepted: {:?},
                                    Received: {:?}",
                                        path.display(),
                                        own_file.content,
                                        other_file.content
                                    ))
                                }
                            } else {
                                differences.push(format!(
                                    "Expected file at '{}', instead found a directory.",
                                    path.display(),
                                ))
                            }
                        }
                        EntryMock::Dir { .. } => {
                            if let EntryMock::File(_) = other_entry {
                                differences.push(format!(
                                    "Expected directory at '{}', instead found a file.",
                                    path.display(),
                                ))
                            }
                        }
                    },
                    (None, Some(missing_entry_for_own)) => {
                        differences.push(match missing_entry_for_own {
                            EntryMock::File(_) => {
                                format!("Found unexpected file at '{}'.", path.display())
                            }
                            EntryMock::Dir { .. } => {
                                format!("Found unexpected directory at '{}'.", path.display())
                            }
                        })
                    }
                    (Some(missing_entry_for_other), None) => {
                        differences.push(match missing_entry_for_other {
                            EntryMock::File(_) => {
                                format!("Expected file at '{}'.", path.display())
                            }
                            EntryMock::Dir { .. } => {
                                format!("Expected directory at '{}'.", path.display())
                            }
                        })
                    }
                    _ => unreachable!(),
                }
            }

            differences
        }

        fn get_or_create_file(&mut self, path: &Path) -> Option<FileMock> {
            if let Some(parent) = path.parent() {
                if !self.is_directory(parent) && !self.create_directory(path) {
                    return None;
                }
            }

            let path_buf = path.to_path_buf();
            match self.entries.entry(path_buf.clone()) {
                hash_map::Entry::Occupied(occupied) => match occupied.get() {
                    EntryMock::File(file) => Some(file.clone()),
                    _ => None,
                },
                hash_map::Entry::Vacant(vacant) => {
                    let file = FileMock {
                        path: path_buf,
                        writable: true,
                        content: Vec::new(),
                    };
                    vacant.insert(EntryMock::File(file.clone()));
                    Some(file)
                }
            }
        }

        fn delete_if_file(&mut self, path: &Path) -> bool {
            if self.is_file(path) {
                self.entries.remove(path).is_some()
            } else {
                false
            }
        }

        fn get_file(&self, path: &Path) -> Option<FileMock> {
            match self.entries.get(path) {
                Some(entry) => match entry {
                    EntryMock::File(file) => Some(file.clone()),
                    _ => None,
                },
                _ => None,
            }
        }

        fn get_file_for_reading(&self, path: &Path) -> Option<FileMock> {
            self.get_file(path).map(|mut f| {
                f.writable = false;
                f
            })
        }

        fn get_content_if_file(&self, path: &Path) -> Option<Vec<u8>> {
            self.get_file(path).map(|f| f.content)
        }

        fn write_to_if_file(&mut self, path: &Path, buffer: Vec<u8>) -> bool {
            match self.entries.get_mut(path) {
                Some(entry) => match entry {
                    EntryMock::File(file) => {
                        file.content = buffer;
                        true
                    }
                    _ => false,
                },
                _ => false,
            }
        }

        fn create_directory(&mut self, path: &Path) -> bool {
            if let Some(parent) = path.parent() {
                if !self.is_directory(parent) && !self.create_directory(path) {
                    return false;
                }
            }

            let path_buf = path.to_path_buf();
            match self.entries.entry(path_buf.clone()) {
                hash_map::Entry::Vacant(vacant) => {
                    vacant.insert(EntryMock::Dir { path: path_buf });
                    true
                }
                _ => false,
            }
        }

        fn delete_if_directory(&mut self, path: &Path) -> bool {
            if self.is_directory(path) {
                self.entries.remove(path).is_some()
            } else {
                false
            }
        }

        fn get_entries_if_directory(&self, path: &Path) -> Option<Vec<EntryMock>> {
            if self.is_directory(path) {
                let directory_entries = self
                    .entries
                    .iter()
                    .filter(|&(path, _)| {
                        if let Some(parent) = path.parent() {
                            parent == path
                        } else {
                            false
                        }
                    })
                    .map(|(_, entry)| entry.clone())
                    .collect();

                Some(directory_entries)
            } else {
                None
            }
        }

        fn is_file(&self, path: &Path) -> bool {
            self.entries
                .get(path)
                .map_or(false, |e| matches!(e, EntryMock::File(_)))
        }

        fn is_directory(&self, path: &Path) -> bool {
            self.entries
                .get(path)
                .map_or(false, |e| matches!(e, EntryMock::Dir { .. }))
        }

        fn exists(&self, path: &Path) -> bool {
            self.entries.contains_key(path)
        }
    }

    #[derive(Clone)]
    pub struct FileMock {
        path: PathBuf,
        writable: bool,
        content: Vec<u8>,
    }

    #[derive(Clone)]
    pub enum EntryMock {
        File(FileMock),
        Dir { path: PathBuf },
    }

    impl EntryMock {
        pub fn file(path_str: &str, content: &[u8]) -> Self {
            EntryMock::File(FileMock {
                path: Path::new(path_str).to_path_buf(),
                writable: true,
                content: content.to_vec(),
            })
        }

        pub fn dir(path_str: &str) -> Self {
            EntryMock::Dir {
                path: Path::new(path_str).to_path_buf(),
            }
        }
    }

    impl FsEntry for EntryMock {
        fn path(&self) -> PathBuf {
            match self {
                EntryMock::File(FileMock { path, .. }) => path.clone(),
                EntryMock::Dir { path } => path.clone(),
            }
        }

        fn is_directory(&self) -> Result<bool> {
            Ok(matches!(self, EntryMock::Dir { .. }))
        }
    }
}