libcnb_common/
toml_file.rs

1use serde::{Serialize, de::DeserializeOwned};
2use std::{fs, path::Path};
3
4/// An error that occurred during reading or writing a TOML file.
5#[derive(thiserror::Error, Debug)]
6pub enum TomlFileError {
7    #[error("I/O error while reading/writing TOML file: {0}")]
8    IoError(#[from] std::io::Error),
9
10    #[error("TOML deserialization error while reading TOML file: {0}")]
11    TomlDeserializationError(#[from] toml::de::Error),
12
13    #[error("TOML serialization error while writing TOML file: {0}")]
14    TomlSerializationError(#[from] toml::ser::Error),
15}
16
17/// Serializes the given value as TOML and writes it to the given file path.
18///
19/// # Errors
20///
21/// Will return `Err` if the file couldn't be written or the value couldn't be serialized as a TOML string.
22pub fn write_toml_file(
23    value: &impl Serialize,
24    path: impl AsRef<Path>,
25) -> Result<(), TomlFileError> {
26    fs::write(path, toml::to_string(value)?)?;
27
28    Ok(())
29}
30
31/// Reads the file at the given path and parses it as `A`.
32///
33/// # Errors
34///
35/// Will return `Err` if the file couldn't be read or its contents couldn't be deserialized.
36pub fn read_toml_file<A: DeserializeOwned>(path: impl AsRef<Path>) -> Result<A, TomlFileError> {
37    let contents = fs::read_to_string(path)?;
38    Ok(toml::from_str(&contents)?)
39}