Switch to storing a path to the config file instead of a path to the root directory.

This commit is contained in:
Tom Alexander 2023-10-20 18:45:24 -04:00
parent 4314937d26
commit 273734c9ff
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
1 changed files with 22 additions and 25 deletions

View File

@ -8,43 +8,40 @@ use super::raw::RawConfig;
/// This is the config struct used by most of the code, which is an interpreted version of the RawConfig struct which is the raw disk-representation of the config.
pub(crate) struct Config {
raw: RawConfig,
root_dir: PathBuf,
config_path: PathBuf,
}
impl Config {
pub(crate) fn new<P: Into<PathBuf>>(root_dir: P) -> Result<Config, Box<dyn std::error::Error>> {
Ok(Config {
raw: RawConfig::default(),
root_dir: root_dir.into(),
})
}
pub(crate) async fn load_from_file<P: AsRef<Path>>(
path: P,
) -> Result<Config, Box<dyn std::error::Error>> {
async fn inner(path: &Path) -> Result<Config, Box<dyn std::error::Error>> {
let contents = tokio::fs::read_to_string(path).await?;
let parsed_contents: RawConfig = toml::from_str(contents.as_str())?;
let root_directory = path
.parent()
.expect("Writer config must exist inside a directory.");
pub(crate) fn new<P: AsRef<Path>>(root_dir: P) -> Result<Config, Box<dyn std::error::Error>> {
fn inner(root_dir: &Path) -> Result<Config, Box<dyn std::error::Error>> {
let file_path = root_dir.join("writer.toml");
Ok(Config {
raw: parsed_contents,
root_dir: root_directory.to_owned(),
raw: RawConfig::default(),
config_path: file_path,
})
}
inner(path.as_ref()).await
inner(root_dir.as_ref())
}
pub(crate) async fn load_from_file<P: Into<PathBuf>>(
path: P,
) -> Result<Config, Box<dyn std::error::Error>> {
async fn inner(path: PathBuf) -> Result<Config, Box<dyn std::error::Error>> {
let contents = tokio::fs::read_to_string(&path).await?;
let parsed_contents: RawConfig = toml::from_str(contents.as_str())?;
Ok(Config {
raw: parsed_contents,
config_path: path,
})
}
inner(path.into()).await
}
pub(crate) async fn write_to_disk(&self) -> Result<(), Box<dyn std::error::Error>> {
let mut config_file = File::create(self.get_path_to_config_file()).await?;
let mut config_file = File::create(&self.config_path).await?;
config_file
.write_all(toml::to_string(&self.raw)?.as_bytes())
.await?;
Ok(())
}
pub(crate) fn get_path_to_config_file(&self) -> PathBuf {
self.root_dir.join("writer.toml")
}
}