Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[refactor] Use captured identifiers in format strings #1101

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions network_utils/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl NetworkClient {
pub async fn send_recv_bytes(&self, buf: Vec<u8>) -> Result<SerializedMessage, SuiError> {
match self.send_recv_bytes_internal(buf).await {
Err(error) => Err(SuiError::ClientIoError {
error: format!("{}", error),
error: format!("{error}"),
}),
Ok(Some(response)) => {
// Parse reply
Expand Down Expand Up @@ -106,7 +106,7 @@ impl NetworkClient {
.take_while(|_buf| {
received += 1;
if received % 5000 == 0 && received > 0 {
debug!("Received {}", received);
debug!("Received {received}");
}
let xcontinue = received <= total;
futures::future::ready(xcontinue)
Expand Down Expand Up @@ -215,7 +215,7 @@ pub fn parse_recv_bytes(
) -> Result<SerializedMessage, SuiError> {
match response {
Err(error) => Err(SuiError::ClientIoError {
error: format!("{}", error),
error: format!("{error}"),
}),
Ok(Some(response)) => {
// Parse reply
Expand Down
4 changes: 2 additions & 2 deletions network_utils/src/unit_tests/transport_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ where
Some(Ok(buffer)) => buffer,
Some(Err(err)) => {
// We expect some EOF or disconnect error at the end.
error!("Error while reading TCP stream: {}", err);
error!("Error while reading TCP stream: {err}");
break;
}
None => {
Expand All @@ -53,7 +53,7 @@ where
if let Some(reply) = self.handle_one_message(&buffer[..]).await {
let status = channel.sink().send(reply.into()).await;
if let Err(error) = status {
error!("Failed to send query response: {}", error);
error!("Failed to send query response: {error}");
}
};
}
Expand Down
6 changes: 3 additions & 3 deletions sui/src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ fn main() {
runtime.block_on(async move {
let server = b.spawn_server(state).await;
if let Err(err) = server.join().await {
error!("Server ended with an error: {}", err);
error!("Server ended with an error: {err}");
}
});
});
Expand Down Expand Up @@ -382,7 +382,7 @@ impl ClientServerBenchmark {
let items_number = transactions.len() / transaction_len_factor;
let mut elapsed_time: u128 = 0;

info!("Number of TCP connections: {}", connections);
info!("Number of TCP connections: {connections}");
info!("Sending requests.");
if !self.single_operation {
let mass_client = NetworkClient::new(
Expand Down Expand Up @@ -445,7 +445,7 @@ impl ClientServerBenchmark {
debug!("Query response: {:?}", info);
}
Err(error) => {
error!("Failed to execute transaction: {}", error);
error!("Failed to execute transaction: {error}");
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion sui/src/keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Keystore for SuiKeystore {
.keys
.get(address)
.ok_or_else(|| {
signature::Error::from_source(format!("Cannot find key for address: [{}]", address))
signature::Error::from_source(format!("Cannot find key for address: [{address}]"))
})?
.sign(msg))
}
Expand Down
20 changes: 10 additions & 10 deletions sui/src/rest_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async fn main() -> Result<(), String> {
};
let log = config_logging
.to_logger("rest_server")
.map_err(|error| format!("failed to create logger: {}", error))?;
.map_err(|error| format!("failed to create logger: {error}"))?;

tracing_subscriber::fmt::init();

Expand All @@ -74,7 +74,7 @@ async fn main() -> Result<(), String> {
let api_context = ServerContext::new(documentation);

let server = HttpServerStarter::new(&config_dropshot, api, api_context, &log)
.map_err(|error| format!("failed to create server: {}", error))?
.map_err(|error| format!("failed to create server: {error}"))?
.start();

server.await
Expand Down Expand Up @@ -326,20 +326,20 @@ async fn sui_start(ctx: Arc<RequestContext<ServerContext>>) -> Result<Response<B
Err(err) => {
return Err(custom_http_error(
StatusCode::FAILED_DEPENDENCY,
format!("Failed to start server: {}", err),
format!("Failed to start server: {err}"),
));
}
}
})
}

let num_authorities = handles.len();
info!("Started {} authorities", num_authorities);
info!("Started {num_authorities} authorities");

while let Some(spawned_server) = handles.next().await {
state.authority_handles.push(task::spawn(async {
if let Err(err) = spawned_server.unwrap().join().await {
error!("Server ended with an error: {}", err);
error!("Server ended with an error: {err}");
}
}));
}
Expand All @@ -358,7 +358,7 @@ async fn sui_start(ctx: Arc<RequestContext<ServerContext>>) -> Result<Response<B
}
custom_http_response(
StatusCode::OK,
format!("Started {} authorities", num_authorities),
format!("Started {num_authorities} authorities"),
)
}

Expand Down Expand Up @@ -431,7 +431,7 @@ async fn get_addresses(
GetAddressResponse {
addresses: addresses
.into_iter()
.map(|address| format!("{}", address))
.map(|address| format!("{address}"))
.collect(),
},
)
Expand Down Expand Up @@ -507,7 +507,7 @@ async fn get_objects(
let obj_type = object
.data
.type_()
.map_or("Unknown Type".to_owned(), |type_| format!("{}", type_));
.map_or("Unknown Type".to_owned(), |type_| format!("{type_}"));

objects.push(Object {
object_id: object_id.to_string(),
Expand Down Expand Up @@ -666,7 +666,7 @@ async fn object_info(
obj_type: object
.data
.type_()
.map_or("Unknown Type".to_owned(), |type_| format!("{}", type_)),
.map_or("Unknown Type".to_owned(), |type_| format!("{type_}")),
data: object_data,
},
)
Expand Down Expand Up @@ -1059,7 +1059,7 @@ async fn get_effect(
object
.data
.type_()
.map_or("Unknown Type".to_owned(), |type_| format!("{}", type_)),
.map_or("Unknown Type".to_owned(), |type_| format!("{type_}")),
);
effect.insert("id".to_string(), object_id.to_string());
effect.insert(
Expand Down
8 changes: 4 additions & 4 deletions sui/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ impl<P: Display, S: Send, H: AsyncHandler<S>> Shell<P, S, H> {
fn split_and_unescape(line: &str) -> Result<Vec<String>, String> {
let mut commands = Vec::new();
for word in line.split_whitespace() {
let command = unescape(word)
.ok_or_else(|| format!("Error: Unhandled escape sequence {}", word))?;
let command =
unescape(word).ok_or_else(|| format!("Error: Unhandled escape sequence {word}"))?;
commands.push(command);
}
Ok(commands)
Expand All @@ -158,7 +158,7 @@ fn substitute_env_variables(s: String) -> String {
env.sort_by(|(k1, _), (k2, _)| Ord::cmp(&k2.len(), &k1.len()));

for (key, value) in env {
let var = format!("${}", key);
let var = format!("${key}");
if s.contains(&var) {
let result = s.replace(var.as_str(), value.as_str());
return if result.contains('$') {
Expand Down Expand Up @@ -205,7 +205,7 @@ impl Completer for ShellHelper {
_pos: usize,
_ctx: &Context<'_>,
) -> Result<(usize, Vec<Self::Candidate>), rustyline::error::ReadlineError> {
let line = format!("{}_", line);
let line = format!("{line}_");
// split line
let mut tokens = line.split_whitespace();
let mut last_token = tokens.next_back().unwrap().to_string();
Expand Down
2 changes: 1 addition & 1 deletion sui/src/sui_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ impl SuiNetwork {
for spawned_server in self.spawned_authorities {
handles.push(async move {
if let Err(err) = spawned_server.join().await {
error!("Server ended with an error: {}", err);
error!("Server ended with an error: {err}");
}
});
}
Expand Down
4 changes: 2 additions & 2 deletions sui/src/sui_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ impl SuiJsonValue {
// Other times we need vec of hex bytes for address. Issue is both Address and Strings are represented as Vec<u8> in Move call
(JsonValue::String(s), NormalizedMoveType::Vector(t)) => {
if *t != NormalizedMoveType::U8 {
return Err(anyhow!("Cannot convert string arg {} to {}", s, typ));
return Err(anyhow!("Cannot convert string arg {s} to {typ}"));
}
let vec = if s.starts_with(HEX_PREFIX) {
// If starts with 0x, treat as hex vector
Expand Down Expand Up @@ -182,7 +182,7 @@ impl SuiJsonValue {
let r: SuiAddress = decode_bytes_hex(s.trim_start_matches(HEX_PREFIX))?;
IntermediateValue::Address(r)
}
_ => return Err(anyhow!("Unexpected arg {} for expected type {}", val, typ)),
_ => return Err(anyhow!("Unexpected arg {val} for expected type {typ}")),
};

Ok(new_serde_value)
Expand Down
14 changes: 7 additions & 7 deletions sui/src/unit_tests/cli_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ async fn test_addresses_command() -> Result<(), anyhow::Error> {

// Check log output contains all addresses
for address in &context.config.accounts {
assert!(logs_contain(&*format!("{}", address)));
assert!(logs_contain(&*format!("{address}")));
}

Ok(())
Expand Down Expand Up @@ -297,7 +297,7 @@ async fn test_objects_command() -> Result<(), anyhow::Error> {

// Check log output contains all object ids.
for (object_id, _, _) in object_refs {
assert!(logs_contain(format!("{}", object_id).as_str()))
assert!(logs_contain(format!("{object_id}").as_str()))
}

network.kill().await?;
Expand Down Expand Up @@ -342,7 +342,7 @@ async fn test_custom_genesis() -> Result<(), anyhow::Error> {

// confirm the object with custom object id.
retry_assert!(
logs_contain(format!("{}", object_id).as_str()),
logs_contain(format!("{object_id}").as_str()),
Duration::from_millis(5000)
);

Expand Down Expand Up @@ -377,7 +377,7 @@ async fn test_custom_genesis_with_custom_move_package() -> Result<(), anyhow::Er

// Make sure we log out package id
for (_, id) in &network_conf.loaded_move_packages {
assert!(logs_contain(&*format!("{}", id)));
assert!(logs_contain(&*format!("{id}")));
}

// Create Wallet context.
Expand Down Expand Up @@ -457,7 +457,7 @@ async fn test_gas_command() -> Result<(), anyhow::Error> {
.execute(&mut context)
.await?
.print(true);
let object_id_str = format!("{}", object_id);
let object_id_str = format!("{object_id}");

tokio::time::sleep(Duration::from_millis(100)).await;

Expand Down Expand Up @@ -603,7 +603,7 @@ async fn get_move_object(
}
_ => panic!("WalletCommands::Object returns wrong type"),
},
_ => panic!("WalletCommands::Object returns wrong type {}", obj),
_ => panic!("WalletCommands::Object returns wrong type {obj}"),
}
}

Expand Down Expand Up @@ -701,7 +701,7 @@ async fn test_move_call_args_linter_command() -> Result<(), anyhow::Error> {

// Check log output contains all object ids.
for (object_id, _, _) in &object_refs {
assert!(logs_contain(format!("{}", object_id).as_str()))
assert!(logs_contain(format!("{object_id}").as_str()))
}

// Create an object for address1 using Move call
Expand Down
2 changes: 1 addition & 1 deletion sui/src/unit_tests/rest_server_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async fn test_concurrency() -> Result<(), anyhow::Error> {

let log = log_config
.to_logger("rest_server")
.map_err(|error| anyhow!("failed to create logger: {}", error))?;
.map_err(|error| anyhow!("failed to create logger: {error}"))?;

let documentation = api.openapi("Sui API", "0.1").json()?;

Expand Down
2 changes: 1 addition & 1 deletion sui/src/unit_tests/shell_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn test_substitute_env_variables() {

let test_string_2 = "$OBJECT_ID/SOME_DIRECTORY".to_string();
assert_eq!(
format!("{}/SOME_DIRECTORY", random_id),
format!("{random_id}/SOME_DIRECTORY"),
substitute_env_variables(test_string_2)
);
// Make sure variable with the same beginnings won't get substituted incorrectly
Expand Down
2 changes: 1 addition & 1 deletion sui/src/unit_tests/sui_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ fn test_basic_args_linter_pure_args() {
),
// U128 value encoded as str
(
Value::from(format!("{}", u128_val)),
Value::from(format!("{u128_val}")),
Type::U128,
Some(bcs::to_bytes(&u128_val).unwrap()),
),
Expand Down
4 changes: 2 additions & 2 deletions sui/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,15 @@ async fn handle_command(
WalletCommandResult::Addresses(ref addresses) => {
let addresses = addresses
.iter()
.map(|addr| format!("{}", addr))
.map(|addr| format!("{addr}"))
.collect::<Vec<_>>();
cache.insert(CacheKey::flag("--address"), addresses.clone());
cache.insert(CacheKey::flag("--to"), addresses);
}
WalletCommandResult::Objects(ref objects) => {
let objects = objects
.iter()
.map(|(object_id, _, _)| format!("{}", object_id))
.map(|(object_id, _, _)| format!("{object_id}"))
.collect::<Vec<_>>();
cache.insert(CacheKey::new("object", "--id"), objects.clone());
cache.insert(CacheKey::flag("--gas"), objects.clone());
Expand Down
8 changes: 4 additions & 4 deletions sui/src/wallet_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,21 +563,21 @@ impl Debug for WalletCommandResult {

fn unwrap_err_to_string<T: Display, F: FnOnce() -> Result<T, anyhow::Error>>(func: F) -> String {
match func() {
Ok(s) => format!("{}", s),
Err(err) => format!("{}", err).red().to_string(),
Ok(s) => format!("{s}"),
Err(err) => format!("{err}").red().to_string(),
}
}

impl WalletCommandResult {
pub fn print(&self, pretty: bool) {
let line = if pretty {
format!("{}", self)
format!("{self}")
} else {
format!("{:?}", self)
};
// Log line by line
for line in line.lines() {
info!("{}", line)
info!("{line}")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion sui_core/src/authority/authority_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ impl<const ALL_OBJ_VER: bool> BackingPackageStore for SuiDataStore<ALL_OBJ_VER>
fp_ensure!(
obj.is_package(),
SuiError::BadObjectType {
error: format!("Package expected, Move object found: {}", package_id),
error: format!("Package expected, Move object found: {package_id}"),
}
);
}
Expand Down
4 changes: 2 additions & 2 deletions sui_core/src/authority_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ impl AuthorityServer {
match reply {
Ok(x) => x,
Err(error) => {
warn!("User query failed: {}", error);
warn!("User query failed: {error}");
self.server.increment_user_errors();
Some(serialize_error(&error))
}
Expand Down Expand Up @@ -342,7 +342,7 @@ where
if let Some(reply) = self.handle_one_message(_message, &mut channel).await {
let status = channel.sink().send(reply.into()).await;
if let Err(error) = status {
error!("Failed to send query response: {}", error);
error!("Failed to send query response: {error}");
}
};
}
Expand Down
Loading