.env pwd configuration to ini xdg configuration

This commit is contained in:
Reid 2024-08-27 17:12:01 -07:00
parent 6899d676aa
commit aa0f2201e4
Signed by: reidlab
GPG key ID: DAF5EAF6665839FD
8 changed files with 229 additions and 66 deletions

View file

@ -1,19 +1,55 @@
use envconfig::Envconfig;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::fs;
use std::fs::{create_dir_all, OpenOptions};
use std::io::Write;
use std::process;
use tracing::info;
#[derive(Envconfig)]
#[derive(Deserialize)]
pub struct Config {
#[envconfig(from = "PLAYER_BUS")]
pub player_bus: Option<String>,
#[envconfig(from = "USERNAME")]
pub username: String,
#[envconfig(from = "PASSWORD")]
pub password: String,
#[envconfig(from = "API_KEY")]
pub api_key: String,
#[envconfig(from = "API_SECRET")]
pub api_secret: String
}
pub fn load_config() -> Result<Config> {
let path = dirs::config_dir()
.context("failed to get config directory")?
.join("lastfmpris")
.join("config.ini");
// create file if it doesnt exist and exit
if !path.exists() {
info!("configuration file doesn't exist, creating boilerplate");
// create underline paths and files
if let Some(parent) = path.parent() {
create_dir_all(parent)
.context("failed to create config file folder(s)")?;
}
let mut file = OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.context("failed to create config file")?;
// write into the config file with the example configuration
// we put inside the base working directory for the project
file.write_all(include_str!("../config.example.ini").as_bytes())
.context("failed to write boilerplate config")?;
info!("configuration boilerplate generation completed: see file: {}", path.display());
// success, exit
process::exit(0)
}
let content = fs::read_to_string(path)
.context("failed to read config content")?;
let config: Config = serde_ini::from_str(&content)
.context("failed to deserialize ini into a readable format")?;
Ok(config)
}

View file

@ -6,14 +6,11 @@ mod main_loop;
mod player;
mod track;
use crate::config::Config;
use crate::lastfm::get_scrobbler;
use anyhow::{Context, Result};
use envconfig::Envconfig;
use tracing::{debug, Level};
fn main() -> Result<()> {
dotenvy::dotenv()?;
tracing_subscriber::fmt()
.with_max_level(if cfg!(debug_assertions) { Level::DEBUG } else { Level::INFO })
.init();
@ -24,8 +21,8 @@ fn main() -> Result<()> {
env!("CARGO_PKG_DESCRIPTION")
);
let config = Config::init_from_env()
.context("failed to initiate configuration from .env")?;
let config = config::load_config()
.context("failed to initiate configuration object!")?;
let scrobbler = get_scrobbler(&config)
.context("failed to create scrobbler")?;