use std::{env, fs};
use std::fs::{DirBuilder, remove_file};
use std::path::Path;
use json::{JsonValue, object};
use log::error;
pub fn root_path() -> String {
let data = env::current_exe().unwrap();
let file_name = Path::new(data.to_str().unwrap());
let file_name = file_name.parent().unwrap();
let dir_name = file_name.parent().unwrap();
if file_name.is_dir() && dir_name.file_name().unwrap() != "target" {
return file_name.to_str().unwrap().to_string();
}
let data = data.parent().unwrap().parent().unwrap().parent().unwrap();
return data.to_str().unwrap().to_string();
}
pub fn file_path(dir: &str, filename: &str) -> String {
let root_path = root_path();
let file_name = Path::new(root_path.as_str());
let file_name = file_name.join(dir);
let file_name = file_name.join(filename);
return file_name.to_str().unwrap().to_string();
}
pub fn dir_path(dir: &str) -> String {
let root_path = root_path();
let file_name = Path::new(root_path.as_str());
let file_name = file_name.join(dir);
return file_name.to_str().unwrap().to_string();
}
pub fn create_dir(path: &str) -> bool {
match DirBuilder::new().recursive(true).create(path) {
Ok(_) => {
return true;
}
Err(_e) => {
return false;
}
}
}
pub fn dir_files(path: &str) -> Vec<String> {
let mut files = vec![];
for entry in walkdir::WalkDir::new(path) {
match entry {
Ok(e) => {
if e.path().is_dir() {
continue;
}
files.push(e.path().display().to_string())
}
_ => {}
}
}
return files;
}
pub fn file_content_get(path: &str) -> String {
let data = fs::read_to_string(path);
match data {
Ok(content) => {
return content;
}
Err(e) => {
error!("{}", e);
return "".to_string();
}
}
}
pub fn file_content_get_stream(path: &str) -> String {
let file = fs::read(path).unwrap();
let contents = unsafe { String::from_utf8_unchecked(file) };
contents
}
pub fn file_content_get_json(path: &str) -> JsonValue {
if !is_file(path) {
return object! {};
}
let data = file_content_get(path);
if data == "" {
return object! {};
}
json::parse(data.as_str()).unwrap()
}
pub fn file_content_put(path: &str, data: &str) -> bool {
create_dir(path);
let data = fs::write(path, data);
match data {
Ok(_) => {
return true;
}
Err(e) => {
error!("{}", e);
return false;
}
}
}
pub fn file_content_put_u8(path: &str, data: Vec<u8>) -> bool {
create_dir(path);
let data = fs::write(path, data);
match data {
Ok(_) => {
return true;
}
Err(e) => {
error!("{}", e);
return false;
}
}
}
pub fn is_file(file: &str) -> bool {
let o = Path::new(file);
return o.is_file();
}
pub fn is_dir(path: &str) -> bool {
let o = Path::new(path);
return o.is_dir();
}
pub fn remove(path: &str) -> bool {
let res = remove_file(path);
match res {
Ok(_) => {
true
}
Err(e) => {
error!("remove file error:{}", e);
false
}
}
}