Skip to content

Commit

Permalink
cargo clippy --fix for uninlined fmt args (#1099)
Browse files Browse the repository at this point in the history
* Clippy fix uninlined format args

Signed-off-by: clux <sszynrae@gmail.com>

* clippy --fix in kube-core

Signed-off-by: clux <sszynrae@gmail.com>

* clippy --fix in runtime

Signed-off-by: clux <sszynrae@gmail.com>

* change the old clippy flag to the new named one instead

Signed-off-by: clux <sszynrae@gmail.com>

* fmt

Signed-off-by: clux <sszynrae@gmail.com>

* fix kube-derive

Signed-off-by: clux <sszynrae@gmail.com>

* fix in kube-core with --all-features..

Signed-off-by: clux <sszynrae@gmail.com>

* fix examples

Signed-off-by: clux <sszynrae@gmail.com>

Signed-off-by: clux <sszynrae@gmail.com>
  • Loading branch information
clux committed Dec 6, 2022
1 parent 6c87ffe commit a4bcf97
Show file tree
Hide file tree
Showing 29 changed files with 61 additions and 70 deletions.
2 changes: 1 addition & 1 deletion clippy.toml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
blacklisted-names = []
disallowed-names = []
2 changes: 1 addition & 1 deletion examples/crd_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fn main() {
});
println!("Spec: {:?}", foo.spec);
let crd = serde_json::to_string_pretty(&FooCrd::crd()).unwrap();
println!("Foo CRD: \n{}", crd);
println!("Foo CRD: \n{crd}");

