Skip to content

Commit a824e84

Browse files
authored
Cleanup format arguments (#2650)
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 ```
1 parent 9463b75 commit a824e84

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

80 files changed

+270
-307
lines changed

examples/mysql/todos/src/main.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
2121

2222
match args.cmd {
2323
Some(Command::Add { description }) => {
24-
println!("Adding new todo with description '{}'", &description);
24+
println!("Adding new todo with description '{description}'");
2525
let todo_id = add_todo(&pool, description).await?;
26-
println!("Added new todo with id {}", todo_id);
26+
println!("Added new todo with id {todo_id}");
2727
}
2828
Some(Command::Done { id }) => {
29-
println!("Marking todo {} as done", id);
29+
println!("Marking todo {id} as done");
3030
if complete_todo(&pool, id).await? {
31-
println!("Todo {} is marked as done", id);
31+
println!("Todo {id} is marked as done");
3232
} else {
33-
println!("Invalid id {}", id);
33+
println!("Invalid id {id}");
3434
}
3535
}
3636
None => {

examples/postgres/axum-social-with-tests/src/http/error.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ impl IntoResponse for Error {
4949

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

5454
(
5555
self.status_code(),

examples/postgres/axum-social-with-tests/tests/common.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,20 @@ pub async fn response_json(resp: &mut Response<BoxBody>) -> serde_json::Value {
5353
pub fn expect_string(value: &serde_json::Value) -> &str {
5454
value
5555
.as_str()
56-
.unwrap_or_else(|| panic!("expected string, got {:?}", value))
56+
.unwrap_or_else(|| panic!("expected string, got {value:?}"))
5757
}
5858

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

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

7070
OffsetDateTime::parse(s, &Rfc3339)
71-
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {:?}: {}", value, e))
71+
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {value:?}: {e}"))
7272
}

examples/postgres/chat/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
157157
terminal.show_cursor()?;
158158

159159
if let Err(err) = res {
160-
println!("{:?}", err)
160+
println!("{err:?}")
161161
}
162162

163163
Ok(())

examples/postgres/files/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ async fn main() -> anyhow::Result<()> {
4141
.await?;
4242

4343
for post_with_author in posts_with_authors {
44-
println!("{}", post_with_author);
44+
println!("{post_with_author}");
4545
}
4646

4747
Ok(())

examples/postgres/json/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ async fn main() -> anyhow::Result<()> {
4747
);
4848

4949
let person_id = add_person(&pool, person).await?;
50-
println!("Added new person with ID {}", person_id);
50+
println!("Added new person with ID {person_id}");
5151
}
5252
None => {
5353
println!("Printing all people");

examples/postgres/listen/src/main.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
3838
let mut counter = 0usize;
3939
loop {
4040
let notification = listener.recv().await?;
41-
println!("[from recv]: {:?}", notification);
41+
println!("[from recv]: {notification:?}");
4242

4343
counter += 1;
4444
if counter >= 3 {
@@ -58,7 +58,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
5858
tokio::select! {
5959
res = stream.try_next() => {
6060
if let Some(notification) = res? {
61-
println!("[from stream]: {:?}", notification);
61+
println!("[from stream]: {notification:?}");
6262
} else {
6363
break;
6464
}
@@ -106,5 +106,5 @@ from (
106106
.execute(pool)
107107
.await;
108108

109-
println!("[from notify]: {:?}", res);
109+
println!("[from notify]: {res:?}");
110110
}

examples/postgres/mockable-todos/src/main.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,14 @@ async fn handle_command(
3939
&description
4040
)?;
4141
let todo_id = todo_repo.add_todo(description).await?;
42-
writeln!(writer, "Added new todo with id {}", todo_id)?;
42+
writeln!(writer, "Added new todo with id {todo_id}")?;
4343
}
4444
Some(Command::Done { id }) => {
45-
writeln!(writer, "Marking todo {} as done", id)?;
45+
writeln!(writer, "Marking todo {id} as done")?;
4646
if todo_repo.complete_todo(id).await? {
47-
writeln!(writer, "Todo {} is marked as done", id)?;
47+
writeln!(writer, "Todo {id} is marked as done")?;
4848
} else {
49-
writeln!(writer, "Invalid id {}", id)?;
49+
writeln!(writer, "Invalid id {id}")?;
5050
}
5151
}
5252
None => {

examples/postgres/todos/src/main.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
2121

2222
match args.cmd {
2323
Some(Command::Add { description }) => {
24-
println!("Adding new todo with description '{}'", &description);
24+
println!("Adding new todo with description '{description}'");
2525
let todo_id = add_todo(&pool, description).await?;
26-
println!("Added new todo with id {}", todo_id);
26+
println!("Added new todo with id {todo_id}");
2727
}
2828
Some(Command::Done { id }) => {
29-
println!("Marking todo {} as done", id);
29+
println!("Marking todo {id} as done");
3030
if complete_todo(&pool, id).await? {
31-
println!("Todo {} is marked as done", id);
31+
println!("Todo {id} is marked as done");
3232
} else {
33-
println!("Invalid id {}", id);
33+
println!("Invalid id {id}");
3434
}
3535
}
3636
None => {

examples/sqlite/todos/src/main.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
2121

2222
match args.cmd {
2323
Some(Command::Add { description }) => {
24-
println!("Adding new todo with description '{}'", &description);
24+
println!("Adding new todo with description '{description}'");
2525
let todo_id = add_todo(&pool, description).await?;
26-
println!("Added new todo with id {}", todo_id);
26+
println!("Added new todo with id {todo_id}");
2727
}
2828
Some(Command::Done { id }) => {
29-
println!("Marking todo {} as done", id);
29+
println!("Marking todo {id} as done");
3030
if complete_todo(&pool, id).await? {
31-
println!("Todo {} is marked as done", id);
31+
println!("Todo {id} is marked as done");
3232
} else {
33-
println!("Invalid id {}", id);
33+
println!("Invalid id {id}");
3434
}
3535
}
3636
None => {

sqlx-bench/benches/pg_pool.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ fn bench_pgpool_acquire(c: &mut Criterion) {
1212
let fairness = if fair { "(fair)" } else { "(unfair)" };
1313

1414
group.bench_with_input(
15-
format!("{} concurrent {}", concurrent, fairness),
15+
format!("{concurrent} concurrent {fairness}"),
1616
&(concurrent, fair),
1717
|b, &(concurrent, fair)| do_bench_acquire(b, concurrent, fair),
1818
);
@@ -47,7 +47,7 @@ fn do_bench_acquire(b: &mut Bencher, concurrent: u32, fair: bool) {
4747
let conn = match pool.acquire().await {
4848
Ok(conn) => conn,
4949
Err(sqlx::Error::PoolClosed) => break,
50-
Err(e) => panic!("failed to acquire concurrent connection: {}", e),
50+
Err(e) => panic!("failed to acquire concurrent connection: {e}"),
5151
};
5252

5353
// pretend we're using the connection

sqlx-bench/benches/sqlite_fetch_all.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ fn main() -> sqlx::Result<()> {
3737
);
3838

3939
let elapsed = chrono::Utc::now() - start;
40-
println!("elapsed {}", elapsed);
40+
println!("elapsed {elapsed}");
4141
}
4242

4343
Ok(())

sqlx-cli/src/database.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ fn ask_to_continue(connect_opts: &ConnectOpts) -> bool {
7373
}
7474
}
7575
Err(e) => {
76-
println!("{}", e);
76+
println!("{e}");
7777
return false;
7878
}
7979
}

sqlx-cli/src/migrate.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ impl MigrationOrdering {
4848
}
4949

5050
fn sequential(version: i64) -> MigrationOrdering {
51-
Self::Sequential(format!("{:04}", version))
51+
Self::Sequential(format!("{version:04}"))
5252
}
5353

5454
fn file_prefix(&self) -> &str {
@@ -149,7 +149,7 @@ pub async fn add(
149149

150150
if !has_existing_migrations {
151151
let quoted_source = if migration_source != "migrations" {
152-
format!("{:?}", migration_source)
152+
format!("{migration_source:?}")
153153
} else {
154154
"".to_string()
155155
};
@@ -178,7 +178,7 @@ See: https://docs.rs/sqlx/0.5/sqlx/macro.migrate.html
178178
fn short_checksum(checksum: &[u8]) -> String {
179179
let mut s = String::with_capacity(checksum.len() * 2);
180180
for b in checksum {
181-
write!(&mut s, "{:02x?}", b).expect("should not fail to write to str");
181+
write!(&mut s, "{b:02x?}").expect("should not fail to write to str");
182182
}
183183
s
184184
}
@@ -341,7 +341,7 @@ pub async fn run(
341341
style(migration.version).cyan(),
342342
style(migration.migration_type.label()).green(),
343343
migration.description,
344-
style(format!("({:?})", elapsed)).dim()
344+
style(format!("({elapsed:?})")).dim()
345345
);
346346
}
347347
}
@@ -431,7 +431,7 @@ pub async fn revert(
431431
style(migration.version).cyan(),
432432
style(migration.migration_type.label()).green(),
433433
migration.description,
434-
style(format!("({:?})", elapsed)).dim()
434+
style(format!("({elapsed:?})")).dim()
435435
);
436436

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

475474
fs::write("build.rs", contents)?;

sqlx-cli/src/migration.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub fn add_file(name: &str) -> anyhow::Result<()> {
3030
file.write_all(b"-- Add migration script here")
3131
.context("Could not write to file")?;
3232

33-
println!("Created migration: '{}'", file_name);
33+
println!("Created migration: '{file_name}'");
3434
Ok(())
3535
}
3636

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

144144
if let Some(ext) = e.path().extension() {
145145
if ext != "sql" {
146-
println!("Wrong ext: {:?}", ext);
146+
println!("Wrong ext: {ext:?}");
147147
continue;
148148
}
149149
} else {

sqlx-cli/src/prepare.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ fn minimal_project_clean(
252252
for file in touch_paths {
253253
let now = filetime::FileTime::now();
254254
filetime::set_file_times(&file, now, now)
255-
.with_context(|| format!("Failed to update mtime for {:?}", file))?;
255+
.with_context(|| format!("Failed to update mtime for {file:?}"))?;
256256
}
257257

258258
// Clean entire packages.

sqlx-core/src/any/driver.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,6 @@ pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> {
139139
.iter()
140140
.find(|driver| driver.url_schemes.contains(&url.scheme()))
141141
.ok_or_else(|| {
142-
Error::Configuration(format!("no driver found for URL scheme {:?}", scheme).into())
142+
Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into())
143143
})
144144
}

sqlx-core/src/any/kind.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl FromStr for AnyKind {
6161
Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into()))
6262
}
6363

64-
_ => Err(Error::Configuration(format!("unrecognized database url: {:?}", url).into()))
64+
_ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into()))
6565
}
6666
}
6767
}

sqlx-core/src/any/row.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl Row for AnyRow {
6060
T::decode(value)
6161
}
6262
.map_err(|source| Error::ColumnDecode {
63-
index: format!("{:?}", index),
63+
index: format!("{index:?}"),
6464
source,
6565
})
6666
}

sqlx-core/src/describe.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,7 @@ impl<DB: Database> Describe<DB> {
8080
AnyTypeInfo::try_from(type_info).map_err(|_| {
8181
crate::Error::AnyDriverError(
8282
format!(
83-
"Any driver does not support type {} of parameter {}",
84-
type_info, i
83+
"Any driver does not support type {type_info} of parameter {i}"
8584
)
8685
.into(),
8786
)

sqlx-core/src/error.rs

+3-10
Original file line numberDiff line numberDiff line change
@@ -253,10 +253,7 @@ impl dyn DatabaseError {
253253
/// specific error type. In other cases, use `try_downcast_ref`.
254254
pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
255255
self.try_downcast_ref().unwrap_or_else(|| {
256-
panic!(
257-
"downcast to wrong DatabaseError type; original error: {}",
258-
self
259-
)
256+
panic!("downcast to wrong DatabaseError type; original error: {self}")
260257
})
261258
}
262259

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

279272
/// Downcast a reference to this generic database error to a specific

sqlx-core/src/executor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ pub trait Execute<'q, DB: Database>: Send + Sized {
202202
}
203203

204204
// NOTE: `Execute` is explicitly not implemented for String and &String to make it slightly more
205-
// involved to write `conn.execute(format!("SELECT {}", val))`
205+
// involved to write `conn.execute(format!("SELECT {val}"))`
206206
impl<'q, DB: Database> Execute<'q, DB> for &'q str {
207207
#[inline]
208208
fn sql(&self) -> &'q str {

sqlx-core/src/query_builder.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ where
116116
pub fn push(&mut self, sql: impl Display) -> &mut Self {
117117
self.sanity_check();
118118

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

121121
self
122122
}
@@ -258,9 +258,9 @@ where
258258
/// // This would normally produce values forever!
259259
/// let users = (0..).map(|i| User {
260260
/// id: i,
261-
/// username: format!("test_user_{}", i),
262-
/// email: format!("test-user-{}@example.com", i),
263-
/// password: format!("Test!User@Password#{}", i),
261+
/// username: format!("test_user_{i}"),
262+
/// email: format!("test-user-{i}@example.com"),
263+
/// password: format!("Test!User@Password#{i}"),
264264
/// });
265265
///
266266
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(
@@ -365,9 +365,9 @@ where
365365
/// // This would normally produce values forever!
366366
/// let users = (0..).map(|i| User {
367367
/// id: i,
368-
/// username: format!("test_user_{}", i),
369-
/// email: format!("test-user-{}@example.com", i),
370-
/// password: format!("Test!User@Password#{}", i),
368+
/// username: format!("test_user_{i}"),
369+
/// email: format!("test-user-{i}@example.com"),
370+
/// password: format!("Test!User@Password#{i}"),
371371
/// });
372372
///
373373
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(

0 commit comments

Comments
 (0)