Auto-apply clippy lint fixes from Rust 1.67

pull/249/head
Matěj Laitl 2023-02-03 20:53:23 +01:00 committed by Jake McGinty
parent 103896dd88
commit 0dc92de722
13 changed files with 44 additions and 54 deletions

View File

@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use shared::{chmod, ensure_dirs_exist, Cidr, IoErrorContext, Peer, WrappedIoError};
use std::{
fs::{File, OpenOptions},
io::{self, Read, Seek, SeekFrom, Write},
io::{self, Read, Seek, Write},
path::{Path, PathBuf},
};
use wireguard_control::InterfaceName;
@ -133,7 +133,7 @@ impl DataStore {
}
pub fn write(&mut self) -> Result<(), io::Error> {
self.file.seek(SeekFrom::Start(0))?;
self.file.rewind()?;
self.file.set_len(0)?;
self.file
.write_all(serde_json::to_string_pretty(&self.contents)?.as_bytes())?;
@ -176,7 +176,7 @@ mod tests {
fn setup_basic_store(dir: &Path) {
let mut store = DataStore::open_with_path(dir.join("peer_store.json"), true).unwrap();
println!("{:?}", store);
println!("{store:?}");
assert_eq!(0, store.peers().len());
assert_eq!(0, store.cidrs().len());

View File

@ -282,7 +282,7 @@ fn update_hosts_file(
) -> Result<(), WrappedIoError> {
log::info!("updating {} with the latest peers.", "/etc/hosts".yellow());
let mut hosts_builder = HostsBuilder::new(format!("innernet {}", interface));
let mut hosts_builder = HostsBuilder::new(format!("innernet {interface}"));
for peer in peers {
hosts_builder.add_hostname(
peer.contents.ip,
@ -725,7 +725,7 @@ fn delete_cidr(
let cidr_id = prompts::delete_cidr(&cidrs, &peers, &sub_opts)?;
println!("Deleting CIDR...");
api.http("DELETE", &format!("/admin/cidrs/{}", cidr_id))?;
api.http("DELETE", &format!("/admin/cidrs/{cidr_id}"))?;
println!("CIDR deleted.");
@ -801,7 +801,7 @@ fn rename_peer(
.next()
.ok_or_else(|| anyhow!("Peer not found."))?;
api.http_form("PUT", &format!("/admin/peers/{}", id), peer_request)?;
api.http_form("PUT", &format!("/admin/peers/{id}"), peer_request)?;
log::info!("Peer renamed.");
} else {
log::info!("exited without renaming peer.");
@ -825,7 +825,7 @@ fn enable_or_disable_peer(
if let Some(peer) = prompts::enable_or_disable_peer(&peers[..], enable)? {
let Peer { id, mut contents } = peer;
contents.is_disabled = !enable;
api.http_form("PUT", &format!("/admin/peers/{}", id), contents)?;
api.http_form("PUT", &format!("/admin/peers/{id}"), contents)?;
} else {
log::info!("exiting without enabling or disabling peer.");
}
@ -1090,7 +1090,7 @@ fn print_interface(device_info: &Device, short: bool) -> Result<(), Error> {
if short {
let listen_port_str = device_info
.listen_port
.map(|p| format!("(:{}) ", p))
.map(|p| format!("(:{p}) "))
.unwrap_or_default();
println!(
"{} {}",

View File

@ -15,7 +15,7 @@ const BASE_MODULES: &[&str] = &["innernet", "shared"];
fn target_is_base(target: &str) -> bool {
BASE_MODULES
.iter()
.any(|module| module == &target || target.starts_with(&format!("{}::", module)))
.any(|module| module == &target || target.starts_with(&format!("{module}::")))
}
impl log::Log for Logger {
@ -245,7 +245,7 @@ impl<'a> Api<'a> {
request.send_json(serde_json::to_value(form).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("failed to serialize JSON request: {}", e),
format!("failed to serialize JSON request: {e}"),
)
})?)?
} else {

View File

@ -231,25 +231,25 @@ impl HostsBuilder {
let mut s = vec![];
for line in &lines[..insert] {
writeln!(s, "{}", line)?;
writeln!(s, "{line}")?;
}
if !self.hostname_map.is_empty() {
writeln!(s, "{}", begin_marker)?;
writeln!(s, "{begin_marker}")?;
for (ip, hostnames) in &self.hostname_map {
if cfg!(windows) {
// windows only allows one hostname per line
for hostname in hostnames {
writeln!(s, "{} {}", ip, hostname)?;
writeln!(s, "{ip} {hostname}")?;
}
} else {
// assume the same format as Unix
writeln!(s, "{} {}", ip, hostnames.join(" "))?;
}
}
writeln!(s, "{}", end_marker)?;
writeln!(s, "{end_marker}")?;
}
for line in &lines[insert..] {
writeln!(s, "{}", line)?;
writeln!(s, "{line}")?;
}
match Self::write_and_swap(&temp_path, hosts_path, &s) {
@ -293,7 +293,7 @@ mod tests {
fn test_temp_path_good() {
let hosts_path = Path::new("/etc/hosts");
let temp_path = HostsBuilder::get_temp_path(hosts_path).unwrap();
println!("{:?}", temp_path);
println!("{temp_path:?}");
assert!(temp_path
.file_name()
.unwrap()
@ -317,7 +317,7 @@ mod tests {
builder.write_to(&temp_path).unwrap();
let contents = std::fs::read_to_string(&temp_path).unwrap();
println!("contents: {}", contents);
println!("contents: {contents}");
assert!(contents.starts_with("preexisting\ncontent"));
assert!(contents.contains("# DO NOT EDIT foo BEGIN"));
assert!(contents.contains("1.1.1.1 whatever"));

View File

@ -188,7 +188,7 @@ mod tests {
let now = Instant::now();
let (v4, v6) = get_both();
println!("Done in {}ms", now.elapsed().as_millis());
println!("v4: {:?}, v6: {:?}", v4, v6);
println!("v4: {v4:?}, v6: {v6:?}");
assert!(v4.is_some());
assert!(v6.is_some());
Ok(())

View File

@ -324,7 +324,7 @@ impl DatabasePeer {
FROM peers
JOIN associated_subcidrs ON peers.cidr_id=associated_subcidrs.cidr_id
WHERE peers.is_disabled = 0 AND peers.is_redeemed = 1;",
COLUMNS.iter().map(|col| format!("peers.{}", col)).collect::<Vec<_>>().join(", ")
COLUMNS.iter().map(|col| format!("peers.{col}")).collect::<Vec<_>>().join(", ")
),
)?;
let peers = stmt

View File

@ -187,9 +187,9 @@ impl Server {
fn base_request_builder(&self, verb: &str, path: &str) -> http::request::Builder {
let path = if cfg!(feature = "v6-test") {
format!("http://[{}]{}", WG_MANAGE_PEER_IP, path)
format!("http://[{WG_MANAGE_PEER_IP}]{path}")
} else {
format!("http://{}{}", WG_MANAGE_PEER_IP, path)
format!("http://{WG_MANAGE_PEER_IP}{path}")
};
Request::builder().uri(path).method(verb).header(
shared::INNERNET_PUBKEY_HEADER,

View File

@ -15,7 +15,7 @@ fn if_nametoindex(interface: &InterfaceName) -> Result<u32, io::Error> {
match unsafe { libc::if_nametoindex(interface.as_ptr()) } {
0 => Err(io::Error::new(
io::ErrorKind::NotFound,
format!("couldn't find interface '{}'.", interface),
format!("couldn't find interface '{interface}'."),
)),
index => Ok(index),
}

View File

@ -30,7 +30,7 @@ pub fn ensure_interactive(prompt: &str) -> Result<(), io::Error> {
} else {
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!("Prompt \"{}\" failed because TTY isn't connected.", prompt),
format!("Prompt \"{prompt}\" failed because TTY isn't connected."),
))
}
}
@ -294,7 +294,7 @@ pub fn add_peer(
let is_admin = if let Some(is_admin) = args.admin {
is_admin
} else {
confirm(&format!("Make {} an admin?", name))?
confirm(&format!("Make {name} an admin?"))?
};
let invite_expires = if let Some(ref invite_expires) = args.invite_expires {
@ -311,7 +311,7 @@ pub fn add_peer(
} else {
input(
"Save peer invitation file to",
Prefill::Default(format!("{}.toml", name)),
Prefill::Default(format!("{name}.toml")),
)?
};
@ -486,7 +486,7 @@ pub fn set_listen_port(
.wait_for_newline(true)
.with_prompt(
&(if let Some(port) = &listen_port {
format!("Set listen port to {}?", port)
format!("Set listen port to {port}?")
} else {
"Unset and randomize listen port?".to_string()
}),
@ -531,7 +531,7 @@ pub fn override_endpoint(
Some(endpoint) => endpoint.clone(),
None => ask_endpoint(listen_port)?,
};
if args.yes || confirm(&format!("Set external endpoint to {}?", endpoint))? {
if args.yes || confirm(&format!("Set external endpoint to {endpoint}?"))? {
Ok(Some(endpoint))
} else {
Ok(None)

View File

@ -546,8 +546,8 @@ impl ChangeString {
{
Self {
name,
old: old.map(|t| format!("{:?}", t)),
new: new.map(|t| format!("{:?}", t)),
old: old.map(|t| format!("{t:?}")),
new: new.map(|t| format!("{t:?}")),
}
}
}
@ -873,7 +873,7 @@ mod tests {
let diff = PeerDiff::new(Some(&info), Some(&peer)).unwrap();
println!("{:?}", diff);
println!("{diff:?}");
assert_eq!(diff, None);
}
@ -907,7 +907,7 @@ mod tests {
};
let diff = PeerDiff::new(Some(&info), Some(&peer)).unwrap();
println!("{:?}", peer);
println!("{peer:?}");
println!("{:?}", info.config);
assert!(matches!(diff, Some(_)));
}

View File

@ -7,5 +7,5 @@ const BACKEND: Backend = Backend::Userspace;
fn main() {
let devices = Device::list(BACKEND).unwrap();
println!("{:?}", devices);
println!("{devices:?}");
}

View File

@ -294,10 +294,7 @@ impl ApplyPayload {
if (self.current_buffer_len + nla_buffer_len) > MAX_GENL_PAYLOAD_LENGTH {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"encoded NLA ({} bytes) is too large: {:?}",
nla_buffer_len, nla
),
format!("encoded NLA ({nla_buffer_len} bytes) is too large: {nla:?}"),
));
}
self.nlas.push(nla);
@ -330,10 +327,7 @@ impl ApplyPayload {
if (self.current_buffer_len + peer_buffer_len) > MAX_GENL_PAYLOAD_LENGTH {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"encoded peer ({} bytes) is too large: {:?}",
peer_buffer_len, peer
),
format!("encoded peer ({peer_buffer_len} bytes) is too large: {peer:?}"),
));
}
@ -379,7 +373,7 @@ pub fn get_by_name(name: &InterfaceName) -> Result<Device, io::Error> {
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected netlink payload: {:?}", nlmsg),
format!("unexpected netlink payload: {nlmsg:?}"),
))
},
};

View File

@ -32,7 +32,7 @@ fn get_namefile(name: &InterfaceName) -> io::Result<PathBuf> {
fn get_socketfile(name: &InterfaceName) -> io::Result<PathBuf> {
if cfg!(target_os = "linux") {
Ok(get_base_folder()?.join(format!("{}.sock", name)))
Ok(get_base_folder()?.join(format!("{name}.sock")))
} else {
Ok(get_base_folder()?.join(format!("{}.sock", resolve_tun(name)?)))
}
@ -231,7 +231,7 @@ impl ConfigParser {
}
},
"protocol_version" | "last_handshake_time_nsec" => {},
_ => println!("got unsupported info: {}={}", key, value),
_ => println!("got unsupported info: {key}={value}"),
}
Ok(())
@ -278,10 +278,7 @@ fn start_userspace_wireguard(iface: &InterfaceName) -> io::Result<Output> {
command.args(&[iface.to_string()]).output()?
} else {
command
.env(
"WG_TUN_NAME_FILE",
&format!("{}/{}.name", VAR_RUN_PATH, iface),
)
.env("WG_TUN_NAME_FILE", &format!("{VAR_RUN_PATH}/{iface}.name"))
.args(["utun"])
.output()?
};
@ -302,7 +299,7 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
start_userspace_wireguard(iface)?;
std::thread::sleep(Duration::from_millis(100));
open_socket(iface)
.map_err(|e| io::Error::new(e.kind(), format!("failed to open socket ({})", e)))?
.map_err(|e| io::Error::new(e.kind(), format!("failed to open socket ({e})")))?
},
Ok(sock) => sock,
};
@ -314,11 +311,11 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
}
if let Some(f) = builder.fwmark {
writeln!(request, "fwmark={}", f).ok();
writeln!(request, "fwmark={f}").ok();
}
if let Some(f) = builder.listen_port {
writeln!(request, "listen_port={}", f).ok();
writeln!(request, "listen_port={f}").ok();
}
if builder.replace_peers {
@ -346,14 +343,13 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
}
if let Some(endpoint) = peer.endpoint {
writeln!(request, "endpoint={}", endpoint).ok();
writeln!(request, "endpoint={endpoint}").ok();
}
if let Some(keepalive_interval) = peer.persistent_keepalive_interval {
writeln!(
request,
"persistent_keepalive_interval={}",
keepalive_interval
"persistent_keepalive_interval={keepalive_interval}"
)
.ok();
}
@ -380,7 +376,7 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
match &split[..] {
["errno", "0"] => Ok(()),
["errno", val] => {
println!("ERROR {}", val);
println!("ERROR {val}");
Err(io::ErrorKind::InvalidInput.into())
},
_ => Err(io::ErrorKind::Other.into()),