println!("Spec (via HasSpec): {:?}", foo.spec());
println!("Status (via HasStatus): {:?}", foo.status());
Expand Down
2 changes: 1 addition & 1 deletion examples/crd_derive_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ async fn delete_crd(client: Client) -> Result<()> {
return Ok(());
}
}
Err(anyhow!(format!("CRD not deleted after {} seconds", timeout_secs)))
Err(anyhow!(format!("CRD not deleted after {timeout_secs} seconds")))
} else {
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions examples/kubectl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl App {

async fn watch(&self, api: Api<DynamicObject>, mut lp: ListParams) -> Result<()> {
if let Some(n) = &self.name {
lp = lp.fields(&format!("metadata.name={}", n));
lp = lp.fields(&format!("metadata.name={n}"));
}
// present a dumb table for it for now. kubectl does not do this anymore.
let mut stream = watcher(api, lp).applied_objects().boxed();
Expand Down Expand Up @@ -196,7 +196,7 @@ async fn main() -> Result<()> {
if let Some(resource) = &app.resource {
// Common discovery, parameters, and api configuration for a single resource
let (ar, caps) = resolve_api_resource(&discovery, resource)
.with_context(|| format!("resource {:?} not found in cluster", resource))?;
.with_context(|| format!("resource {resource:?} not found in cluster"))?;
let mut lp = ListParams::default();
if let Some(label) = &app.selector {
lp = lp.labels(label);
Expand Down Expand Up @@ -238,9 +238,9 @@ fn format_creation_since(time: Option<Time>) -> String {
}
fn format_duration(dur: Duration) -> String {
match (dur.num_days(), dur.num_hours(), dur.num_minutes()) {
(days, _, _) if days > 0 => format!("{}d", days),
(_, hours, _) if hours > 0 => format!("{}h", hours),
(_, _, mins) => format!("{}m", mins),
(days, _, _) if days > 0 => format!("{days}d"),
(_, hours, _) if hours > 0 => format!("{hours}h"),
(_, _, mins) => format!("{mins}m"),
}
}

Expand Down
2 changes: 1 addition & 1 deletion examples/node_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async fn check_for_node_failures(events: &Api<Event>, o: Node) -> anyhow::Result
warn!("Unschedulable Node: {}, ({:?})", name, failed);
// Find events related to this node
let opts =
ListParams::default().fields(&format!("involvedObject.kind=Node,involvedObject.name={}", name));
ListParams::default().fields(&format!("involvedObject.kind=Node,involvedObject.name={name}"));
let evlist = events.list(&opts).await?;
for e in evlist {
warn!("Node event: {:?}", serde_json::to_string_pretty(&e)?);
Expand Down
2 changes: 1 addition & 1 deletion examples/pod_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ async fn main() -> anyhow::Result<()> {
{
let ap = AttachParams::default().stderr(false);
let mut cat = pods
.exec("example", vec!["cat", &format!("/{}", file_name)], &ap)
.exec("example", vec!["cat", &format!("/{file_name}")], &ap)
.await?;
let mut cat_out = tokio_util::io::ReaderStream::new(cat.stdout().unwrap());
let next_stdout = cat_out.next().await.unwrap()?;
Expand Down
8 changes: 4 additions & 4 deletions examples/pod_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async fn main() -> anyhow::Result<()> {
)
.await?;
let output = get_output(attached).await;
println!("{}", output);
println!("{output}");
assert_eq!(output.lines().count(), 3);
}

Expand All @@ -71,7 +71,7 @@ async fn main() -> anyhow::Result<()> {
.exec("example", vec!["uptime"], &AttachParams::default().stderr(false))
.await?;
let output = get_output(attached).await;
println!("{}", output);
println!("{output}");
assert_eq!(output.lines().count(), 1);
}

Expand All @@ -89,15 +89,15 @@ async fn main() -> anyhow::Result<()> {
let next_stdout = stdout_stream.next();
stdin_writer.write_all(b"echo test string 1\n").await?;
let stdout = String::from_utf8(next_stdout.await.unwrap().unwrap().to_vec()).unwrap();
println!("{}", stdout);
println!("{stdout}");
assert_eq!(stdout, "test string 1\n");

// AttachedProcess provides access to a future that resolves with a status object.
let status = attached.take_status().unwrap();
// Send `exit 1` to get a failure status.
stdin_writer.write_all(b"exit 1\n").await?;
if let Some(status) = status.await {
println!("{:?}", status);
println!("{status:?}");
assert_eq!(status.status, Some("Failure".to_owned()));
assert_eq!(status.reason, Some("NonZeroExitCode".to_owned()));
}
Expand Down
4 changes: 2 additions & 2 deletions examples/pod_shell_crossterm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async fn handle_terminal_size(mut channel: Sender<TerminalSize>) -> Result<(), a
// create a stream to catch SIGWINCH signal
let mut sig = signal::unix::signal(signal::unix::SignalKind::window_change())?;
loop {
if sig.recv().await == None {
if (sig.recv().await).is_none() {
return Ok(());
}

Expand Down Expand Up @@ -126,6 +126,6 @@ async fn main() -> anyhow::Result<()> {
assert_eq!(pdel.name_any(), "example");
});

println!("");
println!();
Ok(())
}
2 changes: 1 addition & 1 deletion examples/secret_syncer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type Result<T, E = Error> = std::result::Result<T, E>;

fn secret_name_for_configmap(cm: &ConfigMap) -> Result<String> {
let name = cm.metadata.name.as_deref().ok_or(Error::NoName)?;
Ok(format!("cmsyncer-{}", name))
Ok(format!("cmsyncer-{name}"))
}

async fn apply(cm: Arc<ConfigMap>, secrets: &kube::Api<Secret>) -> Result<Action> {
Expand Down
4 changes: 2 additions & 2 deletions kube-client/src/api/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,11 +429,11 @@ mod tests {

let mut entry = match api.entry(object_name).await? {
Entry::Occupied(entry) => entry,
entry => panic!("entry for existing object must be occupied: {:?}", entry),
entry => panic!("entry for existing object must be occupied: {entry:?}"),
};
let mut entry2 = match api.entry(object_name).await? {
Entry::Occupied(entry) => entry,
entry => panic!("entry for existing object must be occupied: {:?}", entry),
entry => panic!("entry for existing object must be occupied: {entry:?}"),
};

// Entry is up-to-date, modify cleanly
Expand Down
3 changes: 1 addition & 2 deletions kube-client/src/api/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,7 @@ mod test {
assert_eq!(
tokenreviewstatus.user.unwrap().username,
Some(format!(
"system:serviceaccount:{}:{}",
serviceaccount_namespace, serviceaccount_name
"system:serviceaccount:{serviceaccount_namespace}:{serviceaccount_name}"
))
);

Expand Down
22 changes: 10 additions & 12 deletions kube-client/src/client/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl RefreshableToken {
}

fn bearer_header(token: &str) -> Result<HeaderValue, Error> {
let mut value = HeaderValue::try_from(format!("Bearer {}", token)).map_err(Error::InvalidBearerToken)?;
let mut value = HeaderValue::try_from(format!("Bearer {token}")).map_err(Error::InvalidBearerToken)?;
value.set_sensitive(true);
Ok(value)
}
Expand Down Expand Up @@ -381,11 +381,11 @@ fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result<ProviderToke
let output = command
.args(params.trim().split(' '))
.output()
.map_err(|e| Error::AuthExec(format!("Executing {:} failed: {:?}", cmd, e)))?;
.map_err(|e| Error::AuthExec(format!("Executing {cmd:} failed: {e:?}")))?;

if !output.status.success() {
return Err(Error::AuthExecRun {
cmd: format!("{} {}", cmd, params),
cmd: format!("{cmd} {params}"),
status: output.status,
out: output,
});
Expand All @@ -406,7 +406,7 @@ fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result<ProviderToke
}
} else {
let token = std::str::from_utf8(&output.stdout)
.map_err(|e| Error::AuthExec(format!("Result is not a string {:?} ", e)))?
.map_err(|e| Error::AuthExec(format!("Result is not a string {e:?} ")))?
.to_owned();
return Ok(ProviderToken::GcpCommand(token, None));
}
Expand All @@ -430,21 +430,20 @@ fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result<ProviderToke

fn extract_value(json: &serde_json::Value, path: &str) -> Result<String, Error> {
let pure_path = path.trim_matches(|c| c == '"' || c == '{' || c == '}');
match jsonpath_select(json, &format!("${}", pure_path)) {
match jsonpath_select(json, &format!("${pure_path}")) {
Ok(v) if !v.is_empty() => {
if let serde_json::Value::String(res) = v[0] {
Ok(res.clone())
} else {
Err(Error::AuthExec(format!(
"Target value at {:} is not a string",
pure_path
"Target value at {pure_path:} is not a string"
)))
}
}

Err(e) => Err(Error::AuthExec(format!("Could not extract JSON value: {:}", e))),
Err(e) => Err(Error::AuthExec(format!("Could not extract JSON value: {e:}"))),

_ => Err(Error::AuthExec(format!("Target value {:} not found", pure_path))),
_ => Err(Error::AuthExec(format!("Target value {pure_path:} not found"))),
}
}

Expand Down Expand Up @@ -500,7 +499,7 @@ fn auth_exec(auth: &ExecConfig) -> Result<ExecCredential, Error> {
let out = cmd.output().map_err(Error::AuthExecStart)?;
if !out.status.success() {
return Err(Error::AuthExecRun {
cmd: format!("{:?}", cmd),
cmd: format!("{cmd:?}"),
status: out.status,
out,
});
Expand Down Expand Up @@ -544,8 +543,7 @@ mod test {
expiry-key: '{{.credential.token_expiry}}'
token-key: '{{.credential.access_token}}'
name: gcp
"#,
expiry = expiry
"#
);

let config: Kubeconfig = serde_yaml::from_str(&test_file).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/client/middleware/base_uri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ fn set_base_uri(base_uri: &http::Uri, req_pandq: Option<&uri::PathAndQuery>) ->
// Remove any trailing slashes and join.
// `PathAndQuery` always starts with a slash.
let base_path = pandq.path().trim_end_matches('/');
builder.path_and_query(format!("{}{}", base_path, req_pandq))
builder.path_and_query(format!("{base_path}{req_pandq}"))
} else {
builder.path_and_query(pandq.as_str())
};
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/client/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ mod tests {
let (request, send) = handle.next_request().await.expect("service not called");
assert_eq!(
request.headers().get(AUTHORIZATION).unwrap(),
HeaderValue::try_from(format!("Bearer {}", TOKEN)).unwrap()
HeaderValue::try_from(format!("Bearer {TOKEN}")).unwrap()
);
send.send_response(Response::builder().body(Body::empty()).unwrap());
});
Expand Down
6 changes: 3 additions & 3 deletions kube-client/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ impl Client {
/// # }
/// ```
pub async fn list_api_group_resources(&self, apiversion: &str) -> Result<k8s_meta_v1::APIResourceList> {
let url = format!("/apis/{}", apiversion);
let url = format!("/apis/{apiversion}");
self.request(
Request::builder()
.uri(url)
Expand All @@ -405,7 +405,7 @@ impl Client {

/// Lists resources served in particular `core` group version.
pub async fn list_core_api_resources(&self, version: &str) -> Result<k8s_meta_v1::APIResourceList> {
let url = format!("/api/{}", version);
let url = format!("/api/{version}");
self.request(
Request::builder()
.uri(url)
Expand Down Expand Up @@ -435,7 +435,7 @@ fn handle_api_errors(text: &str, s: StatusCode) -> Result<()> {
let ae = ErrorResponse {
status: s.to_string(),
code: s.as_u16(),
message: format!("{:?}", text),
message: format!("{text:?}"),
reason: "Failed to parse error data".into(),
};
tracing::debug!("Unsuccessful: {:?} (reconstruct)", ae);
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/config/file_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,7 @@ username: user
password: kube_rs
"#;
let authinfo: AuthInfo = serde_yaml::from_str(authinfo_yaml).unwrap();
let authinfo_debug_output = format!("{:?}", authinfo);
let authinfo_debug_output = format!("{authinfo:?}");
let expected_output = "AuthInfo { \
username: Some(\"user\"), \
password: Some(Secret([REDACTED alloc::string::String])), \
Expand Down
5 changes: 1 addition & 4 deletions kube-client/src/discovery/apigroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,7 @@ impl ApiGroup {
return Ok((ar, caps));
}
}
Err(Error::Discovery(DiscoveryError::MissingKind(format!(
"{:?}",
gvk
))))
Err(Error::Discovery(DiscoveryError::MissingKind(format!("{gvk:?}"))))
}

// shortcut method to give cheapest return for a pinned group
Expand Down
2 changes: 1 addition & 1 deletion kube-client/src/discovery/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub(crate) fn parse_apicapabilities(list: &APIResourceList, name: &str) -> Resul
Scope::Cluster
};

let subresource_name_prefix = format!("{}/", name);
let subresource_name_prefix = format!("{name}/");
let mut subresources = vec![];
for res in &list.resources {
if let Some(subresource_name) = res.name.strip_prefix(&subresource_name_prefix) {
Expand Down
12 changes: 6 additions & 6 deletions kube-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ mod test {
let mut stream = pods.watch(&lp, "0").await?.boxed();
while let Some(ev) = stream.try_next().await? {
// can debug format watch event
let _ = format!("we: {:?}", ev);
let _ = format!("we: {ev:?}");
match ev {
WatchEvent::Modified(o) => {
let s = o.status.as_ref().expect("status exists on pod");
Expand All @@ -243,7 +243,7 @@ mod test {
break;
}
}
WatchEvent::Error(e) => panic!("watch error: {}", e),
WatchEvent::Error(e) => panic!("watch error: {e}"),
_ => {}
}
}
Expand Down Expand Up @@ -321,7 +321,7 @@ mod test {
break;
}
}
WatchEvent::Error(e) => panic!("watch error: {}", e),
WatchEvent::Error(e) => panic!("watch error: {e}"),
_ => {}
}
}
Expand Down Expand Up @@ -361,15 +361,15 @@ mod test {
let next_stdout = stdout_stream.next();
stdin_writer.write_all(b"echo test string 1\n").await?;
let stdout = String::from_utf8(next_stdout.await.unwrap().unwrap().to_vec()).unwrap();
println!("{}", stdout);
println!("{stdout}");
assert_eq!(stdout, "test string 1\n");

// AttachedProcess resolves with status object.
// Send `exit 1` to get a failure status.
stdin_writer.write_all(b"exit 1\n").await?;
let status = attached.take_status().unwrap();
if let Some(status) = status.await {
println!("{:?}", status);
println!("{status:?}");
assert_eq!(status.status, Some("Failure".to_owned()));
assert_eq!(status.reason, Some("NonZeroExitCode".to_owned()));
}
Expand Down Expand Up @@ -435,7 +435,7 @@ mod test {
break;
}
}
WatchEvent::Error(e) => panic!("watch error: {}", e),
WatchEvent::Error(e) => panic!("watch error: {e}"),
_ => {}
}
}
Expand Down
4 changes: 2 additions & 2 deletions kube-core/src/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ fn to_plural(word: &str) -> String {
|| word.ends_with("ch")
|| word.ends_with("sh")
{
return format!("{}es", word);
return format!("{word}es");
}

// Words ending in y that are preceded by a consonant will be pluralized by
Expand All @@ -142,7 +142,7 @@ fn to_plural(word: &str) -> String {
}

// All other words will have "s" added to the end (eg. days).
format!("{}s", word)
format!("{word}s")
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion kube-core/src/gvk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl GroupVersionResource {
let api_version = if group.is_empty() {
version.to_string()
} else {
format!("{}/{}", group, version)
format!("{group}/{version}")
};

Self {
Expand Down

0 comments on commit a4bcf97

Please sign in to comment.