From 2f2029b6e63efd0a6466d5d27784270d213564cd Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Sat, 23 Dec 2023 12:29:03 +0000 Subject: [PATCH] Made auth file handling fallible. There are no doubt many ways to do it better, but this is a start - now it will at least print what went wrong. --- src/auth.rs | 29 +++++++++++++++++++++++------ src/lib.rs | 5 +++++ src/main.rs | 6 ++++-- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 18e7406..18baae7 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,4 +1,7 @@ use serde::{Deserialize, Serialize}; +use xdg::BaseDirectories; + +use super::OurError; #[derive(Serialize, Deserialize, Debug)] pub struct AuthConfig { @@ -12,12 +15,26 @@ pub struct AuthConfig { } impl AuthConfig { - pub fn load() -> Self { - let xdg_dirs = xdg::BaseDirectories::with_prefix("mastodonochrome") - .unwrap(); + pub fn load() -> Result { + let xdg_dirs = match BaseDirectories::with_prefix("mastodonochrome") { + Err(e) => Err(OurError::Fatal( + format!("unable to get config directory: {}", e))), + Ok(d) => Ok(d), + }?; + let authfile = xdg_dirs.get_config_file("auth"); - let auth = std::fs::read_to_string(authfile).unwrap(); - let auth: Self = serde_json::from_str(&auth).unwrap(); - auth + let authdata = match std::fs::read_to_string(&authfile) { + Err(e) => Err(OurError::Fatal( + format!("unable to read config file '{}': {}", + authfile.display(), e))), + Ok(d) => Ok(d), + }?; + let auth: Self = match serde_json::from_str(&authdata) { + Err(e) => Err(OurError::Fatal( + format!("unable to parse config file '{}': {}", + authfile.display(), e))), + Ok(d) => Ok(d), + }?; + Ok(auth) } } diff --git a/src/lib.rs b/src/lib.rs index 65a8634..bf2f457 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,7 @@ pub mod types; pub mod auth; + +#[derive(Debug)] +pub enum OurError { + Fatal(String), +} diff --git a/src/main.rs b/src/main.rs index f26d700..04f89ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,8 @@ use mastodonochrome::auth::AuthConfig; use std::io::Read; -fn main() { - let auth = AuthConfig::load(); +fn main() -> Result<(), mastodonochrome::OurError> { + let auth = AuthConfig::load()?; let client = reqwest::blocking::Client::new(); let mut req = client.get(auth.instance_url + "/api/v1/streaming/user") @@ -16,4 +16,6 @@ fn main() { let read = &buf[..sz]; dbg!(read); } + + Ok(()) } -- 2.30.2