| 1 |
use crate::FileTime; |
| 2 |
use std::ffi::CString; |
| 3 |
use std::fs; |
| 4 |
use std::io; |
| 5 |
use std::os::unix::prelude::*; |
| 6 |
use std::path::Path; |
| 7 |
|
| 8 |
fn get_times( |
| 9 |
atime: Option<FileTime>, |
| 10 |
mtime: Option<FileTime>, |
| 11 |
current: impl FnOnce() -> io::Result<fs::Metadata>, |
| 12 |
) -> io::Result<Option<(FileTime, FileTime)>> { |
| 13 |
let pair = match (atime, mtime) { |
| 14 |
(Some(a), Some(b)) => (a, b), |
| 15 |
(None, None) => return Ok(None), |
| 16 |
(Some(a), None) => { |
| 17 |
let meta = current()?; |
| 18 |
(a, FileTime::from_last_modification_time(&meta)) |
| 19 |
} |
| 20 |
(None, Some(b)) => { |
| 21 |
let meta = current()?; |
| 22 |
(FileTime::from_last_access_time(&meta), b) |
| 23 |
} |
| 24 |
}; |
| 25 |
Ok(Some(pair)) |
| 26 |
} |
| 27 |
|
| 28 |
#[allow(dead_code)] |
| 29 |
pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { |
| 30 |
set_times(p, Some(atime), Some(mtime), true) |
| 31 |
} |
| 32 |
|
| 33 |
pub fn set_times( |
| 34 |
p: &Path, |
| 35 |
atime: Option<FileTime>, |
| 36 |
mtime: Option<FileTime>, |
| 37 |
symlink: bool, |
| 38 |
) -> io::Result<()> { |
| 39 |
let (atime, mtime) = match get_times(atime, mtime, || p.metadata())? { |
| 40 |
Some(pair) => pair, |
| 41 |
None => return Ok(()), |
| 42 |
}; |
| 43 |
let p = CString::new(p.as_os_str().as_bytes())?; |
| 44 |
let times = [to_timeval(&atime), to_timeval(&mtime)]; |
| 45 |
let rc = unsafe { |
| 46 |
if symlink { |
| 47 |
libc::lutimes(p.as_ptr(), times.as_ptr()) |
| 48 |
} else { |
| 49 |
libc::utimes(p.as_ptr(), times.as_ptr()) |
| 50 |
} |
| 51 |
}; |
| 52 |
return if rc == 0 { |
| 53 |
Ok(()) |
| 54 |
} else { |
| 55 |
Err(io::Error::last_os_error()) |
| 56 |
}; |
| 57 |
} |
| 58 |
|
| 59 |
fn to_timeval(ft: &FileTime) -> libc::timeval { |
| 60 |
libc::timeval { |
| 61 |
tv_sec: ft.seconds() as libc::time_t, |
| 62 |
tv_usec: (ft.nanoseconds() / 1000) as libc::suseconds_t, |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
#[cfg(target_env = "uclibc")] |
| 67 |
fn to_timespec(ft: &FileTime) -> libc::timespec { |
| 68 |
libc::timespec { |
| 69 |
tv_sec: ft.seconds() as libc::time_t, |
| 70 |
#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] |
| 71 |
tv_nsec: (ft.nanoseconds()) as i64, |
| 72 |
#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] |
| 73 |
tv_nsec: (ft.nanoseconds()) as libc::c_long, |
| 74 |
} |
| 75 |
} |