use std::path::Path;
pub fn hide<T: AsRef<Path>>(path: T) -> bool {
let path = path.as_ref();
if !path.exists() {
return false;
}
cfg_if::cfg_if! {
if #[cfg(unix)] {
use os_str_bytes::OsStrBytes;
use os_str_bytes::OsStringBytes;
use std::ffi::OsString;
use std::path::PathBuf;
if let Some(str) = path.file_name() {
let bytes = str.to_raw_bytes();
if bytes[0] == b'.' {
return true; }
let mut vec = bytes.to_vec();
vec.insert(0, b'.');
let mut copy: PathBuf = path.into();
copy.set_file_name(OsString::from_raw_vec(vec).unwrap());
return std::fs::rename(path, copy).is_ok();
}
false } else {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::SetFileAttributesW;
use windows_sys::Win32::Storage::FileSystem::GetFileAttributesW;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN;
use windows_sys::Win32::Storage::FileSystem::INVALID_FILE_ATTRIBUTES;
use windows_sys::Win32::Foundation::PWSTR;
let mut file: Vec<u16> = path.as_os_str().encode_wide().collect();
file.push(0x0000);
unsafe {
let file: PWSTR = std::mem::transmute(file.as_ptr());
let attrs = GetFileAttributesW(file);
if attrs == INVALID_FILE_ATTRIBUTES {
return false;
}
SetFileAttributesW(file, attrs | FILE_ATTRIBUTE_HIDDEN) != 0
}
}
}
}
pub fn unhide<T: AsRef<Path>>(path: T) -> bool {
let path = path.as_ref();
if !path.exists() {
return false;
}
cfg_if::cfg_if! {
if #[cfg(unix)] {
use os_str_bytes::OsStrBytes;
use os_str_bytes::OsStringBytes;
use std::ffi::OsString;
use std::path::PathBuf;
if let Some(str) = path.file_name() {
let bytes = str.to_raw_bytes();
if bytes[0] != b'.' {
return true; }
let mut vec = bytes.to_vec();
vec.remove(0); let mut copy: PathBuf = path.into();
copy.set_file_name(OsString::from_raw_vec(vec).unwrap());
return std::fs::rename(path, copy).is_ok();
}
false } else {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::SetFileAttributesW;
use windows_sys::Win32::Storage::FileSystem::GetFileAttributesW;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN;
use windows_sys::Win32::Storage::FileSystem::INVALID_FILE_ATTRIBUTES;
use windows_sys::Win32::Foundation::PWSTR;
let mut file: Vec<u16> = path.as_os_str().encode_wide().collect();
file.push(0x0000);
unsafe {
let file: PWSTR = std::mem::transmute(file.as_ptr());
let attrs = GetFileAttributesW(file);
if attrs == INVALID_FILE_ATTRIBUTES {
return false;
}
SetFileAttributesW(file, attrs & !FILE_ATTRIBUTE_HIDDEN) != 0
}
}
}
}