You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/oab/src/cfg.rs

157 lines
4.1 KiB
Rust

2 years ago
//
// cfg.rs
// Copyright (C) 2022 veypi <veypi@qq.com>
// Distributed under terms of the MIT license.
//
//
//
//
//
use std::{
fs::File,
io::{self, Read},
};
2 years ago
use clap::{Args, Parser, Subcommand};
2 years ago
use lazy_static::lazy_static;
2 years ago
use sqlx::{mysql::MySqlPoolOptions, Pool};
2 years ago
lazy_static! {
pub static ref CLI: AppCli = AppCli::new();
}
lazy_static! {
pub static ref CONFIG: ApplicationConfig = ApplicationConfig::new();
}
#[derive(Debug, Parser)]
#[clap(name = "oab")]
#[clap(about = "oab", long_about = None)]
pub struct AppCli {
#[clap(short = 'c', value_name = "cfg",default_value_t = String::from("~/.config/oab/oab.yml"), value_hint = clap::ValueHint::DirPath)]
cfg: String,
#[clap(subcommand)]
pub command: Option<Clis>,
}
#[derive(Debug, Subcommand)]
pub enum Clis {
Init,
Web,
Stash(StashData),
}
#[derive(Debug, Args)]
#[clap(args_conflicts_with_subcommands = true)]
pub struct StashData {
command: Option<String>,
}
impl AppCli {
fn new() -> Self {
AppCli::parse()
}
}
2 years ago
#[derive(Debug, serde::Serialize, serde::Deserialize)]
2 years ago
pub struct ApplicationConfig {
2 years ago
pub uuid: String,
pub key: String,
2 years ago
pub debug: bool,
pub server_url: String,
2 years ago
pub media_path: String,
2 years ago
pub db_url: String,
pub db_user: String,
pub db_pass: String,
pub db_name: String,
pub log_dir: Option<String>,
2 years ago
/// "100MB" 日志分割尺寸-单位KB,MB,GB
pub log_temp_size: Option<String>,
pub log_pack_compress: Option<String>,
pub log_level: Option<String>,
pub jwt_secret: Option<String>,
2 years ago
#[serde(skip)]
pub _pool: Option<Pool<sqlx::MySql>>,
2 years ago
}
impl ApplicationConfig {
pub fn new() -> Self {
2 years ago
let mut res = Self::defaut();
let mut f = match File::open(CLI.cfg.clone()) {
Ok(f) => f,
2 years ago
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
res._pool = Some(res.connect());
return res;
}
Err(e) => panic!("{}", e),
};
File::open(CLI.cfg.clone()).unwrap();
let mut yml_data = String::new();
f.read_to_string(&mut yml_data).unwrap();
//读取配置
2 years ago
res = serde_yaml::from_str(&yml_data).expect("load config file fail");
if res.debug {
println!("load config:{:?}", res);
println!("///////////////////// Start On Debug Mode ////////////////////////////");
} else {
println!("release_mode is enable!")
}
2 years ago
res._pool = Some(res.connect());
res
}
pub fn defaut() -> Self {
Self {
2 years ago
uuid: "FR9P5t8debxc11aFF".to_string(),
key: "AMpjwQHwVjGsb1WC4WG6".to_string(),
2 years ago
debug: true,
server_url: "127.0.0.1:4001".to_string(),
2 years ago
media_path: "/Users/veypi/test/media/".to_string(),
db_url: "localhost:3306".to_string(),
2 years ago
db_user: "root".to_string(),
db_pass: "123456".to_string(),
db_name: "test".to_string(),
log_dir: None,
log_temp_size: None,
log_pack_compress: None,
log_level: None,
jwt_secret: None,
2 years ago
_pool: None,
2 years ago
}
}
pub fn save(&self) {}
2 years ago
pub fn db(&self) -> &sqlx::MySqlPool {
match &self._pool {
Some(d) => d,
None => panic!("failed"),
}
2 years ago
}
2 years ago
fn connect(&self) -> Pool<sqlx::MySql> {
2 years ago
let url = format!(
"mysql://{}:{}@{}/{}",
self.db_user, self.db_pass, self.db_url, self.db_name
);
2 years ago
let p = MySqlPoolOptions::new()
.max_connections(5)
.connect_lazy(&url)
.unwrap();
p
2 years ago
}
}
struct FormatTime;
impl tracing_subscriber::fmt::time::FormatTime for FormatTime {
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
2 years ago
let d = chrono::Local::now();
w.write_str(&d.format("%Y-%m-%d %H:%M:%S").to_string())
2 years ago
}
}
pub fn init_log() {
tracing_subscriber::fmt()
.with_line_number(true)
.with_timer(FormatTime {})
.init();
2 years ago
}