Remove some clones by using Cow
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Valentin Brandl 2019-08-11 13:48:04 +02:00
parent 0729909bab
commit 387b6241a2
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D
5 changed files with 46 additions and 31 deletions

View File

@ -24,7 +24,7 @@ impl Cloudflare {
"https://api.cloudflare.com/client/v4/zones/{}/purge_cache", "https://api.cloudflare.com/client/v4/zones/{}/purge_cache",
Self::identifier() Self::identifier()
)) ))
.header(header::USER_AGENT, statics::USER_AGENT.as_str()) .header(header::USER_AGENT, &*statics::USER_AGENT.as_str())
.header("X-Auth-Email", Self::auth_email()) .header("X-Auth-Email", Self::auth_email())
.header("X-Auth-Key", Self::auth_key()) .header("X-Auth-Key", Self::auth_key())
.content_type("application/json") .content_type("application/json")
@ -36,7 +36,7 @@ impl Cloudflare {
// "https://api.cloudflare.com/client/v4/zones/{}/purge_cache", // "https://api.cloudflare.com/client/v4/zones/{}/purge_cache",
// Self::identifier() // Self::identifier()
// )) // ))
// .header(header::USER_AGENT, statics::USER_AGENT.as_str()) // .header(header::USER_AGENT, statics::USER_AGENT.as_ref())
// .header("X-Auth-Email", Self::auth_email()) // .header("X-Auth-Email", Self::auth_email())
// .header("X-Auth-Key", Self::auth_key()) // .header("X-Auth-Key", Self::auth_key())
// .content_type("application/json") // .content_type("application/json")
@ -69,7 +69,7 @@ impl CfPurgeRequest {
Self { Self {
files: vec![format!( files: vec![format!(
"https://{}/{}/{}", "https://{}/{}/{}",
statics::HOSTNAME.as_str(), statics::HOSTNAME.as_ref(),
T::path(), T::path(),
file file
)], )],

View File

@ -20,9 +20,9 @@ impl FilePath {
pub(crate) fn to_key<T: service::Service>(&self) -> Key { pub(crate) fn to_key<T: service::Service>(&self) -> Key {
Key::new( Key::new(
T::cache_service(), T::cache_service(),
self.user.clone(), Arc::clone(&self.user),
self.repo.clone(), Arc::clone(&self.repo),
self.commit.clone(), Arc::clone(&self.commit),
) )
} }
} }

View File

@ -158,7 +158,7 @@ fn purge_local_cache<T: 'static + Service>(
cache: web::Data<State>, cache: web::Data<State>,
data: web::Path<FilePath>, data: web::Path<FilePath>,
) -> impl Future<Item = HttpResponse, Error = Error> { ) -> impl Future<Item = HttpResponse, Error = Error> {
let cache = cache.clone(); let cache = Arc::clone(&cache);
futures::future::ok(()).map(move |_| { futures::future::ok(()).map(move |_| {
if let Ok(mut cache) = cache.write() { if let Ok(mut cache) = cache.write() {
info!("Invalidating local cache for {}/{}", T::path(), data.path()); info!("Invalidating local cache for {}/{}", T::path(), data.path());
@ -188,7 +188,7 @@ fn main() -> Result<()> {
Ok(HttpServer::new(move || { Ok(HttpServer::new(move || {
App::new() App::new()
.data(Client::new()) .data(Client::new())
.data(state.clone()) .data(Arc::clone(&state))
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath) .wrap(middleware::NormalizePath)
.service(favicon32) .service(favicon32)

View File

@ -12,6 +12,7 @@ use actix_web::{
use awc::{error::PayloadError, Client, ClientResponse}; use awc::{error::PayloadError, Client, ClientResponse};
use bytes::Bytes; use bytes::Bytes;
use futures::{Future, Stream}; use futures::{Future, Stream};
use std::borrow::Cow;
pub(crate) trait ApiResponse { pub(crate) trait ApiResponse {
fn commit_ref(&self) -> &str; fn commit_ref(&self) -> &str;
@ -126,15 +127,17 @@ pub(crate) trait Service: Sized {
pub(crate) struct Github; pub(crate) struct Github;
impl Github { impl Github {
pub(crate) fn auth_query() -> Option<String> { pub(crate) fn auth_query() -> Option<Cow<'static, str>> {
OPT.github_id OPT.github_id
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("GITHUB_CLIENT_ID")) .or_else(|| load_env_var("GITHUB_CLIENT_ID"))
.and_then(|id| { .and_then(|id| {
OPT.github_secret OPT.github_secret
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("GITHUB_CLIENT_SECRET")) .or_else(|| load_env_var("GITHUB_CLIENT_SECRET"))
.map(|secret| format!("?client_id={}&client_secret={}", id, secret)) .map(|secret| format!("?client_id={}&client_secret={}", id, secret).into())
}) })
} }
} }
@ -167,7 +170,7 @@ impl Service for Github {
path.user, path.user,
path.repo, path.repo,
path.commit, path.commit,
GITHUB_AUTH_QUERY.as_str() GITHUB_AUTH_QUERY.as_ref()
) )
} }

View File

@ -1,5 +1,5 @@
use crate::{config::Opt, service::Github}; use crate::{config::Opt, service::Github};
use std::{env, time::Duration}; use std::{borrow::Cow, env, time::Duration};
use structopt::StructOpt; use structopt::StructOpt;
const VERSION: &str = env!("CARGO_PKG_VERSION"); const VERSION: &str = env!("CARGO_PKG_VERSION");
@ -8,31 +8,43 @@ pub(crate) const FAVICON: &[u8] = include_bytes!("../static/favicon32.png");
lazy_static! { lazy_static! {
pub(crate) static ref USER_AGENT: String = format!("yagcdn/{}", VERSION); pub(crate) static ref USER_AGENT: String = format!("yagcdn/{}", VERSION);
pub(crate) static ref OPT: Opt = Opt::from_args(); pub(crate) static ref OPT: Opt = Opt::from_args();
pub(crate) static ref GITHUB_AUTH_QUERY: String = Github::auth_query().unwrap_or_default(); pub(crate) static ref GITHUB_AUTH_QUERY: Cow<'static, str> =
pub(crate) static ref CF_ZONE_IDENT: String = OPT Github::auth_query().unwrap_or_default().into();
pub(crate) static ref CF_ZONE_IDENT: Cow<'static, str> = OPT
.cf_zone .cf_zone
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("CF_ZONE_IDENT")) .or_else(|| load_env_var("CF_ZONE_IDENT"))
.expect("Cloudflare zone identifier not set"); .expect("Cloudflare zone identifier not set")
pub(crate) static ref CF_AUTH_KEY: String = OPT .into();
pub(crate) static ref CF_AUTH_KEY: Cow<'static, str> = OPT
.cf_auth_key .cf_auth_key
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("CF_AUTH_KEY")) .or_else(|| load_env_var("CF_AUTH_KEY"))
.expect("Cloudflare auth key not set"); .expect("Cloudflare auth key not set")
pub(crate) static ref CF_AUTH_USER: String = OPT .into();
pub(crate) static ref CF_AUTH_USER: Cow<'static, str> = OPT
.cf_auth_user .cf_auth_user
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("CF_AUTH_USER")) .or_else(|| load_env_var("CF_AUTH_USER"))
.expect("Cloudflare auth user not set"); .expect("Cloudflare auth user not set")
pub(crate) static ref HOSTNAME: String = OPT .into();
pub(crate) static ref HOSTNAME: Cow<'static, str> = OPT
.hostname .hostname
.clone() .as_ref()
.map(Cow::from)
.or_else(|| load_env_var("YAGCDN_HOSTNAME")) .or_else(|| load_env_var("YAGCDN_HOSTNAME"))
.unwrap_or_else(|| "yagcdn.tk".to_string()); .unwrap_or_else(|| "yagcdn.tk".into());
} }
pub(crate) fn load_env_var(key: &str) -> Option<String> { pub(crate) fn load_env_var(key: &str) -> Option<Cow<'static, str>> {
env::var(key) env::var(key).ok().and_then(|val| {
.ok() if val.is_empty() {
.and_then(|val| if val.is_empty() { None } else { Some(val) }) None
} else {
Some(val.into())
}
})
} }