chiark / gitweb /
Made auth file handling fallible.
authorSimon Tatham <anakin@pobox.com>
Sat, 23 Dec 2023 12:29:03 +0000 (12:29 +0000)
committerSimon Tatham <anakin@pobox.com>
Sat, 23 Dec 2023 12:29:03 +0000 (12:29 +0000)
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
src/lib.rs
src/main.rs

index 18e7406f590b6f35ed6cc8042d50d397646ce6f9..18baae745195b5cd762108687e6fe83a54b2bebd 100644 (file)
@@ -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<Self, OurError> {
+        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)
     }
 }
index 65a863493f4438f559b4228b1703ca7681795a55..bf2f4571a110ec308af7b871800b572d85e55c73 100644 (file)
@@ -1,2 +1,7 @@
 pub mod types;
 pub mod auth;
+
+#[derive(Debug)]
+pub enum OurError {
+    Fatal(String),
+}
index f26d7007b01c8e4dff95b6d4b7cd53e28101022d..04f89adc9664f2efb7ea692e49cb82df966ebbec 100644 (file)
@@ -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(())
 }