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
```
This commit is contained in:
Yuri Astrakhan
2023-07-31 22:27:04 +02:00
committed by GitHub
parent 9463b7592f
commit a824e8468c
80 changed files with 270 additions and 307 deletions

View File

@@ -302,9 +302,9 @@ impl PgAdvisoryLock {
fn get_release_query(&self) -> &str {
self.release_query.get_or_init(|| match &self.key {
PgAdvisoryLockKey::BigInt(key) => format!("SELECT pg_advisory_unlock({})", key),
PgAdvisoryLockKey::BigInt(key) => format!("SELECT pg_advisory_unlock({key})"),
PgAdvisoryLockKey::IntPair(key1, key2) => {
format!("SELECT pg_advisory_unlock({}, {})", key1, key2)
format!("SELECT pg_advisory_unlock({key1}, {key2})")
}
})
}

View File

@@ -143,8 +143,7 @@ impl AnyConnectionBackend for PgConnection {
AnyTypeInfo::try_from(type_info).map_err(|_| {
sqlx_core::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(),
)
@@ -181,11 +180,7 @@ impl<'a> TryFrom<&'a PgTypeInfo> for AnyTypeInfo {
PgType::Text => AnyTypeInfoKind::Text,
_ => {
return Err(sqlx_core::Error::AnyDriverError(
format!(
"Any driver does not support the Postgres type {:?}",
pg_type
)
.into(),
format!("Any driver does not support the Postgres type {pg_type:?}").into(),
))
}
},

View File

@@ -50,7 +50,7 @@ pub(crate) async fn authenticate(
}
// channel-binding = "c=" base64
let mut channel_binding = format!("{}=", CHANNEL_ATTR);
let mut channel_binding = format!("{CHANNEL_ATTR}=");
BASE64_STANDARD.encode_string(GS2_HEADER, &mut channel_binding);
// "n=" saslname ;; Usernames are prepared using SASLprep.
@@ -65,14 +65,9 @@ pub(crate) async fn authenticate(
let nonce = gen_nonce();
// client-first-message-bare = [reserved-mext ","] username "," nonce ["," extensions]
let client_first_message_bare =
format!("{username},{nonce}", username = username, nonce = nonce);
let client_first_message_bare = format!("{username},{nonce}");
let client_first_message = format!(
"{gs2_header}{client_first_message_bare}",
gs2_header = GS2_HEADER,
client_first_message_bare = client_first_message_bare
);
let client_first_message = format!("{GS2_HEADER}{client_first_message_bare}");
stream
.send(SaslInitialResponse {
@@ -147,11 +142,7 @@ pub(crate) async fn authenticate(
mac.update(&auth_message.as_bytes());
// client-final-message = client-final-message-without-proof "," proof
let mut client_final_message = format!(
"{client_final_message_wo_proof},{client_proof_attr}=",
client_final_message_wo_proof = client_final_message_wo_proof,
client_proof_attr = CLIENT_PROOF_ATTR,
);
let mut client_final_message = format!("{client_final_message_wo_proof},{CLIENT_PROOF_ATTR}=");
BASE64_STANDARD.encode_string(client_proof, &mut client_final_message);
stream.send(SaslResponse(&client_final_message)).await?;
@@ -194,7 +185,7 @@ fn gen_nonce() -> String {
.collect();
rng.gen_range(32..128);
format!("{}={}", NONCE_ATTR, nonce)
format!("{NONCE_ATTR}={nonce}")
}
// Hi(str, salt, i):

View File

@@ -476,7 +476,7 @@ impl PgConnectOptions {
options_str.push(' ');
}
write!(options_str, "-c {}={}", k, v).expect("failed to write an option to the string");
write!(options_str, "-c {k}={v}").expect("failed to write an option to the string");
}
self
}
@@ -500,7 +500,7 @@ impl PgConnectOptions {
fn default_host(port: u16) -> String {
// try to check for the existence of a unix socket and uses that
let socket = format!(".s.PGSQL.{}", port);
let socket = format!(".s.PGSQL.{port}");
let candidates = [
"/var/run/postgresql", // Debian
"/private/tmp", // OSX (homebrew)

View File

@@ -55,7 +55,7 @@ fn load_password_from_file(
if mode & 0o77 != 0 {
tracing::warn!(
path = %path.to_string_lossy(),
permissions = format!("{:o}", mode),
permissions = format!("{mode:o}"),
"Ignoring path. Permissions are not strict enough",
);
return None;

View File

@@ -48,7 +48,7 @@ impl FromStr for PgSslMode {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `ssl_mode`", s).into(),
format!("unknown value {s:?} for `ssl_mode`").into(),
));
}
})

View File

@@ -40,7 +40,7 @@ impl TestSupport for Postgres {
.acquire()
.await?;
conn.execute(&format!("drop database if exists {0:?};", db_name)[..])
conn.execute(&format!("drop database if exists {db_name:?};")[..])
.await?;
query("delete from _sqlx_test.databases where db_name = $1")
@@ -161,7 +161,7 @@ async fn test_context(args: &TestArgs) -> Result<TestContext<Postgres>, Error> {
.fetch_one(&mut *conn)
.await?;
conn.execute(&format!("create database {:?}", new_db_name)[..])
conn.execute(&format!("create database {new_db_name:?}")[..])
.await?;
Ok(TestContext {
@@ -204,14 +204,14 @@ async fn do_cleanup(conn: &mut PgConnection, created_before: Duration) -> Result
for db_name in delete_db_names {
command.clear();
writeln!(command, "drop database if exists {:?};", db_name).ok();
writeln!(command, "drop database if exists {db_name:?};").ok();
match conn.execute(&*command).await {
Ok(_deleted) => {
deleted_db_names.push(db_name);
}
// Assume a database error just means the DB is still in use.
Err(Error::Database(dbe)) => {
eprintln!("could not clean test database {:?}: {}", db_name, dbe)
eprintln!("could not clean test database {db_name:?}: {dbe}")
}
// Bubble up other errors
Err(e) => return Err(e),

View File

@@ -768,7 +768,7 @@ impl PgType {
unreachable!("(bug) use of unresolved type declaration [oid={}]", oid.0);
}
PgType::DeclareWithName(name) => {
unreachable!("(bug) use of unresolved type declaration [name={}]", name);
unreachable!("(bug) use of unresolved type declaration [name={name}]");
}
}
}
@@ -887,7 +887,7 @@ impl PgType {
unreachable!("(bug) use of unresolved type declaration [oid={}]", oid.0);
}
PgType::DeclareWithName(name) => {
unreachable!("(bug) use of unresolved type declaration [name={}]", name);
unreachable!("(bug) use of unresolved type declaration [name={name}]");
}
}
}

View File

@@ -196,7 +196,7 @@ where
}
if ndim != 1 {
return Err(format!("encountered an array of {} dimensions; only one-dimensional arrays are supported", ndim).into());
return Err(format!("encountered an array of {ndim} dimensions; only one-dimensional arrays are supported").into());
}
// appears to have been used in the past to communicate potential NULLS
@@ -222,7 +222,7 @@ where
let lower = buf.get_i32();
if lower != 1 {
return Err(format!("encountered an array with a lower bound of {} in the first dimension; only arrays starting at one are supported", lower).into());
return Err(format!("encountered an array with a lower bound of {lower} in the first dimension; only arrays starting at one are supported").into());
}
let mut elements = Vec::with_capacity(len as usize);

View File

@@ -34,7 +34,7 @@ impl Decode<'_, Postgres> for bool {
"f" => false,
s => {
return Err(format!("unexpected value {:?} for boolean", s).into());
return Err(format!("unexpected value {s:?} for boolean").into());
}
},
})

View File

@@ -38,7 +38,7 @@ impl Encode<'_, Postgres> for NaiveDateTime {
// TIMESTAMP is encoded as the microseconds since the epoch
let us = (*self - postgres_epoch_datetime())
.num_microseconds()
.unwrap_or_else(|| panic!("NaiveDateTime out of range for Postgres: {:?}", self));
.unwrap_or_else(|| panic!("NaiveDateTime out of range for Postgres: {self:?}"));
Encode::<Postgres>::encode(&us, buf)
}

View File

@@ -112,7 +112,7 @@ impl Decode<'_, Postgres> for IpNetwork {
}
_ => {
return Err(format!("unknown ip family {}", family).into());
return Err(format!("unknown ip family {family}").into());
}
}
}

View File

@@ -114,9 +114,9 @@ impl Display for PgLQuery {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut iter = self.levels.iter();
if let Some(label) = iter.next() {
write!(f, "{}", label)?;
write!(f, "{label}")?;
for label in iter {
write!(f, ".{}", label)?;
write!(f, ".{label}")?;
}
}
Ok(())
@@ -141,7 +141,7 @@ impl Type<Postgres> for PgLQuery {
impl Encode<'_, Postgres> for PgLQuery {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
buf.extend(1i8.to_le_bytes());
write!(buf, "{}", self)
write!(buf, "{self}")
.expect("Display implementation panicked while writing to PgArgumentBuffer");
IsNull::No
@@ -288,7 +288,7 @@ fn write_variants(f: &mut Formatter<'_>, variants: &[PgLQueryVariant], not: bool
if let Some(variant) = iter.next() {
write!(f, "{}{}", if not { "!" } else { "" }, variant)?;
for variant in iter {
write!(f, ".{}", variant)?;
write!(f, ".{variant}")?;
}
}
Ok(())
@@ -299,13 +299,13 @@ impl Display for PgLQueryLevel {
match self {
PgLQueryLevel::Star(Some(at_least), Some(at_most)) => {
if at_least == at_most {
write!(f, "*{{{}}}", at_least)
write!(f, "*{{{at_least}}}")
} else {
write!(f, "*{{{},{}}}", at_least, at_most)
write!(f, "*{{{at_least},{at_most}}}")
}
}
PgLQueryLevel::Star(Some(at_least), _) => write!(f, "*{{{},}}", at_least),
PgLQueryLevel::Star(_, Some(at_most)) => write!(f, "*{{,{}}}", at_most),
PgLQueryLevel::Star(Some(at_least), _) => write!(f, "*{{{at_least},}}"),
PgLQueryLevel::Star(_, Some(at_most)) => write!(f, "*{{,{at_most}}}"),
PgLQueryLevel::Star(_, _) => write!(f, "*"),
PgLQueryLevel::NonStar(variants) => write_variants(f, &variants, false),
PgLQueryLevel::NotNonStar(variants) => write_variants(f, &variants, true),

View File

@@ -150,9 +150,9 @@ impl Display for PgLTree {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut iter = self.labels.iter();
if let Some(label) = iter.next() {
write!(f, "{}", label)?;
write!(f, "{label}")?;
for label in iter {
write!(f, ".{}", label)?;
write!(f, ".{label}")?;
}
}
Ok(())
@@ -183,7 +183,7 @@ impl PgHasArrayType for PgLTree {
impl Encode<'_, Postgres> for PgLTree {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
buf.extend(1i8.to_le_bytes());
write!(buf, "{}", self)
write!(buf, "{self}")
.expect("Display implementation panicked while writing to PgArgumentBuffer");
IsNull::No

View File

@@ -69,7 +69,7 @@ impl PgNumericSign {
SIGN_NAN => unreachable!("sign value for NaN passed to PgNumericSign"),
_ => Err(format!("invalid value for PgNumericSign: {:#04X}", val).into()),
_ => Err(format!("invalid value for PgNumericSign: {val:#04X}").into()),
}
}
}

View File

@@ -480,8 +480,7 @@ fn parse_bound<T>(ch: char, value: Option<T>) -> Result<Bound<T>, BoxDynError> {
_ => {
return Err(format!(
"expected `(`, ')', '[', or `]` but found `{}` for range literal",
ch
"expected `(`, ')', '[', or `]` but found `{ch}` for range literal"
)
.into());
}
@@ -498,14 +497,14 @@ where
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.start {
Bound::Unbounded => f.write_str("(,")?,
Bound::Excluded(v) => write!(f, "({},", v)?,
Bound::Included(v) => write!(f, "[{},", v)?,
Bound::Excluded(v) => write!(f, "({v},")?,
Bound::Included(v) => write!(f, "[{v},")?,
}
match &self.end {
Bound::Unbounded => f.write_str(")")?,
Bound::Excluded(v) => write!(f, "{})", v)?,
Bound::Included(v) => write!(f, "{}]", v)?,
Bound::Excluded(v) => write!(f, "{v})")?,
Bound::Included(v) => write!(f, "{v}]")?,
}
Ok(())

View File

@@ -62,7 +62,7 @@ impl<'r> Decode<'r, Postgres> for PrimitiveDateTime {
let s = if s.contains('.') {
Cow::Borrowed(s)
} else {
Cow::Owned(format!("{}.0", s))
Cow::Owned(format!("{s}.0"))
};
// Contains a time-zone specifier