use anyhow::Result;
use serde::Deserialize;
use std::env;
use std::fs::File;
use std::path::Path;
const DEFAULT_CONFIG_YAML: &str = include_str!("../config.yml");
#[allow(dead_code)]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct MirrorYamlConfig {
#[serde(default)]
pub npm_registry: String,
#[serde(default)]
pub pypi_index_url: String,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Clone)]
pub struct AppConfig {
pub server: ServerConfig,
pub log: LogConfig,
#[serde(default)]
pub mirror: MirrorYamlConfig,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Clone)]
pub struct ServerConfig {
pub port: u16,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Clone)]
pub struct LogConfig {
pub level: String,
pub path: String,
#[serde(default = "default_retain_days")]
pub retain_days: u32,
}
fn default_retain_days() -> u32 {
5
}
#[allow(dead_code)]
impl AppConfig {
pub fn load_config() -> Result<Self> {
let mut config = match (
File::open("/app/config.yml"),
File::open("config.yml"),
env::var("BOT_SERVER_CONFIG"),
) {
(Ok(file), _, _) => serde_yaml::from_reader(file),
(_, Ok(file), _) => serde_yaml::from_reader(file),
(_, _, Ok(file_path)) => serde_yaml::from_reader(File::open(file_path)?),
_ => {
serde_yaml::from_str::<AppConfig>(DEFAULT_CONFIG_YAML)
}
}?;
if let Ok(port) = env::var("MCP_PROXY_PORT")
&& let Ok(port_num) = port.parse::<u16>()
{
config.server.port = port_num;
}
if let Ok(log_dir) = env::var("MCP_PROXY_LOG_DIR") {
config.log.path = log_dir;
}
if let Ok(log_level) = env::var("MCP_PROXY_LOG_LEVEL") {
config.log.level = log_level;
}
Ok(config)
}
pub fn log_path_init(&self) -> Result<()> {
let log_path = &self.log.path;
if let Some(parent) = Path::new(log_path).parent()
&& !parent.exists()
{
std::fs::create_dir_all(parent)?;
}
Ok(())
}
}