improvement: make config file location configurable via CLI args

This commit is contained in:
rorp 2023-02-06 20:35:08 -08:00 committed by Greg Heartsfield
parent 2e42b1b86e
commit 28b7b83a6e
4 changed files with 26 additions and 10 deletions

View File

@ -20,7 +20,7 @@ pub fn main() -> Result<()> {
let _trace_sub = tracing_subscriber::fmt::try_init();
println!("Nostr-rs-relay Bulk Loader");
// check for a database file, or create one.
let settings = config::Settings::new();
let settings = config::Settings::new(&None);
if !Path::new(&settings.database.data_directory).is_dir() {
info!("Database directory does not exist");
return Err(Error::DatabaseDirError);

View File

@ -10,4 +10,11 @@ pub struct CLIArgs {
required = false,
)]
pub db: Option<String>,
#[arg(
short,
long,
help = "Use the <file name> as the location of the config file",
required = false,
)]
pub config: Option<String>,
}

View File

@ -155,10 +155,10 @@ pub struct Settings {
impl Settings {
#[must_use]
pub fn new() -> Self {
pub fn new(config_file_name: &Option<String>) -> Self {
let default_settings = Self::default();
// attempt to construct settings with file
let from_file = Self::new_from_default(&default_settings);
let from_file = Self::new_from_default(&default_settings, config_file_name);
match from_file {
Ok(f) => f,
Err(e) => {
@ -168,13 +168,19 @@ impl Settings {
}
}
fn new_from_default(default: &Settings) -> Result<Self, ConfigError> {
fn new_from_default(default: &Settings, config_file_name: &Option<String>) -> Result<Self, ConfigError> {
let default_config_file_name = "config.toml".to_string();
let config: &String = match config_file_name {
Some(value) => value,
None => &default_config_file_name
};
let builder = Config::builder();
let config: Config = builder
// use defaults
.add_source(Config::try_from(default)?)
// override with file contents
.add_source(File::with_name("config.toml"))
.add_source(File::with_name(config))
.build()?;
let mut settings: Settings = config.try_deserialize()?;
// ensure connection pool size is logical

View File

@ -11,9 +11,14 @@ use console_subscriber::ConsoleLayer;
/// Start running a Nostr relay server.
fn main() {
// configure settings from config.toml
// replace default settings with those read from config.toml
let mut settings = config::Settings::new();
let args = CLIArgs::parse();
// get config file name from args
let config_file_arg = args.config;
// configure settings from the config file (defaults to config.toml)
// replace default settings with those read from the config file
let mut settings = config::Settings::new(&config_file_arg);
// setup tracing
if settings.diagnostics.tracing {
@ -25,8 +30,6 @@ fn main() {
}
info!("Starting up from main");
let args = CLIArgs::parse();
// get database directory from args
let db_dir_arg = args.db;