feat: add clippy

This commit is contained in:
Pierre Mavro
2021-05-07 21:29:25 +02:00
parent 0068bf3d8e
commit 4c69da0685
19 changed files with 139 additions and 199 deletions

2
clippy.toml Normal file
View File

@@ -0,0 +1,2 @@
too-many-arguments-threshold = 32
upper-case-acronyms-aggressive = false

View File

@@ -40,16 +40,14 @@ impl LocalDocker {
}
fn image_does_exist(&self, image: &Image) -> Result<bool, EngineError> {
Ok(
match crate::cmd::utilities::exec(
Ok(matches!(
crate::cmd::utilities::exec(
"docker",
vec!["image", "inspect", image.name_with_tag().as_str()],
&self.get_docker_host_envs(),
) {
Ok(_) => true,
_ => false,
},
)
),
Ok(_)
))
}
fn get_docker_host_envs(&self) -> Vec<(&str, &str)> {

View File

@@ -234,7 +234,7 @@ impl Service for Application {
})
.collect::<Vec<_>>();
let is_storage = storage.len() > 0;
let is_storage = !storage.is_empty();
context.insert("storage", &storage);
context.insert("is_storage", &is_storage);

View File

@@ -91,7 +91,7 @@ impl Service for Redis {
let max_size = 47 - prefix.len(); // 50 (max Elasticache ) - 3 (k8s statefulset chars)
let mut new_name = self.name().replace("_", "").replace("-", "");
if new_name.clone().chars().count() > max_size {
if new_name.chars().count() > max_size {
new_name = new_name[..max_size].to_string();
}

View File

@@ -256,26 +256,24 @@ impl<'a> EKS<'a> {
// Vault
context.insert("vault_auth_method", "none");
match env::var_os("VAULT_ADDR") {
Some(_) => {
// select the correct used method
match env::var_os("VAULT_ROLE_ID") {
Some(role_id) => {
context.insert("vault_auth_method", "app_role");
context.insert("vault_role_id", role_id.to_str().unwrap());
if let Some(_) = env::var_os("VAULT_ADDR") {
// select the correct used method
match env::var_os("VAULT_ROLE_ID") {
Some(role_id) => {
context.insert("vault_auth_method", "app_role");
context.insert("vault_role_id", role_id.to_str().unwrap());
match env::var_os("VAULT_SECRET_ID") {
Some(secret_id) => context.insert("vault_secret_id", secret_id.to_str().unwrap()),
None => error!("VAULT_SECRET_ID environment variable wasn't found"),
}
match env::var_os("VAULT_SECRET_ID") {
Some(secret_id) => context.insert("vault_secret_id", secret_id.to_str().unwrap()),
None => error!("VAULT_SECRET_ID environment variable wasn't found"),
}
}
None => {
if let Some(_) = env::var_os("VAULT_TOKEN") {
context.insert("vault_auth_method", "token")
}
None => match env::var_os("VAULT_TOKEN") {
Some(_) => context.insert("vault_auth_method", "token"),
None => {}
},
}
}
None => {}
};
// AWS
@@ -788,13 +786,12 @@ impl<'a> Kubernetes for EKS<'a> {
));
info!("Running Terraform apply");
match cast_simple_error_to_engine_error(
if let Err(e) = cast_simple_error_to_engine_error(
self.engine_error_scope(),
self.context.execution_id(),
cmd::terraform::terraform_init_validate_plan_apply(temp_dir.as_str(), false),
) {
Err(e) => error!("An issue occurred during the apply before destroy of Terraform, it may be expected if you're resuming a destroy: {:?}", e.message),
_ => {}
error!("An issue occurred during the apply before destroy of Terraform, it may be expected if you're resuming a destroy: {:?}", e.message)
};
// should make the diff between all namespaces and qovery managed namespaces
@@ -803,9 +800,7 @@ impl<'a> Kubernetes for EKS<'a> {
execution_id: self.context.execution_id().to_string(),
},
ProgressLevel::Warn,
Some(format!(
"Deleting all non-Qovery deployed applications and dependencies",
)),
Some("Deleting all non-Qovery deployed applications and dependencies".to_string()),
self.context.execution_id(),
));
@@ -848,9 +843,7 @@ impl<'a> Kubernetes for EKS<'a> {
execution_id: self.context.execution_id().to_string(),
},
ProgressLevel::Warn,
Some(format!(
"Deleting all Qovery deployed elements and associated dependencies",
)),
Some("Deleting all Qovery deployed elements and associated dependencies".to_string()),
self.context.execution_id(),
));

View File

@@ -13,15 +13,13 @@ pub struct Role {
}
pub fn get_default_roles_to_create() -> Vec<Role> {
let mut defaults_role_to_create: Vec<Role> = Vec::new();
defaults_role_to_create.push(Role {
vec![Role {
role_name: "AWSServiceRoleForAmazonElasticsearchService".to_string(),
service_name: "es.amazonaws.com".to_string(),
description:
"role permissions policy allows Amazon ES to complete create, delete, describe, modify on ec2 and elb"
.to_string(),
});
defaults_role_to_create
}]
}
impl Role {

View File

@@ -133,14 +133,11 @@ impl Service for Router {
.iter()
.find(|app| app.name() == r.application_name.as_str())
{
Some(application) => match application.private_port() {
Some(private_port) => Some(RouteDataTemplate {
path: r.path.clone(),
application_name: application.sanitized_name().to_string(),
application_port: private_port,
}),
_ => None,
},
Some(application) => application.private_port().map(|private_port| RouteDataTemplate {
path: r.path.clone(),
application_name: application.sanitized_name(),
application_port: private_port,
}),
_ => None,
}
})

View File

@@ -28,9 +28,7 @@ pub fn get_ip_from_do_load_balancer_api_output(json_content: &str) -> Result<Ipv
},
Err(_) => Err(SimpleError::new(
SimpleErrorKind::Other,
Some(format!(
"Error While trying to deserialize json received from Digital Ocean Load Balancer API"
)),
Some("Error While trying to deserialize json received from Digital Ocean Load Balancer API".to_string()),
)),
}
}
@@ -110,9 +108,8 @@ pub fn get_uuid_of_cluster_from_name(token: &str, kube_cluster_name: &str) -> Re
fn search_uuid_cluster_for(kube_name: &str, clusters: Clusters) -> Option<String> {
for cluster in clusters.kubernetes_clusters {
match cluster.name.eq(kube_name) {
true => return Some(cluster.id),
_ => {}
if let true = cluster.name.eq(kube_name) {
return Some(cluster.id);
}
}
None

View File

@@ -375,15 +375,14 @@ where
let kubernetes_config_file_path = kubernetes.config_file_path()?;
// define labels to add to namespace
let namespace_labels = match service.context().resource_expiration_in_seconds() {
Some(_) => Some(vec![
let namespace_labels = service.context().resource_expiration_in_seconds().map(|_| {
vec![
(LabelsContent {
name: "ttl".to_string(),
value: format! {"{}", service.context().resource_expiration_in_seconds().unwrap()},
}),
]),
None => None,
};
]
});
// create a namespace with labels if do not exists
let _ = cast_simple_error_to_engine_error(
@@ -584,15 +583,14 @@ where
)?;
// define labels to add to namespace
let namespace_labels = match service.context().resource_expiration_in_seconds() {
Some(_) => Some(vec![
let namespace_labels = service.context().resource_expiration_in_seconds().map(|_| {
vec![
(LabelsContent {
name: "ttl".into(),
value: format!("{}", service.context().resource_expiration_in_seconds().unwrap()),
}),
]),
None => None,
};
]
});
// create a namespace with labels if it does not exist
let _ = cast_simple_error_to_engine_error(
@@ -1158,10 +1156,7 @@ where
let progress_info = ProgressInfo::new(
service.progress_scope(),
Info,
match waiting_message {
Some(message) => Some(message.into()),
_ => None,
},
waiting_message.map(|message| message.into()),
service.context().execution_id(),
);
@@ -1204,7 +1199,7 @@ where
}
pub fn get_tfstate_suffix(service: &dyn Service) -> String {
format!("{}", service.id())
service.id().to_string()
}
// Name generated from TF secret suffix

View File

@@ -100,8 +100,8 @@ pub fn get_supported_version_to_use(
return match all_supported_versions.get(&format!(
"{}.{}.{}",
version.major,
version.minor.unwrap().to_string(),
version.patch.unwrap().to_string()
version.minor.unwrap(),
version.patch.unwrap()
)) {
Some(version) => Ok(version.to_string()),
None => {
@@ -115,7 +115,7 @@ pub fn get_supported_version_to_use(
// if a minor version is required
if version.minor.is_some() {
return match all_supported_versions.get(&format!("{}.{}", version.major, version.minor.unwrap()).to_string()) {
return match all_supported_versions.get(&format!("{}.{}", version.major, version.minor.unwrap())) {
Some(version) => Ok(version.to_string()),
None => {
return Err(format!(
@@ -232,15 +232,9 @@ pub fn get_version_number(version: &str) -> Result<VersionsNumber, StringError>
_ => return Err("please check the version you've sent, it can't be checked".to_string()),
};
let minor = match version_split.next() {
Some(minor) => Some(minor.to_string()),
_ => None,
};
let minor = version_split.next().map(|minor| minor.to_string());
let patch = match version_split.next() {
Some(patch) => Some(patch.to_string()),
_ => None,
};
let patch = version_split.next().map(|patch| patch.to_string());
Ok(VersionsNumber { major, minor, patch })
}
@@ -437,10 +431,10 @@ pub fn convert_k8s_cpu_value_to_f32(value: String) -> Result<f32, ParseFloatErro
};
}
return match value.parse::<f32>() {
match value.parse::<f32>() {
Ok(n) => Ok(n),
Err(e) => Err(e),
};
}
}
pub fn validate_k8s_required_cpu_and_burstable(
@@ -474,10 +468,10 @@ pub fn validate_k8s_required_cpu_and_burstable(
set_cpu_burst = total_cpu.clone();
}
return Ok(CpuLimits {
Ok(CpuLimits {
cpu_limit: set_cpu_burst.to_string(),
cpu_request: total_cpu,
});
})
}
#[cfg(test)]

View File

@@ -52,10 +52,9 @@ where
let helm_history_rows = helm_exec_history(kubernetes_config.as_ref(), namespace, release_name, envs)?;
// take the last deployment from helm history - or return none if there is no history
Ok(match helm_history_rows.first() {
Some(helm_history_row) => Some(helm_history_row.clone()),
None => None,
})
Ok(helm_history_rows
.first()
.map(|helm_history_row| helm_history_row.clone()))
}
pub fn helm_exec_upgrade<P>(
@@ -315,10 +314,9 @@ where
let helm_history_rows = helm_exec_history(kubernetes_config.as_ref(), namespace, release_name, envs)?;
// take the last deployment from helm history - or return none if there is no history
Ok(match helm_history_rows.first() {
Some(helm_history_row) => Some(helm_history_row.clone()),
None => None,
})
Ok(helm_history_rows
.first()
.map(|helm_history_row| helm_history_row.clone()))
}
/// List deployed helm charts

View File

@@ -17,7 +17,7 @@ enum CommandOutputType {
STDERR(Result<String, std::io::Error>),
}
fn command<P>(binary: P, args: Vec<&str>, envs: &Vec<(&str, &str)>, use_output: bool) -> Command
fn command<P>(binary: P, args: Vec<&str>, envs: &[(&str, &str)], use_output: bool) -> Command
where
P: AsRef<Path>,
{
@@ -49,14 +49,14 @@ where
cmd.current_dir(current_dir);
}
envs.into_iter().for_each(|(k, v)| {
envs.iter().for_each(|(k, v)| {
cmd.env(k, v);
});
cmd
}
pub fn exec<P>(binary: P, args: Vec<&str>, envs: &Vec<(&str, &str)>) -> Result<(), SimpleError>
pub fn exec<P>(binary: P, args: Vec<&str>, envs: &[(&str, &str)]) -> Result<(), SimpleError>
where
P: AsRef<Path>,
{
@@ -108,11 +108,11 @@ where
F: FnMut(Result<String, Error>),
X: FnMut(Result<String, Error>),
{
let command_string = command_to_string(binary.as_ref(), &args, &vec![]);
let command_string = command_to_string(binary.as_ref(), &args, &[]);
info!("command: {}", command_string.as_str());
let mut child = _with_output(
command(binary, args, &vec![], true).spawn().unwrap(),
command(binary, args, &[], true).spawn().unwrap(),
stdout_output,
stderr_output,
);
@@ -176,16 +176,14 @@ where
match line {
STDOUT(Err(ref err)) | STDERR(Err(ref err)) if err.kind() == ErrorKind::TimedOut => {}
STDOUT(line) => {
match &line {
Ok(x) => command_output.push(x.to_string()),
_ => {}
if let Ok(x) = &line {
command_output.push(x.to_string())
}
stdout_output(line)
}
STDERR(line) => {
match &line {
Ok(x) => command_output.push(x.to_string()),
_ => {}
if let Ok(x) = &line {
command_output.push(x.to_string())
}
stderr_output(line)
}

View File

@@ -57,7 +57,7 @@ impl ContainerRegistry for DockerHub {
"docker",
vec!["--version"],
|r_out| match r_out {
Ok(s) => output_from_cmd.push_str(&s.to_owned()),
Ok(s) => output_from_cmd.push_str(&s),
Err(e) => error!("Error while getting sdtout from docker {}", e),
},
|r_err| match r_err {
@@ -99,10 +99,7 @@ impl ContainerRegistry for DockerHub {
.send();
match res {
Ok(out) => match out.status() {
StatusCode::OK => true,
_ => false,
},
Ok(out) => matches!(out.status(), StatusCode::OK),
Err(e) => {
error!("While trying to retrieve if DockerHub repository exist {:?}", e);
false
@@ -116,21 +113,18 @@ impl ContainerRegistry for DockerHub {
None => vec![],
};
match cmd::utilities::exec(
if let Err(_) = cmd::utilities::exec(
"docker",
vec!["login", "-u", self.login.as_str(), "-p", self.password.as_str()],
&envs,
) {
Err(_) => {
return Err(self.engine_error(
EngineErrorCause::User(
"Your DockerHub account seems to be no longer valid (bad Credentials). \
Please contact your Organization administrator to fix or change the Credentials.",
),
format!("failed to login to DockerHub {}", self.name_with_id()),
));
}
_ => {}
return Err(self.engine_error(
EngineErrorCause::User(
"Your DockerHub account seems to be no longer valid (bad Credentials). \
Please contact your Organization administrator to fix or change the Credentials.",
),
format!("failed to login to DockerHub {}", self.name_with_id()),
));
};
let dest = format!("{}/{}", self.login.as_str(), image.name_with_tag().as_str());
@@ -185,7 +179,7 @@ impl ContainerRegistry for DockerHub {
Err(e) => Err(self.engine_error(
EngineErrorCause::Internal,
e.message
.unwrap_or("unknown error occurring during docker push".to_string()),
.unwrap_or_else(|| "unknown error occurring during docker push".to_string()),
)),
}
}

View File

@@ -199,7 +199,7 @@ impl ECR {
&repository_name, repo_creation_counter
),
Err(Operation { error, .. }) => return error,
Err(retry::Error::Internal(e)) => return Err(self.engine_error(EngineErrorCause::Internal, e.to_string())),
Err(retry::Error::Internal(e)) => return Err(self.engine_error(EngineErrorCause::Internal, e)),
};
// apply retention policy
@@ -381,7 +381,7 @@ impl ContainerRegistry for ECR {
}
};
match cmd::utilities::exec(
if let Err(_) = cmd::utilities::exec(
"docker",
vec![
"login",
@@ -393,16 +393,13 @@ impl ContainerRegistry for ECR {
],
&self.docker_envs(),
) {
Err(_) => {
return Err(self.engine_error(
EngineErrorCause::User(
"Your ECR account seems to be no longer valid (bad Credentials). \
Please contact your Organization administrator to fix or change the Credentials.",
),
format!("failed to login to ECR {}", self.name_with_id()),
))
}
_ => {}
return Err(self.engine_error(
EngineErrorCause::User(
"Your ECR account seems to be no longer valid (bad Credentials). \
Please contact your Organization administrator to fix or change the Credentials.",
),
format!("failed to login to ECR {}", self.name_with_id()),
));
};
let dest = format!("{}:{}", repository.repository_uri.unwrap(), image.tag.as_str());

View File

@@ -16,20 +16,9 @@ fn minus_namespaces<'a>(all: Vec<&'a str>, to_remove_namespaces: Vec<&str>) -> V
pub fn get_qovery_managed_namespaces() -> Vec<&'static str> {
// the order is very important because of dependencies
let mut qovery_managed_namespaces = Vec::with_capacity(5);
qovery_managed_namespaces.push("logging");
qovery_managed_namespaces.push("nginx-ingress");
qovery_managed_namespaces.push("qovery");
qovery_managed_namespaces.push("cert-manager");
qovery_managed_namespaces.push("prometheus");
return qovery_managed_namespaces;
vec!["logging", "nginx-ingress", "qovery", "cert-manager", "prometheus"]
}
fn get_never_delete_namespaces() -> Vec<&'static str> {
let mut kubernetes_never_delete_namespaces = Vec::with_capacity(4);
kubernetes_never_delete_namespaces.push("default");
kubernetes_never_delete_namespaces.push("kube-node-lease");
kubernetes_never_delete_namespaces.push("kube-public");
kubernetes_never_delete_namespaces.push("kube-system");
return kubernetes_never_delete_namespaces;
vec!["default", "kube-node-lease", "kube-public", "kube-system"]
}

View File

@@ -41,7 +41,7 @@ where
tera::ErrorKind::CallFunction(x) => format!("call function: {}", x),
tera::ErrorKind::CallFilter(x) => format!("call filter: {}", x),
tera::ErrorKind::CallTest(x) => format!("call test: {}", x),
tera::ErrorKind::__Nonexhaustive => format!("non exhaustive error"),
tera::ErrorKind::__Nonexhaustive => "non exhaustive error".to_string(),
};
error!("{}", context.clone().into_json());
@@ -129,9 +129,8 @@ pub fn write_rendered_templates(rendered_templates: &[RenderedTemplate], into: &
// perform spcific action based on the extension
let extension = Path::new(&dest).extension().and_then(OsStr::to_str);
match extension {
Some("sh") => set_file_permission(&f, 0o755),
_ => {}
if let Some("sh") = extension {
set_file_permission(&f, 0o755)
}
}

View File

@@ -219,13 +219,12 @@ impl<'a> Transaction<'a> {
Ok(build_result) => build_result,
};
match application.to_application(
if let Some(app) = application.to_application(
self.engine.context(),
&build_result.build.image,
self.engine.cloud_provider(),
) {
Some(app) => applications.push(app),
None => {}
applications.push(app)
}
}
@@ -266,18 +265,15 @@ impl<'a> Transaction<'a> {
}
fn check_environment(&self, environment: &crate::cloud_provider::environment::Environment) -> TransactionResult {
match environment.is_valid() {
Err(engine_error) => {
warn!("ROLLBACK STARTED! an error occurred {:?}", engine_error);
return match self.rollback() {
Ok(_) => TransactionResult::Rollback(engine_error),
Err(err) => {
error!("ROLLBACK FAILED! fatal error: {:?}", err);
TransactionResult::UnrecoverableError(engine_error, err)
}
};
}
_ => {}
if let Err(engine_error) = environment.is_valid() {
warn!("ROLLBACK STARTED! an error occurred {:?}", engine_error);
return match self.rollback() {
Ok(_) => TransactionResult::Rollback(engine_error),
Err(err) => {
error!("ROLLBACK FAILED! fatal error: {:?}", err);
TransactionResult::UnrecoverableError(engine_error, err)
}
};
};
TransactionResult::Ok
@@ -288,23 +284,20 @@ impl<'a> Transaction<'a> {
match step {
Step::CreateKubernetes(kubernetes) => {
// revert kubernetes creation
match kubernetes.on_create_error() {
Err(err) => return Err(RollbackError::CommitError(err)),
_ => {}
if let Err(err) = kubernetes.on_create_error() {
return Err(RollbackError::CommitError(err));
};
}
Step::DeleteKubernetes(kubernetes) => {
// revert kubernetes deletion
match kubernetes.on_delete_error() {
Err(err) => return Err(RollbackError::CommitError(err)),
_ => {}
if let Err(err) = kubernetes.on_delete_error() {
return Err(RollbackError::CommitError(err));
};
}
Step::PauseKubernetes(kubernetes) => {
// revert pause
match kubernetes.on_pause_error() {
Err(err) => return Err(RollbackError::CommitError(err)),
_ => {}
if let Err(err) = kubernetes.on_pause_error() {
return Err(RollbackError::CommitError(err));
};
}
Step::BuildEnvironment(_environment_action, _option) => {
@@ -342,19 +335,20 @@ impl<'a> Transaction<'a> {
for application in environment.applications.iter() {
let build = application.to_build();
match application.to_application(self.engine.context(), &build.image, self.engine.cloud_provider()) {
Some(x) => _applications.push(x),
None => {}
if let Some(x) =
application.to_application(self.engine.context(), &build.image, self.engine.cloud_provider())
{
_applications.push(x)
}
}
for external_service in environment.external_services.iter() {
let build = external_service.to_build();
match external_service.to_application(self.engine.context(), &build.image, self.engine.cloud_provider())
if let Some(x) =
external_service.to_application(self.engine.context(), &build.image, self.engine.cloud_provider())
{
Some(x) => _applications.push(x),
None => {}
_applications.push(x)
}
}
@@ -488,26 +482,23 @@ impl<'a> Transaction<'a> {
applications_by_environment.insert(target_environment, applications);
// build as well the failover environment, retention could remove the application image
match environment_action {
EnvironmentAction::EnvironmentWithFailover(_, fe) => {
let apps_result = match self._build_applications(fe, option) {
Ok(applications) => match self._push_applications(applications, option) {
Ok(results) => {
let applications = results.into_iter().map(|(app, _)| app).collect::<Vec<_>>();
if let EnvironmentAction::EnvironmentWithFailover(_, fe) = environment_action {
let apps_result = match self._build_applications(fe, option) {
Ok(applications) => match self._push_applications(applications, option) {
Ok(results) => {
let applications = results.into_iter().map(|(app, _)| app).collect::<Vec<_>>();
Ok(applications)
}
Err(err) => Err(err),
},
Ok(applications)
}
Err(err) => Err(err),
};
if apps_result.is_err() {
// should never be triggered because core always should ask for working failover environment
let commit_error = apps_result.err().unwrap();
error!("An error occurred on failover application {:?}", commit_error);
}
},
Err(err) => Err(err),
};
if apps_result.is_err() {
// should never be triggered because core always should ask for working failover environment
let commit_error = apps_result.err().unwrap();
error!("An error occurred on failover application {:?}", commit_error);
}
_ => {}
};
}
Step::DeployEnvironment(kubernetes, environment_action) => {
@@ -617,7 +608,7 @@ impl<'a> Transaction<'a> {
// an error occurred on infrastructure deployment AND rolledback is KO
error!("infrastructure ROLLBACK FAILED! fatal error: {:?}", e);
send_progress(&lh, action, execution_id, true);
return TransactionResult::UnrecoverableError(err, e);
TransactionResult::UnrecoverableError(err, e)
}
}
}

View File

@@ -10,7 +10,7 @@ pub fn cpu_string_to_float<T: Into<String>>(cpu: T) -> f32 {
return 0.0;
}
if !cpu.ends_with("m") {
if !cpu.ends_with('m') {
// the value is not in millis
return match cpu.parse::<f32>() {
Ok(v) if v >= 0.0 => v,
@@ -56,13 +56,13 @@ pub fn mi_to_mi<T: Into<String>>(ram: T) -> u32 {
/// convert ki, mi or gi to mi
pub fn any_to_mi<T: Into<String>>(ram: T) -> u32 {
let ram = ram.into();
return if ram.to_lowercase().ends_with("mi") {
if ram.to_lowercase().ends_with("mi") {
mi_to_mi(ram)
} else if ram.to_lowercase().ends_with("ki") {
ki_to_mi(ram)
} else {
gi_to_mi(ram)
};
}
}
#[cfg(test)]

View File

@@ -4,7 +4,7 @@ extern crate serde_derive;
use chrono::Utc;
use qovery_engine::cloud_provider::aws::kubernetes::node::Node;
use qovery_engine::cloud_provider::aws::kubernetes::{Options, EKS};
use qovery_engine::cloud_provider::aws::kubernetes::{EKS, Options};
use qovery_engine::cloud_provider::aws::AWS;
use qovery_engine::cloud_provider::utilities::sanitize_name;
use qovery_engine::cloud_provider::TerraformStateCredentials;