From 46926bf468b5eebe5de8450685df504b18d1f70b Mon Sep 17 00:00:00 2001 From: glyph Date: Tue, 1 Feb 2022 16:07:19 +0200 Subject: [PATCH] add config writer method and required error variants --- peach-lib/src/error.rs | 19 +++++++++++++++---- peach-lib/src/sbot.rs | 20 ++++++++++++++++++-- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/peach-lib/src/error.rs b/peach-lib/src/error.rs index 3e7dff4..ac4ef97 100644 --- a/peach-lib/src/error.rs +++ b/peach-lib/src/error.rs @@ -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 for PeachError { impl From for PeachError { fn from(err: toml::de::Error) -> PeachError { - PeachError::Toml(err) + PeachError::TomlDeser(err) + } +} + +impl From for PeachError { + fn from(err: toml::ser::Error) -> PeachError { + PeachError::TomlSer(err) } } diff --git a/peach-lib/src/sbot.rs b/peach-lib/src/sbot.rs index 2a2e5d5..e9b9081 100644 --- a/peach-lib/src/sbot.rs +++ b/peach-lib/src/sbot.rs @@ -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(()) + } }