dango_core/music_controller/
config.rs1use std::path::PathBuf;
2use std::fs::read_to_string;
3use std::fs;
4
5use serde::{Deserialize, Serialize};
6
7use crate::music_tracker::music_tracker::LastFM;
8
9#[derive(Serialize, Deserialize)]
10pub struct Config {
11 pub db_path: Box<PathBuf>,
12 pub lastfm: Option<LastFM>,
13}
14
15impl Config {
16 pub fn new(config_file: &PathBuf) -> std::io::Result<Config> {
18 let path = PathBuf::from("./music_database.db3");
19
20 let config = Config {
21 db_path: Box::new(path),
22 lastfm: None,
23 };
24 config.save(config_file)?;
25
26 Ok(config)
27 }
28
29 pub fn from(config_file: &PathBuf) -> std::result::Result<Config, toml::de::Error> {
31 return toml::from_str(&read_to_string(config_file)
32 .expect("Failed to initalize music config: File not found!"));
33 }
34
35 pub fn save(&self, config_file: &PathBuf) -> std::io::Result<()> {
38 let toml = toml::to_string_pretty(self).unwrap();
39
40 let mut temp_file = config_file.clone();
41 temp_file.set_extension("tomltemp");
42
43 fs::write(&temp_file, toml)?;
44
45 match fs::metadata(config_file) {
47 Ok(_) => fs::remove_file(config_file)?,
48 Err(_) => {},
49 }
50
51 fs::rename(temp_file, config_file)?;
52 Ok(())
53 }
54}