add configfile stuff

This commit is contained in:
Joe Ardent 2024-02-03 17:09:18 -08:00
parent efec2e670f
commit a46a2e8847
6 changed files with 33 additions and 10 deletions

2
.env
View file

@ -1 +1 @@
DATABASE_URL=sqlite://${HOME}/.what2watch.db
DATABASE_URL=sqlite://${HOME}/.local/share/what2watch/what2watch.db

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
/target
/libjulid.so
ww-style
*.db

10
Cargo.lock generated
View file

@ -635,6 +635,15 @@ dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs"
version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.4.1"
@ -2877,6 +2886,7 @@ dependencies = [
"chrono",
"clap",
"confy",
"dirs",
"http 1.0.0",
"julid-rs",
"justerror",

View file

@ -19,6 +19,7 @@ axum-macros = "0.4"
chrono = { version = "0.4", default-features = false, features = ["std", "clock"] }
clap = { version = "4", features = ["derive", "env", "unicode", "suggestions", "usage"] }
confy = "0.6"
dirs = "5"
http = "1"
julid-rs = "1"
justerror = "1"

View file

@ -1,33 +1,42 @@
use std::ffi::OsString;
use serde::{Deserialize, Serialize};
pub const APP_NAME: &str = "what2watch";
const CONFIG_NAME: Option<&str> = Some("config");
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Config {
pub base_url: String,
pub db_file: OsString,
pub db_file: String,
}
impl Default for Config {
fn default() -> Self {
let mut datadir = dirs::data_dir().unwrap();
datadir.push(APP_NAME);
datadir.push("what2watch.db");
Self {
base_url: "http://localhost:3000".into(),
db_file: "what2watch.db".into(),
db_file: datadir.as_os_str().to_string_lossy().to_string(),
}
}
}
impl Config {
pub fn get() -> Self {
let config: Config = confy::load(APP_NAME, None).unwrap_or_else(|e| {
let config: Config = confy::load(APP_NAME, CONFIG_NAME).unwrap_or_else(|e| {
tracing::debug!("Could not load {APP_NAME} config, got error {e}");
Default::default()
});
confy::store(APP_NAME, None, config.clone()).unwrap_or_else(|e| {
confy::store(APP_NAME, CONFIG_NAME, config.clone()).unwrap_or_else(|e| {
tracing::debug!("Could not store {APP_NAME} config, got error {e}");
});
tracing::info!("Loading config from {}", cpath());
config
}
}
fn cpath() -> String {
confy::get_configuration_file_path(APP_NAME, CONFIG_NAME)
.map(|p| p.as_os_str().to_str().unwrap().to_string())
.expect("couldn't get the path to the configuration file")
}

View file

@ -15,9 +15,11 @@ pub fn get_db_pool() -> SqlitePool {
std::env::var("DATABASE_FILE").unwrap_or_else(|_| {
#[cfg(not(test))]
{
let home =
std::env::var("HOME").expect("Could not determine $HOME for finding db file");
format!("{home}/.what2watch.db")
let f = crate::conf::Config::get().db_file;
let p = std::path::Path::new(&f);
let p = p.parent().unwrap();
std::fs::create_dir_all(p).expect("couldn't create data dir");
f
}
#[cfg(test)]
{