aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2023-02-18 15:38:43 -0500
committerJesse Luehrs <doy@tozt.net>2023-02-18 15:49:17 -0500
commit1d68b717e8ae12dfdf8af9c451dbf0d6a8cc6d71 (patch)
tree9416fd8d1bc125aa6f217d6cbc6340e27655bb99
parentc6a948a5cfa2783907c084cc8d1034c33db319e6 (diff)
downloadrbw-1d68b717e8ae12dfdf8af9c451dbf0d6a8cc6d71.tar.gz
rbw-1d68b717e8ae12dfdf8af9c451dbf0d6a8cc6d71.zip
clippy
-rw-r--r--src/actions.rs7
-rw-r--r--src/api.rs53
-rw-r--r--src/bin/rbw-agent/actions.rs69
-rw-r--r--src/bin/rbw-agent/agent.rs9
-rw-r--r--src/bin/rbw-agent/main.rs2
-rw-r--r--src/bin/rbw-agent/sock.rs7
-rw-r--r--src/bin/rbw/actions.rs6
-rw-r--r--src/bin/rbw/commands.rs111
-rw-r--r--src/bin/rbw/main.rs2
-rw-r--r--src/cipherstring.rs14
-rw-r--r--src/config.rs3
-rw-r--r--src/dirs.rs26
-rw-r--r--src/edit.rs8
-rw-r--r--src/pinentry.rs14
14 files changed, 166 insertions, 165 deletions
diff --git a/src/actions.rs b/src/actions.rs
index df94c29..a7829a4 100644
--- a/src/actions.rs
+++ b/src/actions.rs
@@ -2,8 +2,11 @@ use crate::prelude::*;
fn api_client() -> Result<(crate::api::Client, crate::config::Config)> {
let config = crate::config::Config::load()?;
- let client =
- crate::api::Client::new(&config.base_url(), &config.identity_url(), &config.client_cert_path());
+ let client = crate::api::Client::new(
+ &config.base_url(),
+ &config.identity_url(),
+ &config.client_cert_path(),
+ );
Ok((client, config))
}
diff --git a/src/api.rs b/src/api.rs
index 5fa45cf..5f517bb 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -42,7 +42,7 @@ impl std::fmt::Display for UriMatchType {
RegularExpression => "regular_expression",
Never => "never",
};
- write!(f, "{}", s)
+ write!(f, "{s}")
}
}
@@ -114,7 +114,7 @@ impl std::convert::TryFrom<u64> for TwoFactorProviderType {
6 => Ok(Self::OrganizationDuo),
7 => Ok(Self::WebAuthn),
_ => Err(Error::InvalidTwoFactorProvider {
- ty: format!("{}", ty),
+ ty: format!("{ty}"),
}),
}
}
@@ -559,7 +559,11 @@ pub struct Client {
impl Client {
#[must_use]
- pub fn new(base_url: &str, identity_url: &str, client_cert_path: &str) -> Self {
+ pub fn new(
+ base_url: &str,
+ identity_url: &str,
+ client_cert_path: &str,
+ ) -> Self {
Self {
base_url: base_url.to_string(),
identity_url: identity_url.to_string(),
@@ -568,15 +572,20 @@ impl Client {
}
fn reqwest_client(&self) -> reqwest::Client {
- return if self.client_cert_path == "" {
+ if self.client_cert_path.is_empty() {
reqwest::Client::new()
} else {
let mut buf = Vec::new();
- let mut f = File::open(self.client_cert_path.to_string()).expect("cert not found");
+ let mut f =
+ File::open(&self.client_cert_path).expect("cert not found");
f.read_to_end(&mut buf).expect("cert read failed");
- let pem = reqwest::Identity::from_pem(&buf).expect("invalid cert");
- reqwest::Client::builder().identity(pem).build().expect("wtv")
- };
+ let pem =
+ reqwest::Identity::from_pem(&buf).expect("invalid cert");
+ reqwest::Client::builder()
+ .identity(pem)
+ .build()
+ .expect("wtv")
+ }
}
pub async fn prelogin(&self, email: &str) -> Result<u32> {
@@ -614,7 +623,7 @@ impl Client {
device_type: 8,
device_identifier: device_id.to_string(),
device_name: "rbw".to_string(),
- device_push_token: "".to_string(),
+ device_push_token: String::new(),
two_factor_token: None,
two_factor_provider: None,
};
@@ -651,7 +660,7 @@ impl Client {
device_type: 8,
device_identifier: device_id.to_string(),
device_name: "rbw".to_string(),
- device_push_token: "".to_string(),
+ device_push_token: String::new(),
two_factor_token: two_factor_token
.map(std::string::ToString::to_string),
// enum casts are safe, and i don't think there's a better way to
@@ -696,7 +705,7 @@ impl Client {
let client = self.reqwest_client();
let res = client
.get(&self.api_url("/sync"))
- .header("Authorization", format!("Bearer {}", access_token))
+ .header("Authorization", format!("Bearer {access_token}"))
.send()
.await
.map_err(|source| Error::Reqwest { source })?;
@@ -837,8 +846,8 @@ impl Client {
}
let client = reqwest::blocking::Client::new();
let res = client
- .post(&self.api_url("/ciphers"))
- .header("Authorization", format!("Bearer {}", access_token))
+ .post(self.api_url("/ciphers"))
+ .header("Authorization", format!("Bearer {access_token}"))
.json(&req)
.send()
.map_err(|source| Error::Reqwest { source })?;
@@ -970,8 +979,8 @@ impl Client {
}
let client = reqwest::blocking::Client::new();
let res = client
- .put(&self.api_url(&format!("/ciphers/{}", id)))
- .header("Authorization", format!("Bearer {}", access_token))
+ .put(self.api_url(&format!("/ciphers/{id}")))
+ .header("Authorization", format!("Bearer {access_token}"))
.json(&req)
.send()
.map_err(|source| Error::Reqwest { source })?;
@@ -989,8 +998,8 @@ impl Client {
pub fn remove(&self, access_token: &str, id: &str) -> Result<()> {
let client = reqwest::blocking::Client::new();
let res = client
- .delete(&self.api_url(&format!("/ciphers/{}", id)))
- .header("Authorization", format!("Bearer {}", access_token))
+ .delete(self.api_url(&format!("/ciphers/{id}")))
+ .header("Authorization", format!("Bearer {access_token}"))
.send()
.map_err(|source| Error::Reqwest { source })?;
match res.status() {
@@ -1010,8 +1019,8 @@ impl Client {
) -> Result<Vec<(String, String)>> {
let client = reqwest::blocking::Client::new();
let res = client
- .get(&self.api_url("/folders"))
- .header("Authorization", format!("Bearer {}", access_token))
+ .get(self.api_url("/folders"))
+ .header("Authorization", format!("Bearer {access_token}"))
.send()
.map_err(|source| Error::Reqwest { source })?;
match res.status() {
@@ -1042,8 +1051,8 @@ impl Client {
};
let client = reqwest::blocking::Client::new();
let res = client
- .post(&self.api_url("/folders"))
- .header("Authorization", format!("Bearer {}", access_token))
+ .post(self.api_url("/folders"))
+ .header("Authorization", format!("Bearer {access_token}"))
.json(&req)
.send()
.map_err(|source| Error::Reqwest { source })?;
@@ -1072,7 +1081,7 @@ impl Client {
};
let client = reqwest::blocking::Client::new();
let res = client
- .post(&self.identity_url("/connect/token"))
+ .post(self.identity_url("/connect/token"))
.form(&connect_req)
.send()
.map_err(|source| Error::Reqwest { source })?;
diff --git a/src/bin/rbw-agent/actions.rs b/src/bin/rbw-agent/actions.rs
index 61eb74b..fff34a5 100644
--- a/src/bin/rbw-agent/actions.rs
+++ b/src/bin/rbw-agent/actions.rs
@@ -10,9 +10,8 @@ pub async fn register(
let url_str = config_base_url().await?;
let url = reqwest::Url::parse(&url_str)
.context("failed to parse base url")?;
- let host = if let Some(host) = url.host_str() {
- host
- } else {
+ let Some(host) = url.host_str()
+ else {
return Err(anyhow::anyhow!(
"couldn't find host in rbw base url {}",
url_str
@@ -33,7 +32,7 @@ pub async fn register(
let client_id = rbw::pinentry::getpin(
&config_pinentry().await?,
"API key client__id",
- &format!("Log in to {}", host),
+ &format!("Log in to {host}"),
err.as_deref(),
tty,
false,
@@ -43,7 +42,7 @@ pub async fn register(
let client_secret = rbw::pinentry::getpin(
&config_pinentry().await?,
"API key client__secret",
- &format!("Log in to {}", host),
+ &format!("Log in to {host}"),
err.as_deref(),
tty,
false,
@@ -89,9 +88,8 @@ pub async fn login(
let url_str = config_base_url().await?;
let url = reqwest::Url::parse(&url_str)
.context("failed to parse base url")?;
- let host = if let Some(host) = url.host_str() {
- host
- } else {
+ let Some(host) = url.host_str()
+ else {
return Err(anyhow::anyhow!(
"couldn't find host in rbw base url {}",
url_str
@@ -112,7 +110,7 @@ pub async fn login(
let password = rbw::pinentry::getpin(
&config_pinentry().await?,
"Master Password",
- &format!("Log in to {}", host),
+ &format!("Log in to {host}"),
err.as_deref(),
tty,
true,
@@ -292,14 +290,12 @@ async fn login_success(
sync(sock, false).await?;
let db = load_db().await?;
- let protected_private_key =
- if let Some(protected_private_key) = db.protected_private_key {
- protected_private_key
- } else {
- return Err(anyhow::anyhow!(
- "failed to find protected private key in db"
- ));
- };
+ let Some(protected_private_key) = db.protected_private_key
+ else {
+ return Err(anyhow::anyhow!(
+ "failed to find protected private key in db"
+ ));
+ };
let res = rbw::actions::unlock(
&email,
@@ -330,28 +326,24 @@ pub async fn unlock(
if state.read().await.needs_unlock() {
let db = load_db().await?;
- let iterations = if let Some(iterations) = db.iterations {
- iterations
- } else {
+ let Some(iterations) = db.iterations
+ else {
return Err(anyhow::anyhow!(
"failed to find number of iterations in db"
));
};
- let protected_key = if let Some(protected_key) = db.protected_key {
- protected_key
- } else {
+ let Some(protected_key) = db.protected_key
+ else {
return Err(anyhow::anyhow!(
"failed to find protected key in db"
));
};
- let protected_private_key =
- if let Some(protected_private_key) = db.protected_private_key {
- protected_private_key
- } else {
- return Err(anyhow::anyhow!(
- "failed to find protected private key in db"
- ));
- };
+ let Some(protected_private_key) = db.protected_private_key
+ else {
+ return Err(anyhow::anyhow!(
+ "failed to find protected private key in db"
+ ));
+ };
let email = config_email().await?;
@@ -367,7 +359,10 @@ pub async fn unlock(
let password = rbw::pinentry::getpin(
&config_pinentry().await?,
"Master Password",
- &format!("Unlock the local database for '{}'", rbw::dirs::profile()),
+ &format!(
+ "Unlock the local database for '{}'",
+ rbw::dirs::profile()
+ ),
err.as_deref(),
tty,
true,
@@ -487,9 +482,8 @@ pub async fn decrypt(
org_id: Option<&str>,
) -> anyhow::Result<()> {
let state = state.read().await;
- let keys = if let Some(keys) = state.key(org_id) {
- keys
- } else {
+ let Some(keys) = state.key(org_id)
+ else {
return Err(anyhow::anyhow!(
"failed to find decryption keys in in-memory state"
));
@@ -515,9 +509,8 @@ pub async fn encrypt(
org_id: Option<&str>,
) -> anyhow::Result<()> {
let state = state.read().await;
- let keys = if let Some(keys) = state.key(org_id) {
- keys
- } else {
+ let Some(keys) = state.key(org_id)
+ else {
return Err(anyhow::anyhow!(
"failed to find encryption keys in in-memory state"
));
diff --git a/src/bin/rbw-agent/agent.rs b/src/bin/rbw-agent/agent.rs
index d64bf21..b36fbb7 100644
--- a/src/bin/rbw-agent/agent.rs
+++ b/src/bin/rbw-agent/agent.rs
@@ -15,10 +15,9 @@ pub struct State {
impl State {
pub fn key(&self, org_id: Option<&str>) -> Option<&rbw::locked::Keys> {
- match org_id {
- Some(id) => self.org_keys.as_ref().and_then(|h| h.get(id)),
- None => self.priv_key.as_ref(),
- }
+ org_id.map_or(self.priv_key.as_ref(), |id| {
+ self.org_keys.as_ref().and_then(|h| h.get(id))
+ })
}
pub fn needs_unlock(&self) -> bool {
@@ -94,7 +93,7 @@ impl Agent {
if let Err(e) = res {
// unwrap is the only option here
sock.send(&rbw::protocol::Response::Error {
- error: format!("{:#}", e),
+ error: format!("{e:#}"),
}).await.unwrap();
}
});
diff --git a/src/bin/rbw-agent/main.rs b/src/bin/rbw-agent/main.rs
index f5d478d..d84ab5b 100644
--- a/src/bin/rbw-agent/main.rs
+++ b/src/bin/rbw-agent/main.rs
@@ -78,7 +78,7 @@ fn main() {
if let Err(e) = res {
// XXX log file?
- eprintln!("{:#}", e);
+ eprintln!("{e:#}");
std::process::exit(1);
}
}
diff --git a/src/bin/rbw-agent/sock.rs b/src/bin/rbw-agent/sock.rs
index 9458239..b97d33d 100644
--- a/src/bin/rbw-agent/sock.rs
+++ b/src/bin/rbw-agent/sock.rs
@@ -36,9 +36,8 @@ impl Sock {
buf.read_line(&mut line)
.await
.context("failed to read message from socket")?;
- Ok(serde_json::from_str(&line).map_err(|e| {
- format!("failed to parse message '{}': {}", line, e)
- }))
+ Ok(serde_json::from_str(&line)
+ .map_err(|e| format!("failed to parse message '{line}': {e}")))
}
}
@@ -46,7 +45,7 @@ pub fn listen() -> anyhow::Result<tokio::net::UnixListener> {
let path = rbw::dirs::socket_file();
// if the socket already doesn't exist, that's fine
// https://github.com/rust-lang/rust-clippy/issues/8003
- #[allow(clippy::let_underscore_drop)]
+ #[allow(let_underscore_drop)]
let _ = std::fs::remove_file(&path);
let sock = tokio::net::UnixListener::bind(&path)
.context("failed to listen on socket")?;
diff --git a/src/bin/rbw/actions.rs b/src/bin/rbw/actions.rs
index 321bff5..7ca0ef9 100644
--- a/src/bin/rbw/actions.rs
+++ b/src/bin/rbw/actions.rs
@@ -33,9 +33,9 @@ pub fn quit() -> anyhow::Result<()> {
std::fs::File::open(pidfile)?.read_to_string(&mut pid)?;
let pid = nix::unistd::Pid::from_raw(pid.parse()?);
sock.send(&rbw::protocol::Request {
- tty: nix::unistd::ttyname(0)
- .ok()
- .and_then(|p| p.to_str().map(std::string::ToString::to_string)),
+ tty: nix::unistd::ttyname(0).ok().and_then(|p| {
+ p.to_str().map(std::string::ToString::to_string)
+ }),
action: rbw::protocol::Action::Quit,
})?;
wait_for_exit(pid);
diff --git a/src/bin/rbw/commands.rs b/src/bin/rbw/commands.rs
index fd720cf..dda35e8 100644
--- a/src/bin/rbw/commands.rs
+++ b/src/bin/rbw/commands.rs
@@ -30,11 +30,11 @@ impl DecryptedCipher {
DecryptedData::Login { password, .. } => {
password.as_ref().map_or_else(
|| {
- eprintln!("entry for '{}' had no password", desc);
+ eprintln!("entry for '{desc}' had no password");
false
},
|password| {
- println!("{}", password);
+ println!("{password}");
true
},
)
@@ -42,11 +42,11 @@ impl DecryptedCipher {
DecryptedData::Card { number, .. } => {
number.as_ref().map_or_else(
|| {
- eprintln!("entry for '{}' had no card number", desc);
+ eprintln!("entry for '{desc}' had no card number");
false
},
|number| {
- println!("{}", number);
+ println!("{number}");
true
},
)
@@ -62,11 +62,11 @@ impl DecryptedCipher {
[title, first_name, middle_name, last_name]
.iter()
.copied()
- .cloned()
.flatten()
+ .cloned()
.collect();
if names.is_empty() {
- eprintln!("entry for '{}' had no name", desc);
+ eprintln!("entry for '{desc}' had no name");
false
} else {
println!("{}", names.join(" "));
@@ -75,11 +75,11 @@ impl DecryptedCipher {
}
DecryptedData::SecureNote {} => self.notes.as_ref().map_or_else(
|| {
- eprintln!("entry for '{}' had no notes", desc);
+ eprintln!("entry for '{desc}' had no notes");
false
},
|notes| {
- println!("{}", notes);
+ println!("{notes}");
true
},
),
@@ -99,7 +99,7 @@ impl DecryptedCipher {
} => match field {
"notes" => {
if let Some(notes) = &self.notes {
- println!("{}", notes);
+ println!("{notes}");
}
}
"username" | "user" => {
@@ -107,8 +107,8 @@ impl DecryptedCipher {
}
"totp" | "code" => {
if let Some(totp) = totp {
- if let Ok(code) = generate_totp(&totp) {
- println!("{}", code);
+ if let Ok(code) = generate_totp(totp) {
+ println!("{code}");
}
}
}
@@ -120,7 +120,7 @@ impl DecryptedCipher {
}
}
"password" => {
- self.display_short(&desc);
+ self.display_short(desc);
}
_ => {
for f in &self.fields {
@@ -148,13 +148,13 @@ impl DecryptedCipher {
..
} => match field {
"number" | "card" => {
- self.display_short(&desc);
+ self.display_short(desc);
}
"exp" => {
if let (Some(month), Some(year)) = (exp_month, exp_year) {
display_field(
"Exp",
- Some(format!("{}/{}", month, year).as_str()),
+ Some(format!("{month}/{year}").as_str()),
);
}
}
@@ -175,7 +175,7 @@ impl DecryptedCipher {
}
"notes" => {
if let Some(notes) = &self.notes {
- println!("{}", notes);
+ println!("{notes}");
}
}
_ => {
@@ -212,7 +212,7 @@ impl DecryptedCipher {
..
} => match field {
"name" => {
- self.display_short(&desc);
+ self.display_short(desc);
}
"email" => {
display_field("Email", email.as_deref());
@@ -251,7 +251,7 @@ impl DecryptedCipher {
}
"notes" => {
if let Some(notes) = &self.notes {
- println!("{}", notes);
+ println!("{notes}");
}
}
_ => {
@@ -311,7 +311,7 @@ impl DecryptedCipher {
for uri in uris {
displayed |= display_field("URI", Some(&uri.uri));
let match_type =
- uri.match_type.map(|ty| format!("{}", ty));
+ uri.match_type.map(|ty| format!("{ty}"));
displayed |= display_field(
"Match type",
match_type.as_deref(),
@@ -330,7 +330,7 @@ impl DecryptedCipher {
if displayed {
println!();
}
- println!("{}", notes);
+ println!("{notes}");
}
}
DecryptedData::Card {
@@ -346,7 +346,7 @@ impl DecryptedCipher {
if let (Some(exp_month), Some(exp_year)) =
(exp_month, exp_year)
{
- println!("Expiration: {}/{}", exp_month, exp_year);
+ println!("Expiration: {exp_month}/{exp_year}");
displayed = true;
}
displayed |= display_field("CVV", code.as_deref());
@@ -358,7 +358,7 @@ impl DecryptedCipher {
if displayed {
println!();
}
- println!("{}", notes);
+ println!("{notes}");
}
}
DecryptedData::Identity {
@@ -400,7 +400,7 @@ impl DecryptedCipher {
if displayed {
println!();
}
- println!("{}", notes);
+ println!("{notes}");
}
}
DecryptedData::SecureNote {} => {
@@ -616,7 +616,9 @@ pub fn config_set(key: &str, value: &str) -> anyhow::Result<()> {
"email" => config.email = Some(value.to_string()),
"base_url" => config.base_url = Some(value.to_string()),
"identity_url" => config.identity_url = Some(value.to_string()),
- "client_cert_path" => config.client_cert_path = Some(value.to_string()),
+ "client_cert_path" => {
+ config.client_cert_path = Some(value.to_string());
+ }
"lock_timeout" => {
let timeout = value
.parse()
@@ -731,14 +733,14 @@ pub fn list(fields: &[String]) -> anyhow::Result<()> {
ListField::User => match &cipher.data {
DecryptedData::Login { username, .. } => {
username.as_ref().map_or_else(
- || "".to_string(),
+ String::new,
std::string::ToString::to_string,
)
}
- _ => "".to_string(),
+ _ => String::new(),
},
ListField::Folder => cipher.folder.as_ref().map_or_else(
- || "".to_string(),
+ String::new,
std::string::ToString::to_string,
),
})
@@ -768,15 +770,15 @@ pub fn get(
let desc = format!(
"{}{}",
- user.map_or_else(|| "".to_string(), |s| format!("{}@", s)),
+ user.map_or_else(String::new, |s| format!("{s}@")),
name
);
let (_, decrypted) = find_entry(&db, name, user, folder)
- .with_context(|| format!("couldn't find entry for '{}'", desc))?;
+ .with_context(|| format!("couldn't find entry for '{desc}'"))?;
if full {
decrypted.display_long(&desc);
- } else if field != None {
+ } else if field.is_some() {
decrypted.display_field(&desc, field.unwrap());
} else {
decrypted.display_short(&desc);
@@ -796,12 +798,12 @@ pub fn code(
let desc = format!(
"{}{}",
- user.map_or_else(|| "".to_string(), |s| format!("{}@", s)),
+ user.map_or_else(String::new, |s| format!("{s}@")),
name
);
let (_, decrypted) = find_entry(&db, name, user, folder)
- .with_context(|| format!("couldn't find entry for '{}'", desc))?;
+ .with_context(|| format!("couldn't find entry for '{desc}'"))?;
if let DecryptedData::Login { totp, .. } = decrypted.data {
if let Some(totp) = totp {
@@ -924,7 +926,7 @@ pub fn generate(
ty: rbw::pwgen::Type,
) -> anyhow::Result<()> {
let password = rbw::pwgen::pwgen(ty, len);
- println!("{}", password);
+ println!("{password}");
if let Some(name) = name {
unlock()?;
@@ -1024,19 +1026,19 @@ pub fn edit(
let desc = format!(
"{}{}",
- username.map_or_else(|| "".to_string(), |s| format!("{}@", s)),
+ username.map_or_else(String::new, |s| format!("{s}@")),
name
);
let (entry, decrypted) = find_entry(&db, name, username, folder)
- .with_context(|| format!("couldn't find entry for '{}'", desc))?;
+ .with_context(|| format!("couldn't find entry for '{desc}'"))?;
let (data, notes, history) = match &decrypted.data {
DecryptedData::Login { password, .. } => {
let mut contents =
format!("{}\n", password.as_deref().unwrap_or(""));
if let Some(notes) = decrypted.notes {
- contents.push_str(&format!("\n{}\n", notes));
+ contents.push_str(&format!("\n{notes}\n"));
}
let contents = rbw::edit::edit(&contents, HELP)?;
@@ -1056,16 +1058,15 @@ pub fn edit(
})
.transpose()?;
let mut history = entry.history.clone();
- let (entry_username, entry_password, entry_uris, entry_totp) =
- match &entry.data {
- rbw::db::EntryData::Login {
- username,
- password,
- uris,
- totp,
- } => (username, password, uris, totp),
- _ => unreachable!(),
- };
+ let rbw::db::EntryData::Login {
+ username: entry_username,
+ password: entry_password,
+ uris: entry_uris,
+ totp: entry_totp,
+ } = &entry.data
+ else {
+ unreachable!();
+ };
if let Some(prev_password) = entry_password.clone() {
let new_history_entry = rbw::db::HistoryEntry {
@@ -1127,12 +1128,12 @@ pub fn remove(
let desc = format!(
"{}{}",
- username.map_or_else(|| "".to_string(), |s| format!("{}@", s)),
+ username.map_or_else(String::new, |s| format!("{s}@")),
name
);
let (entry, _) = find_entry(&db, name, username, folder)
- .with_context(|| format!("couldn't find entry for '{}'", desc))?;
+ .with_context(|| format!("couldn't find entry for '{desc}'"))?;
if let (Some(access_token), ()) =
rbw::actions::remove(access_token, refresh_token, &entry.id)?
@@ -1157,12 +1158,12 @@ pub fn history(
let desc = format!(
"{}{}",
- username.map_or_else(|| "".to_string(), |s| format!("{}@", s)),
+ username.map_or_else(String::new, |s| format!("{s}@")),
name
);
let (_, decrypted) = find_entry(&db, name, username, folder)
- .with_context(|| format!("couldn't find entry for '{}'", desc))?;
+ .with_context(|| format!("couldn't find entry for '{desc}'"))?;
for history in decrypted.history {
println!("{}: {}", history.last_used_date, history.password);
}
@@ -1251,7 +1252,7 @@ fn check_config() -> anyhow::Result<()> {
fn version_or_quit() -> anyhow::Result<u32> {
crate::actions::version().map_err(|e| {
// https://github.com/rust-lang/rust-clippy/issues/8003
- #[allow(clippy::let_underscore_drop)]
+ #[allow(let_underscore_drop)]
let _ = crate::actions::quit();
e
})
@@ -1639,7 +1640,7 @@ fn parse_editor(contents: &str) -> (Option<String>, Option<String>) {
let mut notes: String = lines
.skip_while(|line| line.is_empty())
.filter(|line| !line.starts_with('#'))
- .map(|line| format!("{}\n", line))
+ .map(|line| format!("{line}\n"))
.collect();
while notes.ends_with('\n') {
notes.pop();
@@ -1707,7 +1708,7 @@ fn parse_totp_secret(secret: &str) -> anyhow::Result<Vec<u8>> {
};
base32::decode(
base32::Alphabet::RFC4648 { padding: false },
- &secret_str.replace(" ", ""),
+ &secret_str.replace(' ', ""),
)
.ok_or_else(|| anyhow::anyhow!("totp secret was not valid base32"))
}
@@ -1819,7 +1820,7 @@ mod test {
) -> bool {
let res = find_entry_raw(entries, name, username, folder);
if let Err(e) = res {
- format!("{}", e).contains("no entry found")
+ format!("{e}").contains("no entry found")
} else {
false
}
@@ -1833,7 +1834,7 @@ mod test {
) -> bool {
let res = find_entry_raw(entries, name, username, folder);
if let Err(e) = res {
- format!("{}", e).contains("multiple entries found")
+ format!("{e}").contains("multiple entries found")
} else {
false
}
@@ -1892,7 +1893,7 @@ fn display_field(name: &str, field: Option<&str>) -> bool {
field.map_or_else(
|| false,
|field| {
- println!("{}: {}", name, field);
+ println!("{name}: {field}");
true
},
)
diff --git a/src/bin/rbw/main.rs b/src/bin/rbw/main.rs
index f56a5b1..994fb97 100644
--- a/src/bin/rbw/main.rs
+++ b/src/bin/rbw/main.rs
@@ -398,7 +398,7 @@ fn main(opt: Opt) {
.context(format!("rbw {}", opt.subcommand_name()));
if let Err(e) = res {
- eprintln!("{:#}", e);
+ eprintln!("{e:#}");
std::process::exit(1);
}
}
diff --git a/src/cipherstring.rs b/src/cipherstring.rs
index 39254c7..8e40ace 100644
--- a/src/cipherstring.rs
+++ b/src/cipherstring.rs
@@ -247,18 +247,18 @@ impl std::fmt::Display for CipherString {
ciphertext,
mac,
} => {
- let iv = base64::encode(&iv);
- let ciphertext = base64::encode(&ciphertext);
+ let iv = base64::encode(iv);
+ let ciphertext = base64::encode(ciphertext);
if let Some(mac) = &mac {
- let mac = base64::encode(&mac);
- write!(f, "2.{}|{}|{}", iv, ciphertext, mac)
+ let mac = base64::encode(mac);
+ write!(f, "2.{iv}|{ciphertext}|{mac}")
} else {
- write!(f, "2.{}|{}", iv, ciphertext)
+ write!(f, "2.{iv}|{ciphertext}")
}
}
Self::Asymmetric { ciphertext } => {
- let ciphertext = base64::encode(&ciphertext);
- write!(f, "4.{}", ciphertext)
+ let ciphertext = base64::encode(ciphertext);
+ write!(f, "4.{ciphertext}")
}
}
}
diff --git a/src/config.rs b/src/config.rs
index baa855b..11864f1 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -152,8 +152,7 @@ impl Config {
#[must_use]
pub fn client_cert_path(&self) -> String {
- self.client_cert_path.clone()
- .unwrap_or_else(|| "".to_string())
+ self.client_cert_path.clone().unwrap_or_default()
}
#[must_use]
diff --git a/src/dirs.rs b/src/dirs.rs
index 429f8bd..e838e12 100644
--- a/src/dirs.rs
+++ b/src/dirs.rs
@@ -49,7 +49,7 @@ pub fn db_file(server: &str, email: &str) -> std::path::PathBuf {
let server =
percent_encoding::percent_encode(server.as_bytes(), INVALID_PATH)
.to_string();
- cache_dir().join(format!("{}:{}.json", server, email))
+ cache_dir().join(format!("{server}:{email}.json"))
}
#[must_use]
@@ -102,22 +102,24 @@ fn data_dir() -> std::path::PathBuf {
fn runtime_dir() -> std::path::PathBuf {
let project_dirs =
directories::ProjectDirs::from("", "", &profile()).unwrap();
- match project_dirs.runtime_dir() {
- Some(dir) => dir.to_path_buf(),
- None => format!(
- "{}/{}-{}",
- std::env::temp_dir().to_string_lossy(),
- &profile(),
- nix::unistd::getuid().as_raw()
- )
- .into(),
- }
+ project_dirs.runtime_dir().map_or_else(
+ || {
+ format!(
+ "{}/{}-{}",
+ std::env::temp_dir().to_string_lossy(),
+ &profile(),
+ nix::unistd::getuid().as_raw()
+ )
+ .into()
+ },
+ std::path::Path::to_path_buf,
+ )
}
#[must_use]
pub fn profile() -> String {
match std::env::var("RBW_PROFILE") {
- Ok(profile) if !profile.is_empty() => format!("rbw-{}", profile),
+ Ok(profile) if !profile.is_empty() => format!("rbw-{profile}"),
_ => "rbw".to_string(),
}
}
diff --git a/src/edit.rs b/src/edit.rs
index 8f4e534..aa8c7b1 100644
--- a/src/edit.rs
+++ b/src/edit.rs
@@ -53,7 +53,7 @@ pub fn edit(contents: &str, help: &str) -> Result<String> {
(editor, editor_args)
};
- let res = std::process::Command::new(&cmd).args(&args).status();
+ let res = std::process::Command::new(cmd).args(&args).status();
match res {
Ok(res) => {
if !res.success() {
@@ -81,8 +81,6 @@ pub fn edit(contents: &str, help: &str) -> Result<String> {
}
fn contains_shell_metacharacters(cmd: &std::ffi::OsStr) -> bool {
- match cmd.to_str() {
- Some(s) => s.contains(&[' ', '$', '\'', '"'][..]),
- None => false,
- }
+ cmd.to_str()
+ .map_or(false, |s| s.contains(&[' ', '$', '\'', '"'][..]))
}
diff --git a/src/pinentry.rs b/src/pinentry.rs
index ce1227f..d3bf65a 100644
--- a/src/pinentry.rs
+++ b/src/pinentry.rs
@@ -34,18 +34,18 @@ pub async fn getpin(
.map_err(|source| Error::WriteStdin { source })?;
ncommands += 1;
stdin
- .write_all(format!("SETPROMPT {}\n", prompt).as_bytes())
+ .write_all(format!("SETPROMPT {prompt}\n").as_bytes())
.await
.map_err(|source| Error::WriteStdin { source })?;
ncommands += 1;
stdin
- .write_all(format!("SETDESC {}\n", desc).as_bytes())
+ .write_all(format!("SETDESC {desc}\n").as_bytes())
.await
.map_err(|source| Error::WriteStdin { source })?;
ncommands += 1;
if let Some(err) = err {
stdin
- .write_all(format!("SETERROR {}\n", err).as_bytes())
+ .write_all(format!("SETERROR {err}\n").as_bytes())
.await
.map_err(|source| Error::WriteStdin { source })?;
ncommands += 1;
@@ -77,15 +77,13 @@ pub async fn getpin(
Ok(crate::locked::Password::new(buf))
}
-async fn read_password<
- R: tokio::io::AsyncRead + tokio::io::AsyncReadExt + Unpin,
->(
+async fn read_password<R>(
mut ncommands: u8,
data: &mut [u8],
mut r: R,
) -> Result<usize>
where
- R: Send,
+ R: tokio::io::AsyncRead + tokio::io::AsyncReadExt + Unpin + Send,
{
let mut len = 0;
loop {
@@ -120,7 +118,7 @@ where
});
}
return Err(Error::PinentryErrorMessage {
- error: format!("unknown error ({})", code),
+ error: format!("unknown error ({code})"),
});
}
None => {