Skip to content

Commit

Permalink
src: settings: Create settings parent dirs before trying to save sett…
Browse files Browse the repository at this point in the history
…ings files
  • Loading branch information
joaoantoniocardoso committed Nov 20, 2023
1 parent c31dd3d commit f266d01
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/settings/manager.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Error, Result};
use anyhow::{anyhow, Error, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::io::prelude::*;
Expand Down Expand Up @@ -86,6 +86,10 @@ impl Manager {
config,
};

create_directories(&settings.file_name).unwrap_or_else(|error| {
error!("Failed to create parent directories for {file_name:?}. Reason: {error:#?}");
});

save_settings_to_file(&settings.file_name, &settings.config).unwrap_or_else(|error| {
error!("Failed to save file {file_name:?}. Reason: {error:#?}");
});
Expand Down Expand Up @@ -121,11 +125,22 @@ fn load_settings_from_file(file_name: &str) -> SettingsStruct {
.map_err(Error::msg)
.and_then(|value| serde_json::from_str(&value).map_err(Error::msg))
.unwrap_or_else(|error| {
error!("Failed to load settings file {file_name:?}. Reason: {error}");
warn!("Failed to load settings file {file_name:?}. Reason: {error}");
fallback_settings_with_backup_file(file_name)
})
}

fn create_directories(file_name: &str) -> Result<()> {
let path = Path::new(&file_name);
if let Some(parent) = path.parent() {
if let Err(error) = std::fs::create_dir_all(parent) {
return Err(anyhow!("Error creating directories: {error:#?}"));
}
}

Ok(())
}

fn save_settings_to_file(file_name: &str, content: &SettingsStruct) -> Result<()> {
let json = serde_json::to_string_pretty(content)?;

Expand Down

0 comments on commit f266d01

Please sign in to comment.