diskit 0.1.5

Utilities for intercepting disk requests.
Documentation
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
//! Logging diskit
//!
//! For more information see the [struct level documentation](LogDiskit).

// This is a pedantic lint trying to get the output prettier, but I
// explicitly want the logging to not be pretty, but fully escaped, so
// this is a false positive.
#![allow(clippy::unnecessary_debug_formatting)]

use std::{
    io::{Error, ErrorKind, SeekFrom},
    mem::{self, ManuallyDrop},
    path::{Path, PathBuf},
    sync::{Arc, Mutex, MutexGuard},
};

use crate::{
    dir_entry::DirEntry,
    file::{File, FileInner},
    metadata::Metadata,
    open_options::OpenOptions,
    walkdir::{WalkDir, WalkdirIterator, WalkdirIteratorInner},
    Diskit,
};

/// Data type of the logging functions
pub type LogFunc = Box<dyn Fn(String) + Send>;

/// Logging diskit
///
/// This diskit extensively logs all requests it gets and passes them
/// to an other diskit (like [`StdDiskit`](crate::StdDiskit) or
/// [`VirtualDiskit`](crate::VirtualDiskit)) to satisfy.
///
/// Every request is logged before an operation is performed and after
/// – in a style depending on whether it was successful or not – it
/// completed by passing a [`String`] to the [logging](LogDiskit::log)
/// function (the [default logging
/// function](get_standard_log_func) prints them to
/// `stdout`).
/// ```
/// use diskit::{diskit_extend::DiskitExt, log_diskit, LogDiskit, VirtualDiskit};
/// use std::{
///     io::Write,
///     sync::{Arc, Mutex},
/// };
///
/// # fn main() -> Result<(), std::io::Error>
/// # {
/// let output = Arc::new(Mutex::new(String::new()));
/// let diskit = LogDiskit::new(
///     VirtualDiskit::default(),
///     log_diskit::get_log_in_buf_func(output.clone()),
/// );
///
/// let mut file = diskit.create("test.txt")?;
/// file.write_all(b"Hello, World!")?;
///
/// file.close()?;
///
/// assert_eq!(*output.lock().unwrap(),
///     "Creating \"test.txt\".
/// Created \"test.txt\": FileInner { file: None, val: 0 }.
/// Writing all of [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33] into FileInner { file: None, val: 0 }.
/// Wrote all of [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33] in FileInner { file: None, val: 0 }.
/// Closing FileInner { file: None, val: 0 }.
/// Closed a file.
/// ");
///
/// # Ok(())
/// # }
/// ```
/// You can write your own logging function or use one of the two
/// predefined ones: [`get_standard_log_func`] and
/// [`get_log_in_buf_func`].
// See lib.rs for justification.
#[allow(missing_docs)]
#[derive(Clone)]
pub struct LogDiskit<D>
where
    D: Diskit,
{
    pub inner: D,
    pub log: Arc<Mutex<LogFunc>>,
}

impl<D> LogDiskit<D>
where
    D: Diskit,
{
    /// Creates a new custom [`LogDiskit`]
    ///
    /// Creates a new [`LogDiskit`] with the given inner diskit and
    /// logging function.
    pub fn new(inner: D, log: LogFunc) -> Self
    {
        Self::new_raw(inner, Arc::new(Mutex::new(log)))
    }

    /// Creates a new custom [`LogDiskit`] with a reference to a logging function
    ///
    /// Creates a new [`LogDiskit`] with the given inner diskit and an
    /// [`Arc<Mutex<_>>`] of the logging function.  This is useful if
    /// you want to share one function between two [`LogDiskit`]s.
    pub fn new_raw(inner: D, log: Arc<Mutex<LogFunc>>) -> Self
    {
        Self { inner, log }
    }

    /// Sets the logging function
    ///
    /// Changes the logging function to the provided one.
    pub fn set_log_func(&mut self, log: LogFunc)
    {
        self.set_log_func_raw(Arc::new(Mutex::new(log)));
    }

    /// Sets the logging function with a reference to a logging function
    ///
    /// Changes the logging function to the provided one allowing to
    /// share one function between multiple [`LogDiskit`]s.
    pub fn set_log_func_raw(&mut self, log: Arc<Mutex<LogFunc>>)
    {
        self.log = log;
    }

    fn lock_log(&self) -> Result<MutexGuard<'_, LogFunc>, ErrorKind>
    {
        self.log.lock().map_err(|_| ErrorKind::Other)
    }
}

