diff --git a/oab/src/cfg.rs b/oab/src/cfg.rs index 96a1723..7c7bd79 100644 --- a/oab/src/cfg.rs +++ b/oab/src/cfg.rs @@ -14,95 +14,13 @@ use std::{ time::Duration, }; -use clap::{Args, Parser, Subcommand}; use sea_orm::{ConnectOptions, Database, DatabaseConnection}; use serde::{Deserialize, Serialize}; use sqlx::{mysql::MySqlPoolOptions, Pool}; -use tracing::{info, Level}; +use tracing::Level; use crate::Result; -// lazy_static! { -// pub static ref CLI: AppCli = AppCli::new(); -// } -// use lazy_static::lazy_static; - -// 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/oa/oab.yml"), value_hint = clap::ValueHint::DirPath)] - cfg: String, - #[clap(subcommand)] - pub command: Option, -} - -#[derive(Debug, Subcommand)] -pub enum Clis { - Init, - Install, - Uninstall, - Start, - Stop, - Web, - Dump, - Cfg(CfgOpt), -} - -#[derive(Debug, Args)] -#[clap(args_conflicts_with_subcommands = true)] -pub struct CfgOpt { - command: Option, -} - -impl AppCli { - pub fn new() -> Self { - AppCli::parse() - } - pub fn handle_service(&self, data: AppState) -> Result { - let label: service_manager::ServiceLabel = "v.oa".parse().unwrap(); - - // Get generic service by detecting what is available on the platform - let manager = ::native() - .expect("Failed to detect management platform"); - - if let Some(c) = &self.command { - match c { - Clis::Install => { - let p = std::env::current_exe()?; - info!("deploy {}", p.to_str().unwrap()); - manager.install(service_manager::ServiceInstallCtx { - label: label.clone(), - program: p, - args: vec![], - contents: None, // Optional String for system-specific service content. - })? - } - Clis::Uninstall => manager.uninstall(service_manager::ServiceUninstallCtx { - label: label.clone(), - })?, - Clis::Start => manager.start(service_manager::ServiceStartCtx { - label: label.clone(), - })?, - Clis::Stop => manager.stop(service_manager::ServiceStopCtx { - label: label.clone(), - })?, - Clis::Dump => { - let res = serde_yaml::to_string(&data)?; - println!("{}", res); - } - _ => return Ok(false), - } - return Ok(true); - }; - Ok(false) - } -} - #[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] pub struct ApplicationConfig { #[serde(skip)] @@ -130,6 +48,7 @@ pub struct AppState { pub db_pass: String, pub db_name: String, pub log_dir: Option, + pub auto_task: bool, pub fs_root: String, pub ts_url: String, pub nats_url: String, @@ -149,9 +68,9 @@ pub struct AppState { } impl AppState { - pub fn new(cli: &AppCli) -> Self { + pub fn new(cli_path: &str) -> Self { let mut res = Self::defaut(); - let mut f = match File::open(cli.cfg.clone()) { + let mut f = match File::open(cli_path) { Ok(f) => f, Err(ref e) if e.kind() == io::ErrorKind::NotFound => { // res.connect_sqlx().unwrap(); @@ -159,7 +78,7 @@ impl AppState { } Err(e) => panic!("{}", e), }; - File::open(cli.cfg.clone()).unwrap(); + File::open(cli_path).unwrap(); let mut yml_data = String::new(); f.read_to_string(&mut yml_data).unwrap(); //读取配置 @@ -177,6 +96,7 @@ impl AppState { db_pass: "123456".to_string(), db_name: "oneauth".to_string(), log_dir: None, + auto_task: true, media_path: "/Users/veypi/test/media".to_string(), fs_root: "/Users/veypi/test/media".to_string(), log_level: None, diff --git a/oab/src/cli.rs b/oab/src/cli.rs index 26e66fd..058cd33 100644 --- a/oab/src/cli.rs +++ b/oab/src/cli.rs @@ -5,52 +5,81 @@ // Distributed under terms of the Apache license. // +use crate::cfg::AppState; +use crate::Result; use clap::{Args, Parser, Subcommand}; - -use lazy_static::lazy_static; - -lazy_static! { - pub static ref CLI: cli = cli::new(); -} +use tracing::info; #[derive(Debug, Parser)] #[clap(name = "oab")] #[clap(about = "oab", long_about = None)] -struct cli { +pub struct AppCli { + #[clap(short = 'c', value_name = "cfg",default_value_t = String::from("~/.config/oa/oab.yml"), value_hint = clap::ValueHint::DirPath)] + pub cfg: String, + #[clap(short = 'n', value_name = "name",default_value_t = String::from("v.oab"))] + pub name: String, #[clap(subcommand)] - command: Commands, + pub command: Option, } #[derive(Debug, Subcommand)] -enum Commands { - /// Clones repos - #[clap(arg_required_else_help = true)] - Clone { - /// The remote to clone - #[clap(value_parser)] - remote: String, - }, - /// pushes things - #[clap(arg_required_else_help = true)] - Push { - /// The remote to target - #[clap(value_parser)] - remote: String, - }, - /// adds things - #[clap(arg_required_else_help = true)] - Add { - /// Stuff to add - #[clap(required = true, value_parser)] - path: Vec, - }, - Stash(Stash), - #[clap(external_subcommand)] - External(Vec), +pub enum Clis { + Init, + Install, + Uninstall, + Start, + Stop, + Web, + Dump, + Cfg(CfgOpt), +} + +#[derive(Debug, Args)] +#[clap(args_conflicts_with_subcommands = true)] +pub struct CfgOpt { + command: Option, } -impl cli { - fn new() -> Self { - cli::parse() +impl AppCli { + pub fn new() -> Self { + AppCli::parse() + } + pub fn handle_service(&self, data: AppState) -> Result { + let label: service_manager::ServiceLabel = self.name.parse().unwrap(); + + // Get generic service by detecting what is available on the platform + let manager = ::native() + .expect("Failed to detect management platform"); + + if let Some(c) = &self.command { + match c { + Clis::Install => { + let p = std::env::current_exe()?; + info!("deploy {} -c {}", p.to_str().unwrap(), self.cfg); + manager.install(service_manager::ServiceInstallCtx { + label: label.clone(), + program: p, + args: vec![format!("-c {}", self.cfg).into()], + contents: None, // Optional String for system-specific service content. + })? + } + Clis::Uninstall => manager.uninstall(service_manager::ServiceUninstallCtx { + label: label.clone(), + })?, + Clis::Start => manager.start(service_manager::ServiceStartCtx { + label: label.clone(), + })?, + Clis::Stop => manager.stop(service_manager::ServiceStopCtx { + label: label.clone(), + })?, + Clis::Dump => { + let res = serde_yaml::to_string(&data)?; + println!("{}", res); + } + _ => return Ok(false), + } + return Ok(true); + }; + Ok(false) } } diff --git a/oab/src/lib.rs b/oab/src/lib.rs index a4e106c..93a2931 100644 --- a/oab/src/lib.rs +++ b/oab/src/lib.rs @@ -7,9 +7,11 @@ pub mod api; mod cfg; +mod cli; pub mod fs; pub mod libs; pub mod models; mod result; -pub use cfg::{init_log, AppCli, AppState, ApplicationConfig, Clis, InfoOpt}; +pub use cfg::{init_log, AppState, ApplicationConfig, InfoOpt}; +pub use cli::{AppCli, Clis}; pub use result::{Error, Result}; diff --git a/oab/src/main.rs b/oab/src/main.rs index d2e506b..99d7059 100644 --- a/oab/src/main.rs +++ b/oab/src/main.rs @@ -22,14 +22,13 @@ use tracing::{error, info, warn}; #[tokio::main] async fn main() -> Result<()> { let cli = AppCli::new(); - let mut data = AppState::new(&cli); + let mut data = AppState::new(&cli.cfg); if data.debug { std::env::set_var("RUST_LOG", "debug"); std::env::set_var("RUST_BACKTRACE", "full"); } let _log = init_log(&data); if cli.handle_service(data.clone())? { - info!("2"); return Ok(()); } if let Some(c) = &cli.command { @@ -44,13 +43,14 @@ async fn main() -> Result<()> { }; data.connect().await?; data.connect_sqlx()?; + if data.auto_task { + libs::task::start_stats_info(data.ts_url.clone()); + } web(data).await?; Ok(()) } async fn web(data: AppState) -> Result<()> { - // libs::task::start_nats_online(client.clone()); - libs::task::start_stats_info(data.ts_url.clone()); let url = data.server_url.clone(); let serv = HttpServer::new(move || { let logger = middleware::Logger::default();