use std::fs::write;
use std::fs::{self, create_dir_all};
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use dirs::cache_dir;
use super::rm::RoError;
pub fn check_cross_device(item: &Path) -> RoError<'_, ()> {
let item_metadata = fs::metadata(item).unwrap().dev();
create_dir_all(cache_dir().unwrap().join("roxide")).unwrap();
write(
cache_dir().unwrap().join("roxide/state.txt"),
"Just a file to check CrossesDevices Error.",
)
.unwrap();
let file_in_device = cache_dir()
.unwrap()
.join("roxide/state.txt")
.metadata()
.unwrap()
.dev();
if item_metadata != file_in_device {
return Err(crate::core::error::Error::CrossesDevices(item));
}
Ok(())
}
pub fn check_root() -> bool {
use std::fs;
if let Ok(status) = fs::read_to_string("/proc/self/status") {
for line in status.lines() {
if line.starts_with("Uid:") {
let uid = line.split_whitespace().nth(1);
return uid == Some("0");
}
}
}
false
}
#[cfg(test)]
mod test {
use std::fs::{create_dir_all, remove_dir_all};
use std::path;
use super::{check_cross_device, check_root};
#[test]
fn check_cross_device_test() {
create_dir_all("trash/tests/check_cross_device_test/test_dir").unwrap();
check_cross_device(path::Path::new(
"trash/tests/check_cross_device_test/test_dir",
))
.unwrap();
let path = path::Path::new("/media/usb");
if path.exists() {
create_dir_all(path.join("test_dir")).unwrap();
if check_cross_device(&path.join("test_dir")).is_ok() {
panic!("check_cross_device function failed!");
}
}
remove_dir_all("trash/tests/check_cross_device_test").unwrap();
}
#[test]
fn check_root_test() {
if path::Path::new("/proc/self/status").exists() {
if check_root() {
panic!("is root!");
}
} else {
panic!("/proc/self/status not found!");
}
}
}