add config writer method and required error variants

This commit is contained in:
glyph 2022-02-01 16:07:19 +02:00
parent d801c957bd
commit 46926bf468
2 changed files with 33 additions and 6 deletions

View File

@ -71,7 +71,10 @@ pub enum PeachError {
SerdeJson(serde_json::error::Error),
/// Represents a failure to deserialize TOML.
Toml(toml::de::Error),
TomlDeser(toml::de::Error),
/// Represents a failure to serialize TOML.
TomlSer(toml::ser::Error),
/// Represents a failure to serialize or deserialize YAML.
SerdeYaml(serde_yaml::Error),
@ -118,7 +121,8 @@ impl std::error::Error for PeachError {
PeachError::SerdeJson(_) => None,
PeachError::SerdeYaml(_) => None,
PeachError::SsbAdminIdNotFound { .. } => None,
PeachError::Toml(_) => None,
PeachError::TomlDeser(_) => None,
PeachError::TomlSer(_) => None,
PeachError::Utf8ToStr(_) => None,
PeachError::Utf8ToString(_) => None,
PeachError::Write { ref source, .. } => Some(source),
@ -172,7 +176,8 @@ impl std::fmt::Display for PeachError {
PeachError::SsbAdminIdNotFound { ref id } => {
write!(f, "Config error: SSB admin ID `{}` not found", id)
}
PeachError::Toml(ref err) => err.fmt(f),
PeachError::TomlDeser(ref err) => err.fmt(f),
PeachError::TomlSer(ref err) => err.fmt(f),
PeachError::Utf8ToStr(ref err) => err.fmt(f),
PeachError::Utf8ToString(ref err) => err.fmt(f),
PeachError::Write { ref path, .. } => {
@ -226,7 +231,13 @@ impl From<serde_yaml::Error> for PeachError {
impl From<toml::de::Error> for PeachError {
fn from(err: toml::de::Error) -> PeachError {
PeachError::Toml(err)
PeachError::TomlDeser(err)
}
}
impl From<toml::ser::Error> for PeachError {
fn from(err: toml::ser::Error) -> PeachError {
PeachError::TomlSer(err)
}
}

View File

@ -1,9 +1,8 @@
//! Data types and associated methods for monitoring and configuring go-sbot.
use std::{fs, process::Command, str};
use std::{fs, fs::File, io::Write, process::Command, str};
use serde::{Deserialize, Serialize};
use toml;
use crate::error::PeachError;
@ -149,4 +148,21 @@ impl SbotConfig {
Ok(config)
}
pub fn write(config: SbotConfig) -> Result<(), PeachError> {
// convert the provided `SbotConfig` instance to a string
let config_string = toml::to_string(&config)?;
// determine path of user's home directory
let mut config_path = dirs::home_dir().ok_or(PeachError::HomeDir)?;
config_path.push(".ssb-go/config.toml");
// open config file for writing
let mut file = File::create(config_path)?;
// write the config string to file
write!(file, "{}", config_string)?;
Ok(())
}
}