impl<D> Default for LogDiskit<D>
where
    D: Diskit,
{
    fn default() -> Self
    {
        Self::new(D::default(), get_standard_log_func())
    }
}

impl<D> Diskit for LogDiskit<D>
where
    D: Diskit,
{
    fn set_pwd_inner(&self, path: &Path) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Setting pwd to {path:?}."));

        match self.inner.set_pwd_inner(path)
        {
            Ok(()) =>
            {
                log(format!("Set pwd to {path:?}."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!("Failed to set pwd to {path:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn get_pwd(&self) -> Result<PathBuf, Error>
    {
        let log = self.lock_log()?;

        log("Getting pwd.".to_owned());

        match self.inner.get_pwd()
        {
            Ok(path) =>
            {
                log(format!("Got pwd: {path:?}."));

                Ok(path)
            }
            Err(err) =>
            {
                log(format!("Failed to get pwd: {err:?}."));

                Err(err)
            }
        }
    }

    fn open_inner(&self, path: &Path) -> Result<File<Self>, Error>
    {
        let log = self.lock_log()?;

        log(format!("Opening {path:?}."));

        match self.inner.open_inner(path)
        {
            Ok(file) =>
            {
                let inner = mem::replace(
                    &mut ManuallyDrop::new(file).inner,
                    FileInner { file: None, val: 0 },
                );

                log(format!("Opened {path:?}: {inner:?}."));

                Ok(File {
                    inner,
                    diskit: self.clone(),
                })
            }
            Err(err) =>
            {
                log(format!("Failed to open {path:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn create_inner(&self, path: &Path) -> Result<File<Self>, Error>
    {
        let log = self.lock_log()?;

        log(format!("Creating {path:?}."));

        match self.inner.create_inner(path)
        {
            Ok(file) =>
            {
                let inner = mem::replace(
                    &mut ManuallyDrop::new(file).inner,
                    FileInner { file: None, val: 0 },
                );

                log(format!("Created {path:?}: {inner:?}."));

                Ok(File {
                    inner,
                    diskit: self.clone(),
                })
            }
            Err(err) =>
            {
                log(format!("Failed to create {path:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn open_with_options_inner(
        &self,
        path: &Path,
        options: OpenOptions,
    ) -> Result<File<Self>, Error>
    {
        let log = self.lock_log()?;

        log(format!("Opening {path:?} with options {options:?}."));

        match self.inner.open_with_options_inner(path, options)
        {
            Ok(file) =>
            {
                let inner = mem::replace(
                    &mut ManuallyDrop::new(file).inner,
                    FileInner { file: None, val: 0 },
                );

                log(format!(
                    "Opened {path:?} with options {options:?}: {inner:?}."
                ));

                Ok(File {
                    inner,
                    diskit: self.clone(),
                })
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to open {path:?} with options {options:?}: {err:?}."
                ));

                Err(err)
            }
        }
    }

    fn read_inner(&self, file: &FileInner, buf: &mut [u8]) -> Result<usize, Error>
    {
        let log = self.lock_log()?;

        log(format!("Reading {file:?} into {buf:?}."));

        match self.inner.read_inner(file, buf)
        {
            Ok(n) =>
            {
                log(format!("Read {n:?} bytes of {file:?}: {buf:?}."));

                Ok(n)
            }
            Err(err) =>
            {
                log(format!("Failed to read {file:?} into {buf:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn read_to_end_inner(&self, file: &mut FileInner, buf: &mut Vec<u8>) -> Result<usize, Error>
    {
        let log = self.lock_log()?;

        log(format!("Reading {file:?} to end into {buf:?}."));

        match self.inner.read_to_end_inner(file, buf)
        {
            Ok(n) =>
            {
                log(format!("Read {n:?} bytes of {file:?} to end: {buf:?}."));

                Ok(n)
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to read {file:?} into {buf:?} to end: {err:?}."
                ));

                Err(err)
            }
        }
    }

    fn read_to_string_inner(&self, file: &mut FileInner, buf: &mut String) -> Result<usize, Error>
    {
        let log = self.lock_log()?;

        log(format!("Reading {file:?} to string into {buf:?}."));

        match self.inner.read_to_string_inner(file, buf)
        {
            Ok(n) =>
            {
                log(format!("Read {n:?} bytes of {file:?} to string: {buf:?}."));

                Ok(n)
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to read {file:?} into {buf:?} to string: {err:?}."
                ));

                Err(err)
            }
        }
    }

    fn write_inner(&self, file: &mut FileInner, buf: &[u8]) -> Result<usize, Error>
    {
        let log = self.lock_log()?;

        log(format!("Writing {buf:?} into {file:?}."));

        match self.inner.write_inner(file, buf)
        {
            Ok(n) =>
            {
                log(format!("Wrote {n:?} bytes of {buf:?} in {file:?}."));

                Ok(n)
            }
            Err(err) =>
            {
                log(format!("Failed to write {buf:?} into {file:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn write_all_inner(&self, file: &mut FileInner, buf: &[u8]) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Writing all of {buf:?} into {file:?}."));

        match self.inner.write_all_inner(file, buf)
        {
            Ok(()) =>
            {
                log(format!("Wrote all of {buf:?} in {file:?}."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to write all of {buf:?} into {file:?}: {err:?}."
                ));

                Err(err)
            }
        }
    }

    fn flush_inner(&self, file: &mut FileInner) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Flushing {file:?}."));

        match self.inner.flush_inner(file)
        {
            Ok(()) =>
            {
                log(format!("Flushed {file:?}."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!("Failed to flush {file:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn metadata_inner(&self, file: &FileInner) -> Result<Metadata, Error>
    {
        let log = self.lock_log()?;

        log(format!("Retrieving metadata of {file:?}."));

        match self.inner.metadata_inner(file)
        {
            Ok(metadata) =>
            {
                log(format!("Retrieved metadata of {file:?}: {metadata:?}."));

                Ok(metadata)
            }
            Err(err) =>
            {
                log(format!("Failed to retrieve metadata of {file:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn seek_inner(&self, file: &mut FileInner, pos: SeekFrom) -> Result<u64, Error>
    {
        let log = self.lock_log()?;

        log(format!("Seeking {file:?} to {pos:?}."));

        match self.inner.seek_inner(file, pos)
        {
            Ok(pos_rv) =>
            {
                log(format!(
                    "Seeked {file:?} to {pos_rv:?} (requested: {pos:?})."
                ));

                Ok(pos_rv)
            }
            Err(err) =>
            {
                log(format!("Failed to seek {file:?} to {pos:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn create_dir_inner(&self, path: &Path) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Creating directory {path:?}."));

        match self.inner.create_dir_inner(path)
        {
            Ok(()) =>
            {
                log(format!("Created directory {path:?}."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!("Failed to create directory {path:?}: {err:?}."));

                Err(err)
            }
        }
    }

    fn create_dir_all_inner(&self, path: &Path) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Creating directory {path:?} recursively."));

        match self.inner.create_dir_all_inner(path)
        {
            Ok(()) =>
            {
                log(format!("Created directory {path:?} recursively."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to create directory {path:?} recursively: {err:?}."
                ));

                Err(err)
            }
        }
    }

    fn close_inner(&self, file: FileInner) -> Result<(), Error>
    {
        let log = self.lock_log()?;

        log(format!("Closing {file:?}."));

        match self.inner.close_inner(file)
        {
            Ok(()) =>
            {
                log("Closed a file.".to_string());

                Ok(())
            }
            Err(err) =>
            {
                log(format!("Failed to close a file: {err:?}."));

                Err(err)
            }
        }
    }

    fn walkdir_inner(&self, path: &Path) -> WalkDir<Self>
    {
        let log = self
            .lock_log()
            .expect("Failed to get lock on logging function");

        log(format!("Constructing `WalkDir` for {path:?}."));

        let WalkDir { diskit: _, options } = self.inner.walkdir_inner(path);

        log(format!("Constructed `WalkDir` for {path:?}: {options:?}."));

        WalkDir {
            diskit: self.clone(),
            options,
        }
    }

    fn into_walkdir_iterator(&self, walkdir: WalkDir<Self>) -> WalkdirIterator<Self>
    {
        let log = self
            .lock_log()
            .expect("Failed to get lock on logging function");

        log(format!(
            "Constructing `WalkDirIterator` from {:?}.",
            walkdir.options
        ));

        let WalkdirIterator { inner } = self.inner.into_walkdir_iterator(WalkDir {
            diskit: self.inner.clone(),
            options: walkdir.options.clone(),
        });

        match inner
        {
            Ok((inner, _)) =>
            {
                log(format!(
                    "Constructed `WalkDirIterator` from {:?}: {inner:?}.",
                    walkdir.options,
                ));

                WalkdirIterator {
                    inner: Ok((inner, self.clone())),
                }
            }
            Err(err) =>
            {
                log(format!(
                    "Failed to construct `WalkDirIterator` from {:?}: {err:?}.",
                    walkdir.options
                ));
                WalkdirIterator { inner: Err(err) }
            }
        }
    }

    fn walkdir_next_inner(
        &self,
        inner: &mut WalkdirIteratorInner,
    ) -> Option<Result<DirEntry, Error>>
    {
        let log = self.lock_log().ok()?;

        log(format!("Getting next file from {inner:?}."));

        match self.inner.walkdir_next_inner(inner)
        {
            Some(Ok(dir_entry)) =>
            {
                log(format!("Got next file from {inner:?}: {dir_entry:?}."));

                Some(Ok(dir_entry))
            }
            Some(Err(err)) =>
            {
                log(format!("Failed to get next file from {inner:?}: {err:?}."));

                Some(Err(err))
            }
            None =>
            {
                log(format!("Iterator {inner:?} is finished."));

                None
            }
        }
    }

    #[cfg(feature = "trash")]
    fn trash_delete_inner(&self, path: &Path) -> Result<(), trash::Error>
    {
        let log = self.lock_log().map_err(|_| {
            trash::into_unknown(format!("Failed to acquire lock to trash {path:?}"))
        })?;

        log(format!("Trashing {path:?}."));

        match self.inner.trash_delete_inner(path)
        {
            Ok(()) =>
            {
                log(format!("Thrashed {path:?}."));

                Ok(())
            }
            Err(err) =>
            {
                log(format!("Failed to trash {path:?}: {err:?}."));

                Err(err)
            }
        }
    }
}

/// Returns a copy of the standard logging function
///
/// This creates a new copy of the standard logging function.  This
/// function [`println`](println)s all messages.
#[must_use]
pub fn get_standard_log_func() -> LogFunc
{
    Box::new(|msg| println!("{msg}"))
}

/// Returns a function that logs in the provided buffer
///
/// The function that is returned by this function writes all logs in
/// the provided buffer (always adding a newline at the end).
// This is a false positive in two ways, a) the code with the panic is
// just returned not executed in this function itself and b) `lock`
// only returns `Err` if the mutex is poisoned which is impossible
// here since the lock is never held over code that could panic.
#[allow(clippy::missing_panics_doc)]
#[must_use]
pub fn get_log_in_buf_func(buf: Arc<Mutex<String>>) -> LogFunc
{
    Box::new(move |s| {
        let mut lock = buf.lock().unwrap();
        lock.push_str(&s);
        lock.push('\n');
    })
}