Skip to content

Commit

Permalink
Fix remaining clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
ry authored and froydnj committed Mar 13, 2020
1 parent ca73029 commit 65bb3b6
Show file tree
Hide file tree
Showing 28 changed files with 352 additions and 418 deletions.
17 changes: 5 additions & 12 deletions lru-disk-cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,23 +80,16 @@ pub enum Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.description())
write!(f, "{}", self.to_string())
}
}

impl StdError for Error {
fn description(&self) -> &str {
match *self {
Error::FileTooLarge => "File too large",
Error::FileNotInCache => "File not in cache",
Error::Io(ref e) => e.description(),
}
}

fn cause(&self) -> Option<&dyn StdError> {
match *self {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::FileTooLarge => None,
Error::FileNotInCache => None,
Error::Io(ref e) => Some(e),
_ => None,
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/azure/blobstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const BLOB_API_VERSION: &str = "2017-04-17";
fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> {
let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect("HMAC can take key of any size");
hmac.input(data);
hmac.result().code().iter().map(|b| *b).collect::<Vec<u8>>()
hmac.result().code().iter().copied().collect::<Vec<u8>>()
}

fn signature(to_sign: &str, secret: &str) -> String {
Expand Down Expand Up @@ -117,7 +117,7 @@ impl BlobContainer {
.map(|header::ContentLength(len)| len);
Ok((res.into_body(), content_length))
} else {
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
})
.and_then(|(body, content_length)| {
Expand Down Expand Up @@ -207,7 +207,7 @@ impl BlobContainer {
Ok(())
} else {
trace!("PUT failed with HTTP status: {}", res.status());
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
}
Err(e) => {
Expand Down Expand Up @@ -336,12 +336,12 @@ mod test {

let container = BlobContainer::new(creds.azure_blob_endpoint(), container_name).unwrap();

let put_future = container.put("foo", "barbell".as_bytes().to_vec(), &creds);
let put_future = container.put("foo", b"barbell".to_vec(), &creds);
runtime.block_on(put_future).unwrap();

let get_future = container.get("foo", &creds);
let result = runtime.block_on(get_future).unwrap();

assert_eq!("barbell".as_bytes().to_vec(), result);
assert_eq!(b"barbell".to_vec(), result);
}
}
6 changes: 3 additions & 3 deletions src/azure/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl AzureCredentials {
account_key: &str,
container_name: String,
) -> AzureCredentials {
let endpoint = if blob_endpoint.ends_with("/") {
let endpoint = if blob_endpoint.ends_with('/') {
blob_endpoint.to_owned()
} else {
blob_endpoint.to_owned() + "/"
Expand All @@ -42,7 +42,7 @@ impl AzureCredentials {
blob_endpoint: endpoint,
account_name: account_name.to_owned(),
account_key: account_key.to_owned(),
container_name: container_name,
container_name,
}
}

Expand Down Expand Up @@ -92,7 +92,7 @@ fn parse_connection_string(conn: &str, container_name: String) -> Result<AzureCr
let mut account_key = String::default();
let mut endpoint_suffix = String::default();

let split = conn.split(";");
let split = conn.split(';');
for part in split {
if part.starts_with("BlobEndpoint=") {
blob_endpoint = substr(part, "BlobEndpoint=".len()).to_owned();
Expand Down
2 changes: 1 addition & 1 deletion src/cache/azure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl AzureBlobCache {

Ok(AzureBlobCache {
container: Rc::new(container),
credentials: credentials,
credentials,
})
}
}
Expand Down
13 changes: 5 additions & 8 deletions src/cache/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ pub trait Storage {
}

/// Get a suitable `Storage` implementation from configuration.
#[allow(clippy::cognitive_complexity)] // TODO simplify!
pub fn storage_from_config(config: &Config, pool: &CpuPool) -> Arc<dyn Storage> {
for cache_type in config.caches.iter() {
match *cache_type {
Expand Down Expand Up @@ -216,7 +217,7 @@ pub fn storage_from_config(config: &Config, pool: &CpuPool) -> Arc<dyn Storage>

service_account_key_res
.ok()
.map(|account_key| ServiceAccountInfo::AccountKey(account_key))
.map(ServiceAccountInfo::AccountKey)
} else if let Some(ref url) = *url {
Some(ServiceAccountInfo::URL(url.clone()))
} else {
Expand Down Expand Up @@ -265,14 +266,10 @@ pub fn storage_from_config(config: &Config, pool: &CpuPool) -> Arc<dyn Storage>
Err(e) => warn!("Failed to create RedisCache: {:?}", e),
}
}
CacheType::S3(config::S3CacheConfig {
ref bucket,
ref endpoint,
use_ssl,
}) => {
debug!("Trying S3Cache({}, {})", bucket, endpoint);
CacheType::S3(ref c) => {
debug!("Trying S3Cache({}, {})", c.bucket, c.endpoint);
#[cfg(feature = "s3")]
match S3Cache::new(&bucket, &endpoint, use_ssl) {
match S3Cache::new(&c.bucket, &c.endpoint, c.use_ssl) {
Ok(s) => {
trace!("Using S3Cache");
return Arc::new(s);
Expand Down
18 changes: 9 additions & 9 deletions src/cache/gcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Bucket {

let client = self.client.clone();

let creds_opt_future = if let &Some(ref cred_provider) = cred_provider {
let creds_opt_future = if let Some(ref cred_provider) = *cred_provider {
future::Either::A(
cred_provider
.credentials(&self.client)
Expand Down Expand Up @@ -89,7 +89,7 @@ impl Bucket {
if res.status().is_success() {
Ok(res.into_body())
} else {
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
})
.and_then(|body| {
Expand All @@ -116,7 +116,7 @@ impl Bucket {

let client = self.client.clone();

let creds_opt_future = if let &Some(ref cred_provider) = cred_provider {
let creds_opt_future = if let Some(ref cred_provider) = cred_provider {
future::Either::A(cred_provider.credentials(&self.client).map(Some))
} else {
future::Either::B(future::ok(None))
Expand All @@ -141,7 +141,7 @@ impl Bucket {
Ok(())
} else {
trace!("PUT failed with HTTP status: {}", res.status());
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
}
Err(e) => {
Expand Down Expand Up @@ -388,7 +388,7 @@ impl GCSCredentialProvider {
if res.status().is_success() {
Ok(res.into_body())
} else {
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
})
.and_then(move |body| {
Expand Down Expand Up @@ -422,7 +422,7 @@ impl GCSCredentialProvider {
if res.status().is_success() {
Ok(res.into_body())
} else {
Err(ErrorKind::BadHTTPStatus(res.status().clone()).into())
Err(ErrorKind::BadHTTPStatus(res.status()).into())
}
})
.and_then(move |body| {
Expand Down Expand Up @@ -493,8 +493,8 @@ impl GCSCache {
) -> Result<GCSCache> {
Ok(GCSCache {
bucket: Rc::new(Bucket::new(bucket)?),
rw_mode: rw_mode,
credential_provider: credential_provider,
rw_mode,
credential_provider,
})
}
}
Expand Down Expand Up @@ -525,7 +525,7 @@ impl Storage for GCSCache {
let start = time::Instant::now();
let data = match entry.finish() {
Ok(data) => data,
Err(e) => return Box::new(future::err(e.into())),
Err(e) => return Box::new(future::err(e)),
};
let bucket = self.bucket.clone();
let response = bucket
Expand Down
6 changes: 3 additions & 3 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ pub fn request_zero_stats(mut conn: ServerConnection) -> Result<ServerInfo> {
"failed to send zero statistics command to server or failed to receive respone"
})?;
if let Response::Stats(stats) = response {
Ok(stats)
Ok(*stats)
} else {
bail!("Unexpected server response!")
}
Expand All @@ -296,7 +296,7 @@ pub fn request_stats(mut conn: ServerConnection) -> Result<ServerInfo> {
.request(Request::GetStats)
.chain_err(|| "Failed to send data to or receive data from server")?;
if let Response::Stats(stats) = response {
Ok(stats)
Ok(*stats)
} else {
bail!("Unexpected server response!")
}
Expand All @@ -323,7 +323,7 @@ pub fn request_shutdown(mut conn: ServerConnection) -> Result<ServerInfo> {
.request(Request::Shutdown)
.chain_err(|| "Failed to send data to or receive data from server")?;
if let Response::ShuttingDown(stats) = response {
Ok(stats)
Ok(*stats)
} else {
bail!("Unexpected server response!")
}
Expand Down
11 changes: 6 additions & 5 deletions src/compiler/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,7 @@ mod tests {
use self::ArgData::*;

#[test]
#[allow(clippy::cognitive_complexity)]
fn test_arginfo_cmp() {
let info = flag!("-foo", FooFlag);
assert_eq!(info.cmp("-foo"), Ordering::Equal);
Expand Down Expand Up @@ -783,7 +784,7 @@ mod tests {
ArgParseError::UnexpectedEndOfArgs
);
assert_eq!(
info.clone().process("-foo", || Some("bar".into())).unwrap(),
info.process("-foo", || Some("bar".into())).unwrap(),
arg!(WithValue("-foo", Foo("bar"), Separated))
);

Expand All @@ -793,7 +794,7 @@ mod tests {
arg!(WithValue("-foo", Foo(""), Concatenated))
);
assert_eq!(
info.clone().process("-foobar", || None).unwrap(),
info.process("-foobar", || None).unwrap(),
arg!(WithValue("-foo", Foo("bar"), Concatenated))
);

Expand All @@ -803,7 +804,7 @@ mod tests {
arg!(WithValue("-foo", Foo(""), Concatenated('=')))
);
assert_eq!(
info.clone().process("-foo=bar", || None).unwrap(),
info.process("-foo=bar", || None).unwrap(),
arg!(WithValue("-foo", Foo("bar"), Concatenated('=')))
);

Expand All @@ -817,7 +818,7 @@ mod tests {
arg!(WithValue("-foo", Foo("bar"), CanBeSeparated))
);
assert_eq!(
info.clone().process("-foo", || Some("bar".into())).unwrap(),
info.process("-foo", || Some("bar".into())).unwrap(),
arg!(WithValue("-foo", Foo("bar"), CanBeConcatenated))
);

Expand All @@ -835,7 +836,7 @@ mod tests {
arg!(WithValue("-foo", Foo("bar"), CanBeSeparated('=')))
);
assert_eq!(
info.clone().process("-foo", || Some("bar".into())).unwrap(),
info.process("-foo", || Some("bar".into())).unwrap(),
arg!(WithValue("-foo", Foo("bar"), CanBeConcatenated('=')))
);
}
Expand Down
24 changes: 9 additions & 15 deletions src/compiler/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::compiler::{
CompilerKind, HashResult,
};
#[cfg(feature = "dist-client")]
use crate::compiler::{NoopOutputsRewriter, OutputsRewriter};
use crate::compiler::{DistPackagers, NoopOutputsRewriter};
use crate::dist;
#[cfg(feature = "dist-client")]
use crate::dist::pkg;
Expand All @@ -27,7 +27,6 @@ use futures::Future;
use futures_cpupool::CpuPool;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::env::consts::DLL_EXTENSION;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::fs;
Expand Down Expand Up @@ -402,11 +401,7 @@ impl<I: CCompilerImpl> Compilation for CCompilation<I> {
fn into_dist_packagers(
self: Box<Self>,
path_transformer: dist::PathTransformer,
) -> Result<(
Box<dyn pkg::InputsPackager>,
Box<dyn pkg::ToolchainPackager>,
Box<dyn OutputsRewriter>,
)> {
) -> Result<DistPackagers> {
let CCompilation {
parsed_args,
cwd,
Expand Down Expand Up @@ -460,7 +455,7 @@ impl pkg::InputsPackager for CInputsPackager {
{
let input_path = pkg::simplify_path(&input_path)?;
let dist_input_path = path_transformer
.to_dist(&input_path)
.as_dist(&input_path)
.chain_err(|| format!("unable to transform input path {}", input_path.display()))?;

let mut file_header = pkg::make_tar_header(&input_path, &dist_input_path)?;
Expand All @@ -475,7 +470,7 @@ impl pkg::InputsPackager for CInputsPackager {
if !super::CAN_DIST_DYLIBS
&& input_path
.extension()
.map_or(false, |ext| ext == DLL_EXTENSION)
.map_or(false, |ext| ext == std::env::consts::DLL_EXTENSION)
{
bail!(
"Cannot distribute dylib input {} on this platform",
Expand All @@ -484,7 +479,7 @@ impl pkg::InputsPackager for CInputsPackager {
}

let dist_input_path = path_transformer
.to_dist(&input_path)
.as_dist(&input_path)
.chain_err(|| format!("unable to transform input path {}", input_path.display()))?;

let mut file = io::BufReader::new(fs::File::open(&input_path)?);
Expand Down Expand Up @@ -515,7 +510,6 @@ struct CToolchainPackager {
impl pkg::ToolchainPackager for CToolchainPackager {
fn write_pkg(self: Box<Self>, f: fs::File) -> Result<()> {
use std::os::unix::ffi::OsStringExt;
use which::which;

info!("Generating toolchain {}", self.executable.display());
let mut package_builder = pkg::ToolchainPackageBuilder::new();
Expand Down Expand Up @@ -658,7 +652,7 @@ mod test {
#[test]
fn test_hash_key_executable_contents_differs() {
let args = ovec!["a", "b", "c"];
const PREPROCESSED: &'static [u8] = b"hello world";
const PREPROCESSED: &[u8] = b"hello world";
assert_neq!(
hash_key("abcd", Language::C, &args, &[], &[], &PREPROCESSED),
hash_key("wxyz", Language::C, &args, &[], &[], &PREPROCESSED)
Expand All @@ -672,7 +666,7 @@ mod test {
let xyz = ovec!["x", "y", "z"];
let ab = ovec!["a", "b"];
let a = ovec!["a"];
const PREPROCESSED: &'static [u8] = b"hello world";
const PREPROCESSED: &[u8] = b"hello world";
assert_neq!(
hash_key(digest, Language::C, &abc, &[], &[], &PREPROCESSED),
hash_key(digest, Language::C, &xyz, &[], &[], &PREPROCESSED)
Expand Down Expand Up @@ -702,7 +696,7 @@ mod test {
fn test_hash_key_env_var_differs() {
let args = ovec!["a", "b", "c"];
let digest = "abcd";
const PREPROCESSED: &'static [u8] = b"hello world";
const PREPROCESSED: &[u8] = b"hello world";
for var in CACHED_ENV_VARS.iter() {
let h1 = hash_key(digest, Language::C, &args, &[], &[], &PREPROCESSED);
let vars = vec![(OsString::from(var), OsString::from("something"))];
Expand All @@ -718,7 +712,7 @@ mod test {
fn test_extra_hash_data() {
let args = ovec!["a", "b", "c"];
let digest = "abcd";
const PREPROCESSED: &'static [u8] = b"hello world";
const PREPROCESSED: &[u8] = b"hello world";
let extra_data = stringvec!["hello", "world"];

assert_neq!(
Expand Down
Loading

0 comments on commit 65bb3b6

Please sign in to comment.