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
use std::fs::{remove_file, File, OpenOptions};
use std::io::{Read, Result, Seek, Write};
use std::ops::{Deref, DerefMut, Drop};
use std::path::{Path, PathBuf};

/// Wraps a file with its paired lock file.
///
/// The lock file is deleted upon dropping
#[derive(Debug)]
pub struct LockedFile {
    file: File,
    path: PathBuf,
    lock_file_path: PathBuf,
}

impl LockedFile {
    /// Attempts to open a read/write view of the specified file
    ///
    /// This will fail if there is any existing lock on the file. Will create the file
    /// if it does not exist.
    pub fn open_read_write<T: AsRef<Path>>(path: T) -> Result<Option<LockedFile>> {
        // generate the lock file path
        let path = path.as_ref().to_path_buf();
        let extension = if let Some(ext) = path.extension() {
            // FIXME: Really need to handle this in a way that doesn't panic on non unicode
            let mut ext = String::from(ext.to_string_lossy());
            ext.push_str(".lock");
            ext
        } else {
            "lock".to_string()
        };
        let lock_file_path = path.with_extension(extension);
        // Check to see if the lock file exists
        if Path::exists(&lock_file_path) {
            // Unable to return the lock, failing
            Ok(None)
        } else {
            // First, create the lock file
            OpenOptions::new()
                .create(true)
                .write(true)
                .open(&lock_file_path)?;
            // Second, open the real file
            let file = OpenOptions::new()
                .create(true)
                .read(true)
                .write(true)
                .open(&path)?;
            Ok(Some(LockedFile {
                file,
                path,
                lock_file_path,
            }))
        }
    }
}

impl Deref for LockedFile {
    type Target = File;
    fn deref(&self) -> &File {
        &self.file
    }
}

impl DerefMut for LockedFile {
    fn deref_mut(&mut self) -> &mut File {
        &mut self.file
    }
}

impl Drop for LockedFile {
    fn drop(&mut self) {
        // Check to see if the lock file exists before doing anything, if it is already gone (i.e.
        // if it was in a now dropped tempdir) we dont need to do anything
        if self.lock_file_path.exists() {
            // Delete the lock file
            remove_file(&self.lock_file_path).unwrap_or_else(|_| {
                panic!(
                    "Unable to delete lock file for {:?}, something went wrong",
                    self.path
                )
            });
        }
    }
}

impl Read for LockedFile {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.file.read(buf)
    }
}

impl Write for LockedFile {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.file.write(buf)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.file.flush()
    }
}

impl Seek for LockedFile {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.file.seek(pos)
    }
}