Fix crashing without arg default

This commit is contained in:
Garen Tyler 2024-12-05 17:19:00 -07:00
parent e9e35c0dbe
commit fbfb90c3aa
Signed by: garentyler
SSH Key Fingerprint: SHA256:G4ke7blZMdpWPbkescyZ7IQYE4JAtwpI85YoJdq+S7U
4 changed files with 30 additions and 22 deletions

View File

@ -18,7 +18,7 @@ pub static CONFIG: OnceCell<Config> = OnceCell::new();
/// On program startup, Args::load() should be called to initialize it. /// On program startup, Args::load() should be called to initialize it.
pub static ARGS: OnceCell<Args> = OnceCell::new(); pub static ARGS: OnceCell<Args> = OnceCell::new();
const DEFAULT_CONFIG_FILE: &str = "composition.toml"; const DEFAULT_CONFIG_FILE: &str = "composition.toml";
const DEFAULT_LOG_DIR: &str = "logs"; pub const DEFAULT_LOG_DIR: &str = "logs";
/// Helper function to read a file from a `Path` /// Helper function to read a file from a `Path`
/// and return its bytes as a `Vec<u8>`. /// and return its bytes as a `Vec<u8>`.
@ -69,7 +69,11 @@ impl Config {
trace!("GlobalConfig::load()"); trace!("GlobalConfig::load()");
let args = Args::instance(); let args = Args::instance();
let mut config = Config::default(); let mut config = Config::default();
let config_path = Path::new(&args.config_file); let config_path = args
.config_file
.clone()
.unwrap_or(PathBuf::from(DEFAULT_CONFIG_FILE));
let config_path = Path::new(&config_path);
if !config_path.exists() { if !config_path.exists() {
warn!( warn!(
@ -167,9 +171,9 @@ pub enum Subcommand {
/// Arguments will always override the config options specified in `composition.toml` or `Config::default()`. /// Arguments will always override the config options specified in `composition.toml` or `Config::default()`.
#[derive(Debug)] #[derive(Debug)]
pub struct Args { pub struct Args {
config_file: PathBuf, config_file: Option<PathBuf>,
pub log_level: Option<tracing::Level>, pub log_level: Option<tracing::Level>,
pub log_dir: PathBuf, pub log_dir: Option<PathBuf>,
pub subcommand: Subcommand, pub subcommand: Subcommand,
#[cfg(feature = "server")] #[cfg(feature = "server")]
pub server: Option<ServerArgs>, pub server: Option<ServerArgs>,
@ -179,9 +183,9 @@ pub struct Args {
impl Default for Args { impl Default for Args {
fn default() -> Self { fn default() -> Self {
Args { Args {
config_file: PathBuf::from(DEFAULT_CONFIG_FILE), config_file: None,
log_level: None, log_level: None,
log_dir: PathBuf::from(DEFAULT_LOG_DIR), log_dir: None,
subcommand: Subcommand::None, subcommand: Subcommand::None,
#[cfg(feature = "server")] #[cfg(feature = "server")]
server: None, server: None,
@ -229,6 +233,7 @@ impl Args {
.help("Configuration file path") .help("Configuration file path")
.global(true) .global(true)
.value_hint(clap::ValueHint::FilePath) .value_hint(clap::ValueHint::FilePath)
.value_parser(clap::value_parser!(PathBuf))
.default_value(DEFAULT_CONFIG_FILE), .default_value(DEFAULT_CONFIG_FILE),
) )
.arg( .arg(
@ -248,6 +253,7 @@ impl Args {
.global(true) .global(true)
.value_name("dir") .value_name("dir")
.value_hint(clap::ValueHint::DirPath) .value_hint(clap::ValueHint::DirPath)
.value_parser(clap::value_parser!(PathBuf))
.default_value(DEFAULT_LOG_DIR), .default_value(DEFAULT_LOG_DIR),
); );
#[cfg(feature = "server")] #[cfg(feature = "server")]
@ -265,12 +271,8 @@ impl Args {
let mut args = Self::default(); let mut args = Self::default();
let m = Self::command().get_matches(); let m = Self::command().get_matches();
args.config_file = m args.config_file = m.get_one("config-file").cloned();
.get_one::<String>("config-file") args.log_dir = m.get_one("log-dir").cloned();
.map_or(args.config_file, PathBuf::from);
args.log_dir = m
.get_one::<String>("log-dir")
.map_or(args.log_dir, PathBuf::from);
if m.get_flag("verbose") { if m.get_flag("verbose") {
args.log_level = Some(tracing::Level::DEBUG); args.log_level = Some(tracing::Level::DEBUG);

View File

@ -7,9 +7,16 @@ pub fn main() {
.set(std::time::Instant::now()) .set(std::time::Instant::now())
.expect("could not set composition::START_TIME"); .expect("could not set composition::START_TIME");
use composition::config::{Args, DEFAULT_LOG_DIR};
use std::path::{Path, PathBuf};
// Set up logging. // Set up logging.
let file_writer = let log_path = Args::instance()
tracing_appender::rolling::daily(&composition::config::Args::instance().log_dir, "log"); .log_dir
.clone()
.unwrap_or(PathBuf::from(DEFAULT_LOG_DIR));
let log_path = Path::new(&log_path);
let file_writer = tracing_appender::rolling::daily(&log_path, "log");
let (file_writer, _guard) = tracing_appender::non_blocking(file_writer); let (file_writer, _guard) = tracing_appender::non_blocking(file_writer);
tracing_subscriber::registry() tracing_subscriber::registry()

View File

@ -67,6 +67,7 @@ impl ProxyArgs {
.long("port") .long("port")
.help("Proxy listening port") .help("Proxy listening port")
.value_hint(clap::ValueHint::Other) .value_hint(clap::ValueHint::Other)
.value_parser(clap::value_parser!(u16))
.default_value(const_format::formatcp!("{}", DEFAULT_PORT)), .default_value(const_format::formatcp!("{}", DEFAULT_PORT)),
) )
.arg( .arg(
@ -83,6 +84,7 @@ impl ProxyArgs {
.long("upstream-port") .long("upstream-port")
.help("Upstream server port") .help("Upstream server port")
.value_hint(clap::ValueHint::Other) .value_hint(clap::ValueHint::Other)
.value_parser(clap::value_parser!(u16))
.default_value(const_format::formatcp!("{}", DEFAULT_UPSTREAM_PORT)), .default_value(const_format::formatcp!("{}", DEFAULT_UPSTREAM_PORT)),
) )
} }

View File

@ -39,8 +39,8 @@ impl ServerConfig {
} }
pub fn load_args(&mut self) { pub fn load_args(&mut self) {
self.server_icon = ServerArgs::instance() self.server_icon = ServerArgs::instance()
.as_ref()
.map(|s| s.server_icon.clone()) .map(|s| s.server_icon.clone())
.flatten()
.unwrap_or(PathBuf::from(DEFAULT_SERVER_ICON)); .unwrap_or(PathBuf::from(DEFAULT_SERVER_ICON));
self.load_icon(); self.load_icon();
} }
@ -81,13 +81,11 @@ impl ServerConfig {
#[derive(Debug)] #[derive(Debug)]
pub struct ServerArgs { pub struct ServerArgs {
pub server_icon: PathBuf, pub server_icon: Option<PathBuf>,
} }
impl Default for ServerArgs { impl Default for ServerArgs {
fn default() -> Self { fn default() -> Self {
ServerArgs { ServerArgs { server_icon: None }
server_icon: PathBuf::from(DEFAULT_SERVER_ICON),
}
} }
} }
impl ServerArgs { impl ServerArgs {
@ -102,14 +100,13 @@ impl ServerArgs {
.long("server-icon") .long("server-icon")
.help("Server icon file path") .help("Server icon file path")
.value_hint(clap::ValueHint::FilePath) .value_hint(clap::ValueHint::FilePath)
.value_parser(clap::value_parser!(PathBuf))
.default_value(DEFAULT_SERVER_ICON), .default_value(DEFAULT_SERVER_ICON),
) )
} }
pub fn parse(m: clap::ArgMatches) -> Self { pub fn parse(m: clap::ArgMatches) -> Self {
let mut server_args = ServerArgs::default(); let mut server_args = ServerArgs::default();
server_args.server_icon = m server_args.server_icon = m.get_one("server-icon").cloned();
.get_one::<String>("server-icon")
.map_or(server_args.server_icon, PathBuf::from);
server_args server_args
} }
} }