better panic, rename ImgurHandle -> ImgurClient

This commit is contained in:
MedzikUser 2022-01-27 14:14:46 +01:00
parent ecace5aa46
commit 7455932107
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
17 changed files with 59 additions and 90 deletions

View File

@ -10,8 +10,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased] ## [Unreleased]
- SimpleLogger init error handling - SimpleLogger init error handling
### CLI
- better panic
- panic instead of send log error
### Library ### Library
- The returned error in the Result is from now on anyhow::Error and not String. - The returned error in the Result is from now on anyhow::Error and not String.
- Do not exit program if send_api_request error
- rename ImgurHandle -> ImgurClient
## [0.2.0] - 2022-01-23 ## [0.2.0] - 2022-01-23
### Added ### Added

View File

@ -29,6 +29,7 @@ base64 = "0.13.0"
notify-rust = "4.5.5" notify-rust = "4.5.5"
clap_complete = "3.0.5" clap_complete = "3.0.5"
anyhow = "1.0.53" anyhow = "1.0.53"
better-panic = "0.3.0"
[dependencies.clap] [dependencies.clap]
version = "3.0.13" version = "3.0.13"

View File

@ -9,20 +9,20 @@ macro_rules! api_url (
pub(crate) use api_url; pub(crate) use api_url;
pub struct ImgurHandle { pub struct ImgurClient {
pub client_id: String, pub client_id: String,
pub client: Client, pub client: Client,
} }
impl fmt::Debug for ImgurHandle { impl fmt::Debug for ImgurClient {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ImgurClient - client_id: {}", self.client_id) write!(f, "ImgurClient - client_id: {}", self.client_id)
} }
} }
impl ImgurHandle { impl ImgurClient {
pub fn new(client_id: String) -> Self { pub fn new(client_id: String) -> Self {
let client = Client::new(); let client = Client::new();
ImgurHandle { client_id, client } ImgurClient { client_id, client }
} }
} }

View File

