2020-04-30 20:11:06 +00:00
|
|
|
use std::fs;
|
|
|
|
use std::os::unix::fs::MetadataExt;
|
2020-11-28 10:14:20 +00:00
|
|
|
use std::path::Path;
|
2020-04-30 20:11:06 +00:00
|
|
|
|
2020-06-01 14:56:24 +00:00
|
|
|
/// Reads the file and strips whitespace (including newlines)
|
2020-04-30 20:11:06 +00:00
|
|
|
/// Useful for file-based key-value store
|
2020-06-01 14:56:24 +00:00
|
|
|
pub fn read_or_none(path: &Path) -> Option<String> {
|
2020-04-30 20:11:06 +00:00
|
|
|
if !path.is_file() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
match fs::read_to_string(path) {
|
|
|
|
Ok(content) => {
|
|
|
|
// Remove trailing space/newlines
|
|
|
|
Some(content.trim().to_string())
|
2020-11-25 22:59:39 +00:00
|
|
|
}
|
2020-04-30 20:11:06 +00:00
|
|
|
Err(e) => {
|
|
|
|
eprintln!("IO ERROR: {}", e);
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-28 10:14:20 +00:00
|
|
|
pub fn read_extension(path: &Path, setting: &str) -> Option<String> {
|
|
|
|
let mut path = path.to_path_buf();
|
|
|
|
path.set_extension(setting);
|
|
|
|
read_or_none(&path)
|
|
|
|
}
|
|
|
|
|
2020-11-25 22:55:33 +00:00
|
|
|
/// Returns true when the file exists and has user exec
|
|
|
|
/// permission. Returns false otherwise.
|
2020-06-01 14:56:24 +00:00
|
|
|
pub fn is_executable(path: &Path) -> bool {
|
|
|
|
// Do not match directories
|
|
|
|
if !path.is_file() {
|
|
|
|
return false;
|
|
|
|
}
|
2020-04-30 20:11:06 +00:00
|
|
|
match fs::metadata(path) {
|
|
|
|
Ok(stat) => {
|
|
|
|
let mode = stat.mode();
|
|
|
|
// Check user exec permission)
|
|
|
|
if (mode & 0o100) == 0o100 {
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
2020-11-25 22:59:39 +00:00
|
|
|
}
|
2020-04-30 20:11:06 +00:00
|
|
|
Err(e) => {
|
|
|
|
eprintln!("IO Error: {}", e);
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|