Skip to content

Commit

Permalink
Cleanup format arguments (#2650)
Browse files Browse the repository at this point in the history
Inlined format args make code more readable, and code more compact.

I ran this clippy command to fix most cases, and then cleaned up a few trailing commas and uncaught edge cases.

```
cargo clippy --bins --examples  --benches --tests --lib --workspace --fix -- -A clippy::all -W clippy::uninlined_format_args
```
  • Loading branch information
nyurik committed Jul 31, 2023
1 parent 9463b75 commit a824e84
Show file tree
Hide file tree
Showing 80 changed files with 270 additions and 307 deletions.
10 changes: 5 additions & 5 deletions examples/mysql/todos/src/main.rs
Expand Up @@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {

match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/axum-social-with-tests/src/http/error.rs
Expand Up @@ -49,7 +49,7 @@ impl IntoResponse for Error {

// Normally you wouldn't just print this, but it's useful for debugging without
// using a logging framework.
println!("API error: {:?}", self);
println!("API error: {self:?}");

(
self.status_code(),
Expand Down
6 changes: 3 additions & 3 deletions examples/postgres/axum-social-with-tests/tests/common.rs
Expand Up @@ -53,20 +53,20 @@ pub async fn response_json(resp: &mut Response<BoxBody>) -> serde_json::Value {
pub fn expect_string(value: &serde_json::Value) -> &str {
value
.as_str()
.unwrap_or_else(|| panic!("expected string, got {:?}", value))
.unwrap_or_else(|| panic!("expected string, got {value:?}"))
}

#[track_caller]
pub fn expect_uuid(value: &serde_json::Value) -> Uuid {
expect_string(value)
.parse::<Uuid>()
.unwrap_or_else(|e| panic!("failed to parse UUID from {:?}: {}", value, e))
.unwrap_or_else(|e| panic!("failed to parse UUID from {value:?}: {e}"))
}

#[track_caller]
pub fn expect_rfc3339_timestamp(value: &serde_json::Value) -> OffsetDateTime {
let s = expect_string(value);

OffsetDateTime::parse(s, &Rfc3339)
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {:?}: {}", value, e))
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {value:?}: {e}"))
}
2 changes: 1 addition & 1 deletion examples/postgres/chat/src/main.rs
Expand Up @@ -157,7 +157,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
terminal.show_cursor()?;

if let Err(err) = res {
println!("{:?}", err)
println!("{err:?}")
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/files/src/main.rs
Expand Up @@ -41,7 +41,7 @@ async fn main() -> anyhow::Result<()> {
.await?;

for post_with_author in posts_with_authors {
println!("{}", post_with_author);
println!("{post_with_author}");
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/postgres/json/src/main.rs
Expand Up @@ -47,7 +47,7 @@ async fn main() -> anyhow::Result<()> {
);

let person_id = add_person(&pool, person).await?;
println!("Added new person with ID {}", person_id);
println!("Added new person with ID {person_id}");
}
None => {
println!("Printing all people");
Expand Down
6 changes: 3 additions & 3 deletions examples/postgres/listen/src/main.rs
Expand Up @@ -38,7 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut counter = 0usize;
loop {
let notification = listener.recv().await?;
println!("[from recv]: {:?}", notification);
println!("[from recv]: {notification:?}");

counter += 1;
if counter >= 3 {
Expand All @@ -58,7 +58,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::select! {
res = stream.try_next() => {
if let Some(notification) = res? {
println!("[from stream]: {:?}", notification);
println!("[from stream]: {notification:?}");
} else {
break;
}
Expand Down Expand Up @@ -106,5 +106,5 @@ from (
.execute(pool)
.await;

println!("[from notify]: {:?}", res);
println!("[from notify]: {res:?}");
}
8 changes: 4 additions & 4 deletions examples/postgres/mockable-todos/src/main.rs
Expand Up @@ -39,14 +39,14 @@ async fn handle_command(
&description
)?;
let todo_id = todo_repo.add_todo(description).await?;
writeln!(writer, "Added new todo with id {}", todo_id)?;
writeln!(writer, "Added new todo with id {todo_id}")?;
}
Some(Command::Done { id }) => {
writeln!(writer, "Marking todo {} as done", id)?;
writeln!(writer, "Marking todo {id} as done")?;
if todo_repo.complete_todo(id).await? {
writeln!(writer, "Todo {} is marked as done", id)?;
writeln!(writer, "Todo {id} is marked as done")?;
} else {
writeln!(writer, "Invalid id {}", id)?;
writeln!(writer, "Invalid id {id}")?;
}
}
None => {
Expand Down
10 changes: 5 additions & 5 deletions examples/postgres/todos/src/main.rs
Expand Up @@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {

match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {
Expand Down
10 changes: 5 additions & 5 deletions examples/sqlite/todos/src/main.rs
Expand Up @@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {

match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {
Expand Down
4 changes: 2 additions & 2 deletions sqlx-bench/benches/pg_pool.rs
Expand Up @@ -12,7 +12,7 @@ fn bench_pgpool_acquire(c: &mut Criterion) {
let fairness = if fair { "(fair)" } else { "(unfair)" };

group.bench_with_input(
format!("{} concurrent {}", concurrent, fairness),
format!("{concurrent} concurrent {fairness}"),
&(concurrent, fair),
|b, &(concurrent, fair)| do_bench_acquire(b, concurrent, fair),
);
Expand Down Expand Up @@ -47,7 +47,7 @@ fn do_bench_acquire(b: &mut Bencher, concurrent: u32, fair: bool) {
let conn = match pool.acquire().await {
Ok(conn) => conn,
Err(sqlx::Error::PoolClosed) => break,
Err(e) => panic!("failed to acquire concurrent connection: {}", e),
Err(e) => panic!("failed to acquire concurrent connection: {e}"),
};

// pretend we're using the connection
Expand Down
2 changes: 1 addition & 1 deletion sqlx-bench/benches/sqlite_fetch_all.rs
Expand Up @@ -37,7 +37,7 @@ fn main() -> sqlx::Result<()> {
);

let elapsed = chrono::Utc::now() - start;
println!("elapsed {}", elapsed);
println!("elapsed {elapsed}");
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion sqlx-cli/src/database.rs
Expand Up @@ -73,7 +73,7 @@ fn ask_to_continue(connect_opts: &ConnectOpts) -> bool {
}
}
Err(e) => {
println!("{}", e);
println!("{e}");
return false;
}
}
Expand Down
13 changes: 6 additions & 7 deletions sqlx-cli/src/migrate.rs
Expand Up @@ -48,7 +48,7 @@ impl MigrationOrdering {
}

fn sequential(version: i64) -> MigrationOrdering {
Self::Sequential(format!("{:04}", version))
Self::Sequential(format!("{version:04}"))
}

fn file_prefix(&self) -> &str {
Expand Down Expand Up @@ -149,7 +149,7 @@ pub async fn add(

if !has_existing_migrations {
let quoted_source = if migration_source != "migrations" {
format!("{:?}", migration_source)
format!("{migration_source:?}")
} else {
"".to_string()
};
Expand Down Expand Up @@ -178,7 +178,7 @@ See: https://docs.rs/sqlx/0.5/sqlx/macro.migrate.html
fn short_checksum(checksum: &[u8]) -> String {
let mut s = String::with_capacity(checksum.len() * 2);
for b in checksum {
write!(&mut s, "{:02x?}", b).expect("should not fail to write to str");
write!(&mut s, "{b:02x?}").expect("should not fail to write to str");
}
s
}
Expand Down Expand Up @@ -341,7 +341,7 @@ pub async fn run(
style(migration.version).cyan(),
style(migration.migration_type.label()).green(),
migration.description,
style(format!("({:?})", elapsed)).dim()
style(format!("({elapsed:?})")).dim()
);
}
}
Expand Down Expand Up @@ -431,7 +431,7 @@ pub async fn revert(
style(migration.version).cyan(),
style(migration.migration_type.label()).green(),
migration.description,
style(format!("({:?})", elapsed)).dim()
style(format!("({elapsed:?})")).dim()
);

is_applied = true;
Expand Down Expand Up @@ -467,9 +467,8 @@ pub fn build_script(migration_source: &str, force: bool) -> anyhow::Result<()> {
r#"// generated by `sqlx migrate build-script`
fn main() {{
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed={}");
println!("cargo:rerun-if-changed={migration_source}");
}}"#,
migration_source
);

fs::write("build.rs", contents)?;
Expand Down
4 changes: 2 additions & 2 deletions sqlx-cli/src/migration.rs
Expand Up @@ -30,7 +30,7 @@ pub fn add_file(name: &str) -> anyhow::Result<()> {
file.write_all(b"-- Add migration script here")
.context("Could not write to file")?;

println!("Created migration: '{}'", file_name);
println!("Created migration: '{file_name}'");
Ok(())
}

Expand Down Expand Up @@ -143,7 +143,7 @@ fn load_migrations() -> anyhow::Result<Vec<Migration>> {

if let Some(ext) = e.path().extension() {
if ext != "sql" {
println!("Wrong ext: {:?}", ext);
println!("Wrong ext: {ext:?}");
continue;
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion sqlx-cli/src/prepare.rs
Expand Up @@ -252,7 +252,7 @@ fn minimal_project_clean(
for file in touch_paths {
let now = filetime::FileTime::now();
filetime::set_file_times(&file, now, now)
.with_context(|| format!("Failed to update mtime for {:?}", file))?;
.with_context(|| format!("Failed to update mtime for {file:?}"))?;
}

// Clean entire packages.
Expand Down
2 changes: 1 addition & 1 deletion sqlx-core/src/any/driver.rs
Expand Up @@ -139,6 +139,6 @@ pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> {
.iter()
.find(|driver| driver.url_schemes.contains(&url.scheme()))
.ok_or_else(|| {
Error::Configuration(format!("no driver found for URL scheme {:?}", scheme).into())
Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into())
})
}
2 changes: 1 addition & 1 deletion sqlx-core/src/any/kind.rs
Expand Up @@ -61,7 +61,7 @@ impl FromStr for AnyKind {
Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into()))
}

_ => Err(Error::Configuration(format!("unrecognized database url: {:?}", url).into()))
_ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into()))
}
}
}
2 changes: 1 addition & 1 deletion sqlx-core/src/any/row.rs
Expand Up @@ -60,7 +60,7 @@ impl Row for AnyRow {
T::decode(value)
}
.map_err(|source| Error::ColumnDecode {
index: format!("{:?}", index),
index: format!("{index:?}"),
source,
})
}
Expand Down
3 changes: 1 addition & 2 deletions sqlx-core/src/describe.rs
Expand Up @@ -80,8 +80,7 @@ impl<DB: Database> Describe<DB> {
AnyTypeInfo::try_from(type_info).map_err(|_| {
crate::Error::AnyDriverError(
format!(
"Any driver does not support type {} of parameter {}",
type_info, i
"Any driver does not support type {type_info} of parameter {i}"
)
.into(),
)
Expand Down
13 changes: 3 additions & 10 deletions sqlx-core/src/error.rs
Expand Up @@ -253,10 +253,7 @@ impl dyn DatabaseError {
/// specific error type. In other cases, use `try_downcast_ref`.
pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
self.try_downcast_ref().unwrap_or_else(|| {
panic!(
"downcast to wrong DatabaseError type; original error: {}",
self
)
panic!("downcast to wrong DatabaseError type; original error: {self}")
})
}

Expand All @@ -268,12 +265,8 @@ impl dyn DatabaseError {
/// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast`.
pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {
self.try_downcast().unwrap_or_else(|e| {
panic!(
"downcast to wrong DatabaseError type; original error: {}",
e
)
})
self.try_downcast()
.unwrap_or_else(|e| panic!("downcast to wrong DatabaseError type; original error: {e}"))
}

/// Downcast a reference to this generic database error to a specific
Expand Down
2 changes: 1 addition & 1 deletion sqlx-core/src/executor.rs
Expand Up @@ -202,7 +202,7 @@ pub trait Execute<'q, DB: Database>: Send + Sized {
}

// NOTE: `Execute` is explicitly not implemented for String and &String to make it slightly more
// involved to write `conn.execute(format!("SELECT {}", val))`
// involved to write `conn.execute(format!("SELECT {val}"))`
impl<'q, DB: Database> Execute<'q, DB> for &'q str {
#[inline]
fn sql(&self) -> &'q str {
Expand Down
14 changes: 7 additions & 7 deletions sqlx-core/src/query_builder.rs
Expand Up @@ -116,7 +116,7 @@ where
pub fn push(&mut self, sql: impl Display) -> &mut Self {
self.sanity_check();

write!(self.query, "{}", sql).expect("error formatting `sql`");
write!(self.query, "{sql}").expect("error formatting `sql`");

self
}
Expand Down Expand Up @@ -258,9 +258,9 @@ where
/// // This would normally produce values forever!
/// let users = (0..).map(|i| User {
/// id: i,
/// username: format!("test_user_{}", i),
/// email: format!("test-user-{}@example.com", i),
/// password: format!("Test!User@Password#{}", i),
/// username: format!("test_user_{i}"),
/// email: format!("test-user-{i}@example.com"),
/// password: format!("Test!User@Password#{i}"),
/// });
///
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(
Expand Down Expand Up @@ -365,9 +365,9 @@ where
/// // This would normally produce values forever!
/// let users = (0..).map(|i| User {
/// id: i,
/// username: format!("test_user_{}", i),
/// email: format!("test-user-{}@example.com", i),
/// password: format!("Test!User@Password#{}", i),
/// username: format!("test_user_{i}"),
/// email: format!("test-user-{i}@example.com"),
/// password: format!("Test!User@Password#{i}"),
/// });
///
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(
Expand Down

0 comments on commit a824e84

Please sign in to comment.