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]
- SimpleLogger init error handling
### CLI
- better panic
- panic instead of send log error
### Library
- 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
### Added

View File

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

View File

@ -9,20 +9,20 @@ macro_rules! api_url (
pub(crate) use api_url;
pub struct ImgurHandle {
pub struct ImgurClient {
pub client_id: String,
pub client: Client,
}
impl fmt::Debug for ImgurHandle {
impl fmt::Debug for ImgurClient {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ImgurClient - client_id: {}", self.client_id)
}
}
impl ImgurHandle {
impl ImgurClient {
pub fn new(client_id: String) -> Self {
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;
@ -6,7 +6,7 @@ use anyhow::Error as anyhow_err;
use reqwest::Method;
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 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 super::send_api_request;
@ -7,7 +7,7 @@ use anyhow::Error as anyhow_err;
use reqwest::Method;
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 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 upload_image;
pub use configuration::ImgurHandle;
pub use configuration::ImgurClient;
pub use image_type::*;
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;
@ -28,7 +28,7 @@ pub struct RateLimitData {
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 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 reqwest::Method;
use std::collections::HashMap;
pub async fn send_api_request(
config: &ImgurHandle,
config: &ImgurClient,
method: Method,
uri: String,
form: Option<HashMap<&str, String>>,

View File

@ -1,5 +1,5 @@
use crate::api::{
configuration::{api_url, ImgurHandle},
configuration::{api_url, ImgurClient},
ImageInfo,
};
@ -12,7 +12,7 @@ use std::{
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();
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 log::{error, info};
use std::{
process::exit,
time::{Duration, UNIX_EPOCH},
};
use log::info;
use std::time::{Duration, UNIX_EPOCH};
pub async fn credits(client: ImgurHandle) {
let i = rate_limit(client).await.unwrap_or_else(|e| {
error!("{e}");
exit(1);
});
pub async fn credits(client: ImgurClient) {
let i = rate_limit(client).await.expect("send api request");
let d = UNIX_EPOCH + Duration::from_secs(i.data.user_reset.try_into().unwrap());
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 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);
});
use log::info;
pub async fn delete_image(client: ImgurClient, delete_hash: String) {
let i = del_img(client, delete_hash)
.await
.expect("send api request");
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 log::error;
use std::process::exit;
pub async fn image_info(client: ImgurHandle, id: &str) {
let i = get_image(client, id).await.unwrap_or_else(|e| {
error!("{e}");
exit(1);
});
pub async fn image_info(client: ImgurClient, id: &str) {
let i = get_image(client, id).await.expect("send api request");
print_image_info(i, false);
}

View File

@ -8,12 +8,9 @@ use crate::config::toml::parse;
use imgurs::api::ImageInfo;
use chrono::{prelude::DateTime, Utc};
use log::{error, info};
use log::info;
use notify_rust::Notification;
use std::{
process::exit,
time::{Duration, UNIX_EPOCH},
};
use std::time::{Duration, UNIX_EPOCH};
pub fn print_image_info(i: ImageInfo, notify: bool) {
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")
.body(&format!("Uploaded {}", i.data.link))
.show()
.unwrap_or_else(|e| {
error!("send notification: {}", e);
exit(2)
});
.expect("send notification");
}
}

View File

@ -1,4 +1,4 @@
use imgurs::api::configuration::ImgurHandle;
use imgurs::api::ImgurClient;
use clap::{App, AppSettings, IntoApp, Parser, Subcommand};
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())
}
pub async fn parse(client: ImgurHandle) {
pub async fn parse(client: ImgurClient) {
let args = Cli::parse();
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 base64::encode as base64_encode;
use log::error;
use std::{fs::read as fs_read, path::Path, process::exit};
use std::{fs::read as fs_read, path::Path};
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();
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);
}
let i = upload_img(client, &image).await.unwrap_or_else(|e| {
error!("{e}");
exit(1);
});
let i = upload_img(client, &image).await.expect("send api request");
print_image_info(i, true);
}

View File

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

View File

@ -2,22 +2,18 @@ mod cli;
mod config;
use cli::parse::parse;
use imgurs::api::ImgurHandle;
use imgurs::api::ImgurClient;
use log::error;
use simple_logger::SimpleLogger;
use std::process::exit;
#[tokio::main]
async fn main() {
SimpleLogger::new().init().unwrap_or_else(|e| {
error!("init simple logger: {e}");
exit(2)
});
SimpleLogger::new().init().expect("init SimpleLogger");
better_panic::install();
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
}