refactor: done

This commit is contained in:
GyDi
2022-11-18 18:18:41 +08:00
parent 34daffbc96
commit 2667ed13f1
24 changed files with 343 additions and 341 deletions

View File

@@ -1,48 +0,0 @@
use anyhow::{anyhow, bail, Context, Result};
use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::{Mapping, Value};
use std::{fs, path::PathBuf};
/// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
if !path.exists() {
bail!("file not found \"{}\"", path.display());
}
let yaml_str = fs::read_to_string(&path)
.context(format!("failed to read the file \"{}\"", path.display()))?;
serde_yaml::from_str::<T>(&yaml_str).context(format!(
"failed to read the file with yaml format \"{}\"",
path.display()
))
}
/// read mapping from yaml fix #165
pub fn read_merge_mapping(path: &PathBuf) -> Result<Mapping> {
let mut val: Value = read_yaml(path)?;
val.apply_merge()
.context(format!("failed to apply merge \"{}\"", path.display()))?;
Ok(val
.as_mapping()
.ok_or(anyhow!(
"failed to transform to yaml mapping \"{}\"",
path.display()
))?
.to_owned())
}
/// save the data to the file
/// can set `prefix` string to add some comments
pub fn save_yaml<T: Serialize>(path: PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = serde_yaml::to_string(data)?;
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}\n{data_str}"),
None => data_str,
};
let path_str = path.as_os_str().to_string_lossy().to_string();
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
}

View File

@@ -1,5 +1,5 @@
use anyhow::Result;
use std::{env::temp_dir, path::PathBuf};
use std::path::PathBuf;
use tauri::{
api::path::{home_dir, resource_dir},
Env, PackageInfo,
@@ -107,14 +107,6 @@ pub fn profiles_path() -> Result<PathBuf> {
Ok(app_home_dir()?.join(PROFILE_YAML))
}
pub fn clash_runtime_yaml() -> Result<PathBuf> {
Ok(app_home_dir()?.join("clash-verge-runtime.yaml"))
}
pub fn clash_check_yaml() -> Result<PathBuf> {
Ok(temp_dir().join("clash-verge-check.yaml"))
}
pub fn app_res_dir() -> Result<PathBuf> {
unsafe {
Ok(RESOURCE_DIR

View File

@@ -1,8 +1,52 @@
use anyhow::Result;
use anyhow::{anyhow, bail, Context, Result};
use nanoid::nanoid;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::{Mapping, Value};
use std::{fs, path::PathBuf, process::Command, str::FromStr};
/// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
if !path.exists() {
bail!("file not found \"{}\"", path.display());
}
let yaml_str = fs::read_to_string(&path)
.context(format!("failed to read the file \"{}\"", path.display()))?;
serde_yaml::from_str::<T>(&yaml_str).context(format!(
"failed to read the file with yaml format \"{}\"",
path.display()
))
}
/// read mapping from yaml fix #165
pub fn read_merge_mapping(path: &PathBuf) -> Result<Mapping> {
let mut val: Value = read_yaml(path)?;
val.apply_merge()
.context(format!("failed to apply merge \"{}\"", path.display()))?;
Ok(val
.as_mapping()
.ok_or(anyhow!(
"failed to transform to yaml mapping \"{}\"",
path.display()
))?
.to_owned())
}
/// save the data to the file
/// can set `prefix` string to add some comments
pub fn save_yaml<T: Serialize>(path: &PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = serde_yaml::to_string(data)?;
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}\n\n{data_str}"),
None => data_str,
};
let path_str = path.as_os_str().to_string_lossy().to_string();
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
}
const ALPHABET: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
@@ -68,16 +112,6 @@ macro_rules! error {
};
}
#[deprecated]
#[macro_export]
macro_rules! log_if_err {
($result: expr) => {
if let Err(err) = $result {
log::error!(target: "app", "{err}");
}
};
}
#[macro_export]
macro_rules! log_err {
($result: expr) => {

View File

@@ -1,4 +1,4 @@
use crate::utils::{dirs, tmpl};
use crate::utils::dirs;
use anyhow::Result;
use chrono::Local;
use log::LevelFilter;
@@ -7,7 +7,6 @@ use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use std::fs;
use std::io::Write;
use tauri::PackageInfo;
/// initialize this instance's log file
@@ -21,13 +20,20 @@ fn init_log() -> Result<()> {
let log_file = format!("{}.log", local_time);
let log_file = log_dir.join(log_file);
#[cfg(feature = "verge-dev")]
let time_format = "{d(%Y-%m-%d %H:%M:%S)} {l} - {M} {m}{n}";
#[cfg(not(feature = "verge-dev"))]
let time_format = "{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}";
let stdout = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new(time_format)))
.build();
let tofile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new(time_format)))
.build(log_file)?;
let encode = Box::new(PatternEncoder::new(time_format));
let stdout = ConsoleAppender::builder().encoder(encode.clone()).build();
let tofile = FileAppender::builder().encoder(encode).build(log_file)?;
#[cfg(feature = "verge-dev")]
let level = LevelFilter::Debug;
#[cfg(not(feature = "verge-dev"))]
let level = LevelFilter::Info;
let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
@@ -36,9 +42,9 @@ fn init_log() -> Result<()> {
Logger::builder()
.appenders(["file", "stdout"])
.additive(false)
.build("app", LevelFilter::Info),
.build("app", level),
)
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
.build(Root::builder().appender("stdout").build(level))?;
log4rs::init_config(config)?;
@@ -58,21 +64,6 @@ pub fn init_config() -> Result<()> {
if !app_dir.exists() {
let _ = fs::create_dir_all(&app_dir);
}
// // target path
// let clash_path = app_dir.join("config.yaml");
// let verge_path = app_dir.join("verge.yaml");
// let profile_path = app_dir.join("profiles.yaml");
// if !clash_path.exists() {
// fs::File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
// }
// if !verge_path.exists() {
// fs::File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
// }
// if !profile_path.exists() {
// fs::File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
// }
});
let _ = dirs::app_profiles_dir().map(|profiles_dir| {

View File

@@ -1,4 +1,3 @@
pub mod config;
pub mod dirs;
pub mod help;
pub mod init;

View File

@@ -10,9 +10,10 @@ pub fn resolve_setup(app: &mut App) {
handle::Handle::global().init(app.app_handle());
init::init_resources(app.package_info());
log_err!(init::init_resources(app.package_info()));
// 启动核心
log_err!(Config::init_config());
log_err!(CoreManager::global().init());
// setup a simple http server for singleton