shell-rs 0.2.6

Rust reimplementation of common coreutils APIs
Documentation
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::path::Path;

use crate::error::Error;

#[derive(Debug, PartialEq)]
pub enum SyncMode {
    /// Sync all filesystem caches in system to disk.
    Sync,

    /// Sync the file systems that contain the file.
    Filesystem,

    /// Sync file data and metadata.
    File,

    /// Sync only file data, no unneeded metadata.
    Data,
}

/// Sychronize cached writes to persistent storage.
pub fn sync<P: AsRef<Path>>(file: Option<P>, mode: SyncMode) -> Result<(), Error> {
    if mode == SyncMode::Sync || file.is_none() {
        return unsafe { nc::sync().map_err(Into::into) };
    }
    let file = file.unwrap();
    let file = file.as_ref();
    let mut open_flags = nc::O_RDONLY | nc::O_NONBLOCK;
    let mut fd = unsafe { nc::open(file, open_flags, 0) };
    if fd.is_err() {
        open_flags = nc::O_WRONLY | nc::O_NONBLOCK;
        fd = unsafe { nc::open(file, open_flags, 0) };
    }
    let fd = fd?;
    // We used O_NONBLOCK above to not hang with fifos, so reset that here.
    let fdflags = unsafe { nc::fcntl(fd, nc::F_GETFL, 0)? };
    let _ = unsafe { nc::fcntl(fd, nc::F_SETFL, (fdflags & !nc::O_NONBLOCK) as usize)? };

    match mode {
        SyncMode::Filesystem => unsafe { nc::syncfs(fd)? },
        SyncMode::File => unsafe { nc::fsync(fd)? },
        SyncMode::Data => unsafe { nc::fdatasync(fd)? },
        _ => (),
    }

    unsafe { nc::close(fd)? };
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sync() {
        assert!(sync::<&str>(None, SyncMode::Sync).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::Filesystem).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::File).is_ok());
        assert!(sync(Some("/etc/passwd"), SyncMode::Data).is_ok());
    }
}