Skip to content

Commit

Permalink
refactor(0.6.0rc1): clippy and fmt (#380)
Browse files Browse the repository at this point in the history
* refactor: fmt

* refactor: clippy

* fix(e2e): unresolved import
  • Loading branch information
oddgrd authored Oct 7, 2022
1 parent 9ab2a5a commit 280197d
Show file tree
Hide file tree
Showing 13 changed files with 50 additions and 50 deletions.
2 changes: 1 addition & 1 deletion cargo-shuttle/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ impl Client {
let mut request = url.into_client_request()?;

if let Some(ref api_key) = self.api_key {
let auth_header = Authorization::bearer(&api_key)?;
let auth_header = Authorization::bearer(api_key)?;
request.headers_mut().typed_insert(auth_header);
}

Expand Down
4 changes: 2 additions & 2 deletions deployer/src/deployment/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ pub async fn task(
let logger = logger_factory.get_logger(id);

let old_deployments_killer = kill_old_deployments(
built.service_id.clone(),
id.clone(),
built.service_id,
id,
active_deployment_getter.clone(),
kill_send,
);
Expand Down
2 changes: 1 addition & 1 deletion e2e/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dev-dependencies]
crossterm = "0.23.2"
crossterm = "0.25.0"
lazy_static = "1.4.0"
portpicker = "0.1.1"
rand = "0.8.5"
Expand Down
4 changes: 2 additions & 2 deletions e2e/tests/integration/salvo.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use colored::Color;
use crossterm::style::Color;

use crate::helpers::{self, APPS_FQDN};

#[test]
fn hello_world_salvo() {
let client = helpers::Services::new_docker("hello-world (salvo)", Color::Cyan);
let client = helpers::Services::new_docker("hello-world (salvo)", Color::DarkRed);
client.deploy("salvo/hello-world");

let request_text = client
Expand Down
6 changes: 3 additions & 3 deletions gateway/src/api/latest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ pub mod tests {

let (sender, mut receiver) = channel::<Work>(256);
tokio::spawn(async move {
while let Some(_) = receiver.recv().await {
while receiver.recv().await.is_some() {
// do not do any work with inbound requests
}
});
Expand Down Expand Up @@ -322,7 +322,7 @@ pub mod tests {

let (sender, mut receiver) = channel::<Work>(256);
tokio::spawn(async move {
while let Some(_) = receiver.recv().await {
while receiver.recv().await.is_some() {
// do not do any work with inbound requests
}
});
Expand Down Expand Up @@ -417,7 +417,7 @@ pub mod tests {
// do not process until instructed
ctl_recv.await.unwrap();

while let Some(_) = receiver.recv().await {
while receiver.recv().await.is_some() {
done_send.take().unwrap().send(()).unwrap();
// do nothing
}
Expand Down
16 changes: 8 additions & 8 deletions gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::json;
use tracing::error;
use tokio::sync::mpsc::error::SendError;
use tracing::error;

pub mod api;
pub mod args;
Expand Down Expand Up @@ -169,7 +169,7 @@ impl<'de> Deserialize<'de> for ProjectName {
{
String::deserialize(deserializer)?
.parse()
.map_err(|err| <D::Error as serde::de::Error>::custom(err))
.map_err(<D::Error as serde::de::Error>::custom)
}
}

Expand Down Expand Up @@ -565,10 +565,10 @@ pub mod tests {
);

let image = env::var("SHUTTLE_TESTS_RUNTIME_IMAGE")
.unwrap_or("public.ecr.aws/shuttle/deployer:latest".to_string());
.unwrap_or_else(|_| "public.ecr.aws/shuttle/deployer:latest".to_string());

let network_name =
env::var("SHUTTLE_TESTS_NETWORK").unwrap_or("shuttle_default".to_string());
env::var("SHUTTLE_TESTS_NETWORK").unwrap_or_else(|_| "shuttle_default".to_string());

let provisioner_host = "provisioner".to_string();

Expand Down Expand Up @@ -611,7 +611,7 @@ pub mod tests {
}

impl World {
pub fn context<'c>(&'c self) -> WorldContext<'c> {
pub fn context(&self) -> WorldContext {
WorldContext {
docker: &self.docker,
container_settings: &self.settings,
Expand Down Expand Up @@ -658,12 +658,12 @@ pub mod tests {
let api = make_api(Arc::clone(&service), log_out);
let api_addr = format!("127.0.0.1:{}", base_port).parse().unwrap();
let serve_api = hyper::Server::bind(&api_addr).serve(api.into_make_service());
let api_client = world.client(api_addr.clone());
let api_client = world.client(api_addr);

let proxy = make_proxy(Arc::clone(&service));
let proxy_addr = format!("127.0.0.1:{}", base_port + 1).parse().unwrap();
let serve_proxy = hyper::Server::bind(&proxy_addr).serve(proxy);
let proxy_client = world.client(proxy_addr.clone());
let proxy_client = world.client(proxy_addr);

let _gateway = tokio::spawn(async move {
tokio::select! {
Expand Down Expand Up @@ -705,7 +705,7 @@ pub mod tests {
.await
.unwrap();

let _ = timed_loop!(wait: 1, max: 12, {
timed_loop!(wait: 1, max: 12, {
let project: project::Response = api_client
.request(
Request::get("/projects/matrix")
Expand Down
2 changes: 1 addition & 1 deletion gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ async fn start(db: SqlitePool, args: StartArgs) -> io::Result<()> {

let proxy_handle = tokio::spawn(hyper::Server::bind(&args.user).serve(proxy));

let _ = tokio::select!(
tokio::select!(
_ = worker_handle => info!("worker handle finished"),
_ = api_handle => info!("api handle finished"),
_ = proxy_handle => info!("proxy handle finished"),
Expand Down
10 changes: 5 additions & 5 deletions gateway/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ impl Project {

pub fn target_ip(&self) -> Result<Option<IpAddr>, Error> {
match self.clone() {
Self::Ready(project_ready) => Ok(Some(project_ready.target_ip().clone())),
Self::Ready(project_ready) => Ok(Some(*project_ready.target_ip())),
_ => Ok(None), // not ready
}
}
Expand Down Expand Up @@ -522,7 +522,7 @@ impl ProjectReady {
}
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Service {
name: String,
target: IpAddr,
Expand Down Expand Up @@ -603,12 +603,12 @@ impl<'c> State<'c> for ProjectDestroying {
async fn next<C: Context<'c>>(self, ctx: &C) -> Result<Self::Next, Self::Error> {
let container_id = self.container.id.as_ref().unwrap();
ctx.docker()
.stop_container(&container_id, Some(StopContainerOptions { t: 1 }))
.stop_container(container_id, Some(StopContainerOptions { t: 1 }))
.await
.unwrap_or(());
ctx.docker()
.remove_container(
&container_id,
container_id,
Some(RemoveContainerOptions {
force: true,
..Default::default()
Expand Down Expand Up @@ -637,7 +637,7 @@ impl<'c> State<'c> for ProjectDestroyed {
}
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProjectErrorKind {
Internal,
}
Expand Down
6 changes: 3 additions & 3 deletions gateway/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use tower::Service;
use crate::service::GatewayService;
use crate::{Error, ErrorKind, ProjectName};

const SHUTTLEAPP_SUFFIX: &'static str = ".shuttleapp.rs";
const SHUTTLEAPP_SUFFIX: &str = ".shuttleapp.rs";
static PROXY_CLIENT: Lazy<ReverseProxy<HttpConnector<GaiResolver>>> =
Lazy::new(|| ReverseProxy::new(Client::new()));

Expand All @@ -39,7 +39,7 @@ impl Service<Request<Body>> for ProxyService {
}

fn call(&mut self, req: Request<Body>) -> Self::Future {
let remote_addr = self.remote_addr.ip().clone();
let remote_addr = self.remote_addr.ip();
let gateway = Arc::clone(&self.gateway);
Box::pin(
async move {
Expand All @@ -48,7 +48,7 @@ impl Service<Request<Body>> for ProxyService {
.get("Host")
.map(|head| head.to_str().unwrap())
.and_then(|host| {
host.strip_suffix(".")
host.strip_suffix('.')
.unwrap_or(host)
.strip_suffix(SHUTTLEAPP_SUFFIX)
})
Expand Down
22 changes: 10 additions & 12 deletions gateway/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,7 @@ impl<'d> ContainerSettingsBuilder<'d> {
}
})
})
.expect(&format!(
"cannot find a Docker network with name=`{network_name}`"
))
.unwrap_or_else(|| panic!("cannot find a Docker network with name=`{network_name}`"))
}

pub async fn build(mut self) -> ContainerSettings {
Expand Down Expand Up @@ -145,7 +143,7 @@ pub struct ContainerSettings {
}

impl ContainerSettings {
pub fn builder<'d>(docker: &'d Docker) -> ContainerSettingsBuilder<'d> {
pub fn builder(docker: &Docker) -> ContainerSettingsBuilder {
ContainerSettingsBuilder::new(docker)
}
}
Expand All @@ -160,7 +158,7 @@ impl GatewayContextProvider {
Self { docker, settings }
}

pub fn context<'c>(&'c self) -> GatewayContext {
pub fn context(&self) -> GatewayContext {
GatewayContext {
docker: &self.docker,
settings: &self.settings,
Expand Down Expand Up @@ -324,17 +322,17 @@ impl GatewayService {
.bind(&key)
.execute(&self.db)
.await
.or_else(|err| {
.map_err(|err| {
// If the error is a broken PK constraint, this is a
// project name clash
if let Some(db_err) = err.as_database_error() {
if db_err.code().unwrap() == "1555" {
// SQLITE_CONSTRAINT_PRIMARYKEY
return Err(Error::from_kind(ErrorKind::UserAlreadyExists));
return Error::from_kind(ErrorKind::UserAlreadyExists);
}
}
// Otherwise this is internal
return Err(err.into());
err.into()
})?;
Ok(User {
name,
Expand Down Expand Up @@ -399,16 +397,16 @@ impl GatewayService {
.bind(&project)
.execute(&self.db)
.await
.or_else(|err| {
.map_err(|err| {
// If the error is a broken PK constraint, this is a
// project name clash
if let Some(db_err_code) = err.as_database_error().and_then(DatabaseError::code) {
if db_err_code == "1555" { // SQLITE_CONSTRAINT_PRIMARYKEY
return Err(Error::from_kind(ErrorKind::ProjectAlreadyExists))
return Error::from_kind(ErrorKind::ProjectAlreadyExists)
}
}
// Otherwise this is internal
return Err(err.into())
err.into()
})?;

let project = project.0;
Expand All @@ -434,7 +432,7 @@ impl GatewayService {
})
}

fn context<'c>(&'c self) -> GatewayContext<'c> {
fn context(&self) -> GatewayContext {
self.provider.context()
}
}
Expand Down
13 changes: 7 additions & 6 deletions gateway/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use tracing::info;

use crate::project::Project;
use crate::service::GatewayService;
use crate::{
AccountName, Context, EndState, Error, ProjectName, Refresh, Service, State,
};
use crate::{AccountName, Context, EndState, Error, ProjectName, Refresh, Service, State};

#[must_use]
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -152,13 +150,16 @@ pub mod tests {

pub struct DummyService<S> {
world: World,
state: Mutex<Option<S>>
state: Mutex<Option<S>>,
}

impl DummyService<()> {
pub async fn new<S>() -> DummyService<S> {
let world = World::new().await;
DummyService { world, state: Mutex::new(None) }
DummyService {
world,
state: Mutex::new(None),
}
}
}

Expand All @@ -184,7 +185,7 @@ pub mod tests {
}
}

#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct FiniteState {
count: usize,
max_count: usize,
Expand Down
5 changes: 2 additions & 3 deletions service/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ fn get_config(writer: PipeWriter) -> anyhow::Result<Config> {

/// Get options to compile in build mode
fn get_compile_options(config: &Config) -> anyhow::Result<CompileOptions> {
let mut opts = CompileOptions::new(&config, CompileMode::Build)?;
let mut opts = CompileOptions::new(config, CompileMode::Build)?;
opts.build_config.message_format = MessageFormat::Json {
render_diagnostics: false,
short: false,
Expand Down Expand Up @@ -220,8 +220,7 @@ fn check_version(summary: &Summary) -> anyhow::Result<()> {
let version_req = summary
.dependencies()
.iter()
.filter(|dependency| dependency.package_name() == NAME)
.next()
.find(|dependency| dependency.package_name() == NAME)
.unwrap()
.version_req();

Expand Down
8 changes: 5 additions & 3 deletions service/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ where
state: State::Running,
level: metadata.level().into(),
timestamp: datetime,
file: visitor.file.or(metadata.file().map(str::to_string)),
line: visitor.line.or(metadata.line()),
target: visitor.target.unwrap_or(metadata.target().to_string()),
file: visitor.file.or_else(|| metadata.file().map(str::to_string)),
line: visitor.line.or_else(|| metadata.line()),
target: visitor
.target
.unwrap_or_else(|| metadata.target().to_string()),
fields: serde_json::to_vec(&visitor.fields).unwrap(),
}
};
Expand Down

0 comments on commit 280197d

Please sign in to comment.