navid/veins / 5cec66944879958839c3441fea831ebf0f26f343353220445e794abd21872a3f / veinsrs/src/platform.rs

platform.rs

← veinsrs/src · 10691 bytes · raw · download

//! Small cross-platform shims for the OS primitives the store and worktree rely on.

use std::fs::{self, File, Metadata};
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

#[cfg(unix)]
mod imp {
    use super::*;
    use std::ffi::OsString;
    use std::os::unix::ffi::{OsStrExt, OsStringExt};
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    use std::io::IsTerminal;

    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {
        PathBuf::from(OsString::from_vec(bytes.to_vec()))
    }

    pub fn path_to_bytes(path: &Path) -> Vec<u8> {
        path.as_os_str().as_bytes().to_vec()
    }

    pub fn path_display(path: &Path) -> String {
        String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()
    }

    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {
        OsString::from_vec(bytes.to_vec())
    }

    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {
        value.into_vec()
    }

    pub fn mtime_ns(metadata: &Metadata) -> u64 {
        (metadata.mtime() as u64)
            .wrapping_mul(1_000_000_000)
            .wrapping_add(metadata.mtime_nsec() as u64)
    }

    pub fn inode(metadata: &Metadata) -> u64 {
        metadata.ino()
    }

    pub fn executable(metadata: &Metadata) -> bool {
        metadata.mode() & 0o111 != 0
    }

    pub fn permissions_mode(metadata: &Metadata) -> u32 {
        metadata.permissions().mode()
    }

    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {
        fs::set_permissions(path, fs::Permissions::from_mode(mode))
    }

    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {
        std::os::unix::fs::symlink(target, link)
    }

    pub fn sync_file(path: &Path) -> io::Result<()> {
        File::open(path)?.sync_all()
    }

    pub fn sync_directory(path: &Path) {
        if let Ok(directory) = File::open(path) {
            let _ = directory.sync_all();
        }
    }

    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
        use std::os::unix::fs::FileExt;
        file.read_at(buffer, offset)
    }

    pub fn shell(command: &str) -> Command {
        let mut process = Command::new("sh");
        process.arg("-c").arg(command);
        process
    }

    pub fn shell_quote(value: &str) -> String {
        let mut output = String::from("'");
        for character in value.chars() {
            if character == '\'' {
                output.push_str("'\\''");
            } else {
                output.push(character);
            }
        }
        output.push('\'');
        output
    }

    pub fn default_editor() -> &'static str {
        "vi"
    }

    pub fn default_pager() -> &'static str {
        "less -R"
    }

    pub fn stdin_is_terminal() -> bool {
        io::stdin().is_terminal()
    }

    pub fn stdout_is_terminal() -> bool {
        io::stdout().is_terminal()
    }

    pub fn stderr_is_terminal() -> bool {
        io::stderr().is_terminal()
    }
}

#[cfg(windows)]
mod imp {
    use super::*;
    use std::ffi::OsString;

    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {
        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
    }

    pub fn path_to_bytes(path: &Path) -> Vec<u8> {
        path.as_os_str().to_string_lossy().into_owned().into_bytes()
    }

    pub fn path_display(path: &Path) -> String {
        path.to_string_lossy().into_owned()
    }

    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {
        OsString::from(String::from_utf8_lossy(bytes).into_owned())
    }

    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {
        value.to_string_lossy().into_owned().into_bytes()
    }

    pub fn mtime_ns(metadata: &Metadata) -> u64 {
        use std::time::UNIX_EPOCH;
        metadata
            .modified()
            .ok()
            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
            .map(|elapsed| elapsed.as_nanos() as u64)
            .unwrap_or(0)
    }

    pub fn inode(_metadata: &Metadata) -> u64 {
        0
    }

    pub fn executable(_metadata: &Metadata) -> bool {
        false
    }

    pub fn permissions_mode(_metadata: &Metadata) -> u32 {
        0
    }

    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {
        let mut permissions = fs::metadata(path)?.permissions();
        permissions.set_readonly(mode & 0o200 == 0);
        fs::set_permissions(path, permissions)
    }

    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {
        std::os::windows::fs::symlink_file(target, link)
            .or_else(|_| std::os::windows::fs::symlink_dir(target, link))
    }

    pub fn sync_file(path: &Path) -> io::Result<()> {
        File::open(path)?.sync_all()
    }

