use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use once_cell::sync::Lazy;
use crate::tina::data::AppResult;
use crate::tina::util::string::AsStr;
use crate::{app_error_from_none_static, app_system_error};
pub mod address;
pub mod base64;
pub mod client;
pub mod convert;
pub mod excel;
pub mod file;
pub mod invoke_util;
pub mod ip;
pub mod is_empty;
pub mod json;
pub mod not_empty;
pub mod num_format;
pub mod schema;
pub mod string;
pub mod string_joiner;
static GLOBAL_TEMP_PATH: Lazy<Arc<RwLock<String>>> = Lazy::new(|| {
let cur_exe = std::env::current_exe().expect("retrieve current exe failed.");
let parent = cur_exe.parent().expect("get current exe folder failed.");
let path = format!("{}/{}", parent.to_string_lossy().as_ref(), "UploadPath");
let path = Path::new(path.as_str());
Arc::new(RwLock::new(path.to_string_lossy().to_string()))
});
static TERM_FLAG: AtomicBool = AtomicBool::new(false);
pub struct Utility;
impl Utility {
pub fn set_tmp_dir(path: &Path, auto_create: bool) -> AppResult<()> {
let r = if path.is_dir() {
Ok(())
} else if auto_create {
match std::fs::create_dir_all(path) {
Ok(_) => Ok(()),
Err(err) => Err(crate::app_system_error!("create dir failed: {}, reason: {:?}", path.as_str(), err)),
}
} else {
Err(app_system_error!("path is not dir: {}", path.to_string_lossy()))
};
if r.is_ok() {
let mut lock = GLOBAL_TEMP_PATH.write().map_err(app_error_from_none_static!())?;
(*lock) = path.to_string_lossy().to_string();
}
r
}
#[allow(deprecated)]
pub fn get_tmp_dir(auto_create: bool) -> AppResult<String> {
let parent_dir = {
let lock = GLOBAL_TEMP_PATH.read().map_err(app_error_from_none_static!())?;
lock.to_string()
};
let path = Path::new(parent_dir.as_str());
if path.is_dir() {
return Ok(path.to_string_lossy().into_owned());
} else if auto_create {
return match std::fs::create_dir_all(parent_dir.as_str()) {
Ok(_) => Ok(path.to_string_lossy().into_owned()),
Err(err) => Err(crate::app_system_error!("{:?}", err)),
};
}
Err(crate::app_system_error!("failed to get tmp dir"))
}
pub fn get_current_exe_last_modified() -> SystemTime {
if let Ok(exe) = std::env::current_exe() {
if let Ok(meta_data) = std::fs::metadata(exe) {
if let Ok(modified) = meta_data.modified() {
return modified;
}
}
}
SystemTime::now()
}
pub fn get_current_exe_dir() -> AppResult<String> {
match std::env::current_exe() {
Ok(exe) => {
let parent = exe.parent().ok_or_else(|| app_system_error!("get current exe parent dir failed"))?;
Ok(parent.to_string_lossy().replacen("\\\\?\\", "", 1))
}
Err(err) => Err(app_system_error!("get current exe failed: {}", err)),
}
}
pub fn get_user_dir() -> AppResult<String> {
#[allow(deprecated)]
match std::env::home_dir() {
None => Self::get_current_exe_dir(),
Some(v) => Ok(v.as_path().to_string_lossy().into_owned()),
}
}
pub fn is_terminated() -> bool {
TERM_FLAG.load(Ordering::Relaxed)
}
pub fn terminate() {
TERM_FLAG.store(true, Ordering::Relaxed);
}
}