VirtWeb/virtweb_backend/src/utils/files_utils.rs

60 lines
1.4 KiB
Rust
Raw Normal View History

2023-12-06 20:27:59 +01:00
use std::os::unix::fs::PermissionsExt;
2023-10-26 11:43:05 +02:00
use std::path::Path;
2023-09-05 13:19:25 +02:00
const INVALID_CHARS: [&str; 19] = [
"@", "\\", "/", ":", ",", "<", ">", "%", "'", "\"", "?", "{", "}", "$", "*", "|", ";", "=",
"\t",
];
/// Check out whether a file name is valid or not
pub fn check_file_name(name: &str) -> bool {
!name.is_empty() && !INVALID_CHARS.iter().any(|c| name.contains(c))
}
/// Create directory if missing
2023-10-26 11:43:05 +02:00
pub fn create_directory_if_missing<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
let path = path.as_ref();
2023-09-05 13:19:25 +02:00
if !path.exists() {
std::fs::create_dir_all(path)?;
}
Ok(())
}
2023-12-06 20:27:59 +01:00
/// Update file permission
pub fn set_file_permission<P: AsRef<Path>>(path: P, mode: u32) -> anyhow::Result<()> {
let mut perms = std::fs::metadata(path.as_ref())?.permissions();
perms.set_mode(mode);
std::fs::set_permissions(path.as_ref(), perms)?;
Ok(())
}
2023-09-05 13:19:25 +02:00
#[cfg(test)]
mod test {
use crate::utils::files_utils::check_file_name;
#[test]
fn empty_file_name() {
assert!(!check_file_name(""));
}
#[test]
fn parent_dir_file_name() {
assert!(!check_file_name("../file.test"));
}
#[test]
fn windows_parent_dir_file_name() {
assert!(!check_file_name("..\\test.fr"));
}
#[test]
fn special_char_file_name() {
assert!(!check_file_name("test:test.@"));
}
#[test]
fn valid_file_name() {
assert!(check_file_name("test.iso"));
}
}