    pub fn sync_directory(_path: &Path) {}

    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
        use std::os::windows::fs::FileExt;
        file.seek_read(buffer, offset)
    }

    pub fn shell(command: &str) -> Command {
        let mut process = Command::new("cmd");
        process.arg("/C").arg(command);
        process
    }

    pub fn shell_quote(value: &str) -> String {
        let mut output = String::from("\"");
        for character in value.chars() {
            if character == '"' {
                output.push_str("\\\"");
            } else {
                output.push(character);
            }
        }
        output.push('"');
        output
    }

    pub fn default_editor() -> &'static str {
        "notepad"
    }

    pub fn default_pager() -> &'static str {
        "more"
    }

    pub fn stdin_is_terminal() -> bool {
        use std::io::IsTerminal;
        io::stdin().is_terminal()
    }

    pub fn stdout_is_terminal() -> bool {
        use std::io::IsTerminal;
        io::stdout().is_terminal()
    }

    pub fn stderr_is_terminal() -> bool {
        use std::io::IsTerminal;
        io::stderr().is_terminal()
    }
}

#[cfg(not(any(unix, windows)))]
mod imp {
    use super::*;
    use std::ffi::OsString;

    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {
        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
    }

    pub fn path_to_bytes(path: &Path) -> Vec<u8> {
        path.to_string_lossy().into_owned().into_bytes()
    }

    pub fn path_display(path: &Path) -> String {
        path.to_string_lossy().into_owned()
    }

    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {
        OsString::from(String::from_utf8_lossy(bytes).into_owned())
    }

    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {
        value.to_string_lossy().into_owned().into_bytes()
    }

    pub fn mtime_ns(_metadata: &Metadata) -> u64 {
        0
    }

    pub fn inode(_metadata: &Metadata) -> u64 {
        0
    }

    pub fn executable(_metadata: &Metadata) -> bool {
        false
    }

    pub fn permissions_mode(_metadata: &Metadata) -> u32 {
        0
    }

    pub fn set_mode(_path: &Path, _mode: u32) -> io::Result<()> {
        Ok(())
    }

    pub fn create_symlink(_target: &Path, _link: &Path) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks unavailable"))
    }

    pub fn sync_file(path: &Path) -> io::Result<()> {
        File::open(path)?.sync_all()
    }

    pub fn sync_directory(_path: &Path) {}

    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
        use std::io::{Read, Seek, SeekFrom};
        let mut file = file;
        file.seek(SeekFrom::Start(offset))?;
        file.read(buffer)
    }

    pub fn shell(command: &str) -> Command {
        let mut process = Command::new("sh");
        process.arg("-c").arg(command);
        process
    }

    pub fn shell_quote(value: &str) -> String {
        let mut output = String::from("'");
        for character in value.chars() {
            if character == '\'' {
                output.push_str("'\\''");
            } else {
                output.push(character);
            }
        }
        output.push('\'');
        output
    }

    pub fn default_editor() -> &'static str {
        "vi"
    }

    pub fn default_pager() -> &'static str {
        "less -R"
    }

    pub fn stdin_is_terminal() -> bool {
        false
    }

    pub fn stdout_is_terminal() -> bool {
        false
    }

    pub fn stderr_is_terminal() -> bool {
        false
    }
}

pub use imp::*;

/// Read-only memory mapping of a pack file, used to avoid one syscall per record.
///
/// Only Unix maps; other platforms return `None` and the store falls back to
/// positioned reads, matching the C++ implementation's behaviour.
pub struct Mapping {
    #[cfg(unix)]
    ptr: *mut libc::c_void,
    #[cfg(unix)]
    len: usize,
}

#[cfg(unix)]
unsafe impl Send for Mapping {}
#[cfg(unix)]
unsafe impl Sync for Mapping {}

impl Mapping {
    pub fn open(path: &Path) -> Option<Self> {
        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            let file = File::open(path).ok()?;
            let len = file.metadata().ok()?.len();
            if len == 0 || len as u128 > usize::MAX as u128 {
                return None;
            }
            let ptr = unsafe {
                libc::mmap(
                    std::ptr::null_mut(),
                    len as usize,
                    libc::PROT_READ,
                    libc::MAP_PRIVATE,
                    file.as_raw_fd(),
                    0,
                )
            };
            if ptr == libc::MAP_FAILED {
                return None;
            }
            Some(Mapping {
                ptr,
                len: len as usize,
            })
        }
        #[cfg(not(unix))]
        {
            let _ = path;
            None
        }
    }

    pub fn as_slice(&self) -> &[u8] {
        #[cfg(unix)]
        {
            unsafe { std::slice::from_raw_parts(self.ptr as *const u8, self.len) }
        }
        #[cfg(not(unix))]
        {
            &[]
        }
    }
}

#[cfg(unix)]
impl Drop for Mapping {
    fn drop(&mut self) {
        unsafe {
            libc::munmap(self.ptr, self.len);
        }
    }
}

/// Read only the requested window of a file into a fresh buffer.
pub fn read_range(file: &File, offset: u64, length: usize) -> Option<Vec<u8>> {
    let mut data = vec![0u8; length];
    let mut done = 0;
    while done < length {
        match read_at(file, &mut data[done..], offset + done as u64) {
            Ok(0) => break,
            Ok(count) => done += count,
            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
            Err(_) => return None,
        }
    }
    data.truncate(done);
    Some(data)
}