From 3539ceb20f5383a332a8ad1fcab816cf083f277e Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sun, 18 Aug 2019 23:45:33 -0400 Subject: better error handling --- src/paths.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 4 deletions(-) (limited to 'src/paths.rs') diff --git a/src/paths.rs b/src/paths.rs index 31c07d0..f53bef5 100644 --- a/src/paths.rs +++ b/src/paths.rs @@ -1,6 +1,56 @@ -pub fn api_key() -> std::path::PathBuf { - directories::ProjectDirs::from("", "", "ynab") - .unwrap() +use snafu::{OptionExt, ResultExt}; +use std::io::Read; + +#[derive(Debug, snafu::Snafu)] +pub enum Error { + #[snafu(display("couldn't find config path for project {}", name))] + FindConfigDir { name: String }, + + #[snafu(display( + "couldn't open file {}: {}", + file.to_string_lossy(), + source + ))] + OpenFile { + file: std::path::PathBuf, + source: std::io::Error, + }, + + #[snafu(display( + "couldn't read file {}: {}", + file.to_string_lossy(), + source + ))] + ReadFile { + file: std::path::PathBuf, + source: std::io::Error, + }, +} + +pub type Result = std::result::Result; + +const PROJECT_NAME: &str = "ynab"; + +pub fn api_key() -> Result { + Ok(directories::ProjectDirs::from("", "", PROJECT_NAME) + .with_context(|| FindConfigDir { + name: PROJECT_NAME.to_string(), + })? .config_dir() - .join("api-key") + .join("api-key")) +} + +pub fn read_api_key() -> Result { + let mut key = String::new(); + let key_file = api_key()?; + std::fs::File::open(key_file.clone()) + .with_context(|| OpenFile { + file: key_file.clone(), + })? + .read_to_string(&mut key) + .with_context(|| ReadFile { + file: key_file.clone(), + })?; + let key = key.trim(); + Ok(key.to_string()) } -- cgit v1.2.3-54-g00ecf