Skip to main content

configlation/
lib.rs

1mod config;
2
3use anyhow::Context;
4use serde::{Deserialize, Serialize};
5use std::{
6    fs::{self, OpenOptions},
7    io::Write,
8    os::unix::fs::OpenOptionsExt,
9    path::Path,
10};
11
12pub use config::{Config, Contents, Input, InputKind, Output};
13
14/// # Errors
15///
16/// Returns an error if reading the file fails or the contents fail to
17/// deserialize into the type.
18pub fn read_toml<T: for<'a> Deserialize<'a>>(
19    path: impl AsRef<Path>,
20) -> anyhow::Result<T> {
21    toml::from_str(
22        &fs::read_to_string(&path)
23            .context(format!("reading file: {:?}", path.as_ref()))?,
24    )
25    .context(format!("parsing config file: {:?}", path.as_ref()))
26}
27
28/// # Errors
29///
30/// Returns an error if the value fails to serialize or writing the file fails.
31pub fn write_toml<T: Serialize>(
32    path: &impl AsRef<Path>,
33    value: &T,
34    mode: u32,
35) -> anyhow::Result<()> {
36    let mut f = OpenOptions::new().write(true).mode(mode).open(path)?;
37    f.write_all(toml::to_string_pretty(value)?.as_bytes())
38        .context(format!("writing file: {:?}", path.as_ref()))?;
39
40    Ok(())
41}