@ -1,4 +1,4 @@
use crate::api::configuration::{api_url, ImgurHandle}; use crate::api::configuration::{api_url, ImgurClient};
use super::send_api_request; use super::send_api_request;
@ -6,7 +6,7 @@ use anyhow::Error as anyhow_err;
use reqwest::Method; use reqwest::Method;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
pub async fn delete_image(c: ImgurHandle, delete_hash: String) -> Result<String, anyhow_err> { pub async fn delete_image(c: ImgurClient, delete_hash: String) -> Result<String, anyhow_err> {
let uri = api_url!(format!("image/{delete_hash}")); let uri = api_url!(format!("image/{delete_hash}"));
let res = send_api_request(&c, Method::DELETE, uri, None).await?; let res = send_api_request(&c, Method::DELETE, uri, None).await?;

View File

@ -1,4 +1,4 @@
use crate::api::configuration::{api_url, ImgurHandle}; use crate::api::configuration::{api_url, ImgurClient};
use crate::api::ImageInfo; use crate::api::ImageInfo;
use super::send_api_request; use super::send_api_request;
@ -7,7 +7,7 @@ use anyhow::Error as anyhow_err;
use reqwest::Method; use reqwest::Method;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
pub async fn get_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, anyhow_err> { pub async fn get_image(c: ImgurClient, image: &str) -> Result<ImageInfo, anyhow_err> {
let uri = api_url!(format!("image/{image}")); let uri = api_url!(format!("image/{image}"));
let res = send_api_request(&c, Method::GET, uri, None).await?; let res = send_api_request(&c, Method::GET, uri, None).await?;

View File

@ -7,6 +7,6 @@ pub mod get_image;
pub mod rate_limit; pub mod rate_limit;
pub mod upload_image; pub mod upload_image;
pub use configuration::ImgurHandle; pub use configuration::ImgurClient;
pub use image_type::*; pub use image_type::*;
pub use send_request::send_api_request; pub use send_request::send_api_request;

View File

@ -1,4 +1,4 @@
use crate::api::configuration::{api_url, ImgurHandle}; use crate::api::configuration::{api_url, ImgurClient};
use super::send_api_request; use super::send_api_request;
@ -28,7 +28,7 @@ pub struct RateLimitData {
pub client_remaining: i32, pub client_remaining: i32,
} }
pub async fn rate_limit(c: ImgurHandle) -> Result<RateLimitInfo, anyhow_err> { pub async fn rate_limit(c: ImgurClient) -> Result<RateLimitInfo, anyhow_err> {
let uri = api_url!("credits"); let uri = api_url!("credits");
let res = send_api_request(&c, Method::GET, uri, None).await?; let res = send_api_request(&c, Method::GET, uri, None).await?;

View File

@ -1,11 +1,11 @@
use super::ImgurHandle; use super::ImgurClient;
use anyhow::Error; use anyhow::Error;
use reqwest::Method; use reqwest::Method;
use std::collections::HashMap; use std::collections::HashMap;
pub async fn send_api_request( pub async fn send_api_request(
config: &ImgurHandle, config: &ImgurClient,
method: Method, method: Method,
uri: String, uri: String,
form: Option<HashMap<&str, String>>, form: Option<HashMap<&str, String>>,

View File

@ -1,5 +1,5 @@
use crate::api::{ use crate::api::{
configuration::{api_url, ImgurHandle}, configuration::{api_url, ImgurClient},
ImageInfo, ImageInfo,
}; };
@ -12,7 +12,7 @@ use std::{
io::{Error, ErrorKind}, io::{Error, ErrorKind},
}; };
pub async fn upload_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, anyhow_err> { pub async fn upload_image(c: ImgurClient, image: &str) -> Result<ImageInfo, anyhow_err> {
let mut form = HashMap::new(); let mut form = HashMap::new();
form.insert("image", image.to_string()); form.insert("image", image.to_string());

View File

@ -1,17 +1,11 @@
use imgurs::api::{rate_limit::rate_limit, ImgurHandle}; use imgurs::api::{rate_limit::rate_limit, ImgurClient};
use chrono::{prelude::DateTime, Utc}; use chrono::{prelude::DateTime, Utc};
use log::{error, info}; use log::info;
use std::{ use std::time::{Duration, UNIX_EPOCH};
process::exit,
time::{Duration, UNIX_EPOCH},
};
pub async fn credits(client: ImgurHandle) { pub async fn credits(client: ImgurClient) {
let i = rate_limit(client).await.unwrap_or_else(|e| { let i = rate_limit(client).await.expect("send api request");
error!("{e}");
exit(1);
});
let d = UNIX_EPOCH + Duration::from_secs(i.data.user_reset.try_into().unwrap()); let d = UNIX_EPOCH + Duration::from_secs(i.data.user_reset.try_into().unwrap());
let datetime = DateTime::<Utc>::from(d); let datetime = DateTime::<Utc>::from(d);

View File

@ -1,13 +1,10 @@
use imgurs::api::{configuration::ImgurHandle, delete_image::delete_image as del_img}; use imgurs::api::{delete_image::delete_image as del_img, ImgurClient};
use log::{error, info}; use log::info;
use std::process::exit;
pub async fn delete_image(client: ImgurHandle, delete_hash: String) {
let i = del_img(client, delete_hash).await.unwrap_or_else(|e| {
error!("{e}");
exit(1);
});
pub async fn delete_image(client: ImgurClient, delete_hash: String) {
let i = del_img(client, delete_hash)
.await
.expect("send api request");
info!("{i}"); info!("{i}");
} }

View File

@ -1,15 +1,8 @@
use imgurs::api::{configuration::ImgurHandle, get_image::get_image}; use imgurs::api::{get_image::get_image, ImgurClient};
use super::print_image_info; use super::print_image_info;
use log::error; pub async fn image_info(client: ImgurClient, id: &str) {
use std::process::exit; let i = get_image(client, id).await.expect("send api request");
pub async fn image_info(client: ImgurHandle, id: &str) {
let i = get_image(client, id).await.unwrap_or_else(|e| {
error!("{e}");
exit(1);
});
print_image_info(i, false); print_image_info(i, false);
} }

View File

@ -8,12 +8,9 @@ use crate::config::toml::parse;
use imgurs::api::ImageInfo; use imgurs::api::ImageInfo;
use chrono::{prelude::DateTime, Utc}; use chrono::{prelude::DateTime, Utc};
use log::{error, info}; use log::info;
use notify_rust::Notification; use notify_rust::Notification;
use std::{ use std::time::{Duration, UNIX_EPOCH};
process::exit,
time::{Duration, UNIX_EPOCH},
};
pub fn print_image_info(i: ImageInfo, notify: bool) { pub fn print_image_info(i: ImageInfo, notify: bool) {
let d = UNIX_EPOCH + Duration::from_secs(i.data.datetime.try_into().unwrap()); let d = UNIX_EPOCH + Duration::from_secs(i.data.datetime.try_into().unwrap());
@ -56,10 +53,6 @@ pub fn print_image_info(i: ImageInfo, notify: bool) {
.summary("Imgurs") .summary("Imgurs")
.body(&format!("Uploaded {}", i.data.link)) .body(&format!("Uploaded {}", i.data.link))
.show() .show()
.unwrap_or_else(|e| { .expect("send notification");
error!("send notification: {}", e);
exit(2)
});
} }
} }

View File

@ -1,4 +1,4 @@
use imgurs::api::configuration::ImgurHandle; use imgurs::api::ImgurClient;
use clap::{App, AppSettings, IntoApp, Parser, Subcommand}; use clap::{App, AppSettings, IntoApp, Parser, Subcommand};
use clap_complete::{generate, Generator, Shell}; use clap_complete::{generate, Generator, Shell};
@ -52,7 +52,7 @@ fn print_completions<G: Generator>(gen: G, app: &mut App) {
generate(gen, app, app.get_name().to_string(), &mut stdout()) generate(gen, app, app.get_name().to_string(), &mut stdout())
} }
pub async fn parse(client: ImgurHandle) { pub async fn parse(client: ImgurClient) {
let args = Cli::parse(); let args = Cli::parse();
match &args.command { match &args.command {

View File

@ -1,24 +1,20 @@
use imgurs::api::{configuration::ImgurHandle, upload_image::upload_image as upload_img}; use imgurs::api::{upload_image::upload_image as upload_img, ImgurClient};
use super::print_image_info; use super::print_image_info;
use base64::encode as base64_encode; use base64::encode as base64_encode;
use log::error; use std::{fs::read as fs_read, path::Path};
use std::{fs::read as fs_read, path::Path, process::exit};
pub async fn upload_image(client: ImgurHandle, path: &str) { pub async fn upload_image(client: ImgurClient, path: &str) {
let mut image: String = path.to_string(); let mut image: String = path.to_string();
if Path::new(path).exists() { if Path::new(path).exists() {
let bytes = fs_read(path).map_err(|err| err.to_string()).unwrap(); let bytes = fs_read(path)
.map_err(|err| err.to_string())
.expect("read file");
image = base64_encode(bytes); image = base64_encode(bytes);
} }
let i = upload_img(client, &image).await.unwrap_or_else(|e| { let i = upload_img(client, &image).await.expect("send api request");
error!("{e}");
exit(1);
});
print_image_info(i, true); print_image_info(i, true);
} }

View File

@ -2,14 +2,13 @@ use super::Config;
use anyhow::Error; use anyhow::Error;
use dirs::config_dir; use dirs::config_dir;
use log::{error, warn}; use log::warn;
use std::{ use std::{
fs::{create_dir_all, read_to_string, File}, fs::{create_dir_all, read_to_string, File},
io::Write as _, io::Write as _,
path::Path, path::Path,
process::exit,
}; };
use toml::from_str; use toml::from_str as toml_from_str;
const CONFIG_DIR: &str = "/imgurs/config.toml"; const CONFIG_DIR: &str = "/imgurs/config.toml";
@ -19,12 +18,12 @@ pub fn parse() -> Config {
let default_config = include_str!(concat!("../../config.toml")); let default_config = include_str!(concat!("../../config.toml"));
let sys_config_dir = config_dir().unwrap(); let sys_config_dir = config_dir().expect("find config dir");
let config_dir = format!("{}{CONFIG_DIR}", sys_config_dir.to_string_lossy()); let config_dir = format!("{}{CONFIG_DIR}", sys_config_dir.to_string_lossy());
let config_path = Path::new(&config_dir); let config_path = Path::new(&config_dir);
let prefix = config_path.parent().unwrap(); let prefix = config_path.parent().unwrap();
create_dir_all(prefix).unwrap(); create_dir_all(prefix).expect("create config dir");
let mut file_ref = File::create(config_path).expect("create failed"); let mut file_ref = File::create(config_path).expect("create failed");
@ -32,21 +31,15 @@ pub fn parse() -> Config {
.write_all(default_config.as_bytes()) .write_all(default_config.as_bytes())
.expect("failed write default config to file"); .expect("failed write default config to file");
toml().unwrap_or_else(|e| { toml().expect("parse toml config")
error!("parse toml config: {e}");
exit(3);
})
}) })
} }
fn toml() -> Result<Config, Error> { fn toml() -> Result<Config, Error> {
let config_dir = config_dir().unwrap(); let config_dir = config_dir().unwrap();
let file_dir = format!("{}{CONFIG_DIR}", config_dir.to_string_lossy());
let file_dir: String = String::from(config_dir.to_string_lossy()) + CONFIG_DIR;
let toml_str = read_to_string(file_dir).map_err(Error::new)?; let toml_str = read_to_string(file_dir).map_err(Error::new)?;
let decode = toml_from_str(&toml_str).map_err(Error::new)?;
let decode = from_str(&toml_str).map_err(Error::new)?;
Ok(decode) Ok(decode)
} }

View File

@ -2,22 +2,18 @@ mod cli;
mod config; mod config;
use cli::parse::parse; use cli::parse::parse;
use imgurs::api::ImgurHandle; use imgurs::api::ImgurClient;
use log::error;
use simple_logger::SimpleLogger; use simple_logger::SimpleLogger;
use std::process::exit;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
SimpleLogger::new().init().unwrap_or_else(|e| { SimpleLogger::new().init().expect("init SimpleLogger");
error!("init simple logger: {e}"); better_panic::install();
exit(2)
});
let config = config::toml::parse(); let config = config::toml::parse();
let client = ImgurHandle::new((&config.imgur.id).to_string()); let client = ImgurClient::new((&config.imgur.id).to_string());
parse(client).await parse(client).await
} }