Fix clippy issues, mainly string capture.

This commit is contained in:
Rasmus Kaj 2023-01-28 18:32:47 +01:00
parent c9463bcb16
commit f692047889
17 changed files with 57 additions and 72 deletions

View File

@ -27,13 +27,12 @@ impl Findphotos {
if !self.base.is_empty() {
for base in &self.base {
crawl(&mut db, &pd, Path::new(base)).map_err(|e| {
Error::Other(format!("Failed to crawl {}: {}", base, e))
Error::Other(format!("Failed to crawl {base}: {e}"))
})?;
}
} else {
crawl(&mut db, &pd, Path::new("")).map_err(|e| {
Error::Other(format!("Failed to crawl: {}", e))
})?;
crawl(&mut db, &pd, Path::new(""))
.map_err(|e| Error::Other(format!("Failed to crawl: {e}")))?;
}
Ok(())
}

View File

@ -59,7 +59,7 @@ impl Makepublic {
)
.set(p::is_public.eq(true))
.execute(&mut db)?;
println!("Made {} images public.", n);
println!("Made {n} images public.");
Ok(())
}
(None, None, Some(image)) => one(&mut db, image),
@ -78,11 +78,11 @@ pub fn one(db: &mut PgConnection, tpath: &str) -> Result<(), Error> {
.get_result::<Photo>(db)
{
Ok(photo) => {
println!("Made {} public: {:?}", tpath, photo);
println!("Made {tpath} public: {photo:?}");
Ok(())
}
Err(DieselError::NotFound) => {
Err(Error::Other(format!("File {} is not known", tpath,)))
Err(Error::Other(format!("File {tpath} is not known",)))
}
Err(error) => Err(error.into()),
}

View File

@ -34,21 +34,21 @@ impl Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Connection(ref e) => write!(f, "Connection error: {}", e),
Error::Db(ref e) => write!(f, "Database error: {}", e),
Error::Io(ref e) => write!(f, "I/O error: {}", e),
Error::Connection(ref e) => write!(f, "Connection error: {e}"),
Error::Db(ref e) => write!(f, "Database error: {e}"),
Error::Io(ref e) => write!(f, "I/O error: {e}"),
Error::UnknownOrientation(ref o) => {
write!(f, "Unknown image orientation: {:?}", o)
write!(f, "Unknown image orientation: {o:?}")
}
Error::BadTimeFormat(ref e) => write!(f, "Bad time value: {}", e),
Error::BadIntFormat(ref e) => write!(f, "Bad int value: {}", e),
Error::Cache(ref e) => write!(f, "Memcached error: {}", e),
Error::BadTimeFormat(ref e) => write!(f, "Bad time value: {e}"),
Error::BadIntFormat(ref e) => write!(f, "Bad int value: {e}"),
Error::Cache(ref e) => write!(f, "Memcached error: {e}"),
Error::MissingHeight => write!(f, "Missing height property"),
Error::MissingWidth => write!(f, "Missing width property"),
Error::PlacesFailed(ref e) => {
write!(f, "Failed to get places: {:?}", e)
write!(f, "Failed to get places: {e:?}")
}
Error::Other(ref s) => write!(f, "Error: {}", s),
Error::Other(ref s) => write!(f, "Error: {s}"),
}
}
}
@ -90,7 +90,7 @@ impl From<io::Error> for Error {
}
impl From<Utf8Error> for Error {
fn from(e: Utf8Error) -> Self {
Error::Other(format!("{}", e))
Error::Other(e.to_string())
}
}
@ -102,6 +102,6 @@ impl From<fetch_places::Error> for Error {
impl From<R2d2Error> for Error {
fn from(e: R2d2Error) -> Self {
Error::Other(format!("{}", e))
Error::Other(e.to_string())
}
}

View File

@ -24,18 +24,17 @@ pub fn passwd(db: &mut PgConnection, uname: &str) -> Result<(), Error> {
.execute(db)?
{
1 => {
println!("Updated password for {:?} to {:?}", uname, pword);
println!("Updated password for {uname:?} to {pword:?}");
}
0 => {
insert_into(users)
.values((username.eq(uname), password.eq(&hashword)))
.execute(db)?;
println!("Created user {:?} with password {:?}", uname, pword);
println!("Created user {uname:?} with password {pword:?}");
}
n => {
println!(
"Strange, updated {} passwords for {:?} to {:?}",
n, uname, pword,
"Strange, updated {n} passwords for {uname:?} to {pword:?}",
);
}
};

View File

@ -40,7 +40,7 @@ impl Fetchplaces {
.limit(self.limit)
.load::<(i32, Coord)>(&mut db.get()?)?;
for (photo_id, coord) in result {
println!("Find places for #{}, {:?}", photo_id, coord);
println!("Find places for #{photo_id}, {coord:?}");
self.overpass.update_image_places(&db, photo_id).await?;
}
} else {
@ -321,7 +321,7 @@ fn get_or_create_place(
while is_duplicate(&result) && attempt < 25 {
info!("Attempt #{} got {:?}, trying again", attempt, result);
attempt += 1;
let name = format!("{} ({})", name, attempt);
let name = format!("{name} ({attempt})");
result = diesel::insert_into(places)
.values((
place_name.eq(&name),

View File

@ -92,7 +92,7 @@ async fn main() {
match run(&RPhotos::parse()).await {
Ok(()) => (),
Err(err) => {
println!("{}", err);
println!("{err}");
exit(1);
}
}

View File

@ -222,10 +222,7 @@ impl Photo {
Photo {
id: ((((((y as u32 * 12) + mo) * 30 + da) * 24) + h) * 60 + s)
as i32,
path: format!(
"{}/{:02}/{:02}/IMG{:02}{:02}{:02}.jpg",
y, mo, da, h, m, s,
),
path: format!("{y}/{mo:02}/{da:02}/IMG{h:02}{m:02}{s:02}.jpg"),
date: NaiveDate::from_ymd_opt(y, mo, da)
.unwrap()
.and_hms_opt(h, m, s),

View File

@ -169,7 +169,7 @@ fn is_lat_long(f: &Field, tag: Tag) -> Option<f64> {
Some(v[0].to_f64() + d * (v[1].to_f64() + d * v[2].to_f64()))
}
ref v => {
println!("ERROR: Bad value for {}: {:?}", tag, v);
println!("ERROR: Bad value for {tag}: {v:?}");
None
}
}
@ -183,7 +183,7 @@ fn is_datetime(f: &Field, tag: Tag) -> Option<NaiveDateTime> {
single_ascii(&f.value)
.and_then(|s| Ok(NaiveDateTime::parse_from_str(s, "%Y:%m:%d %T")?))
.map_err(|e| {
println!("ERROR: Expected datetime for {}: {:?}", tag, e);
println!("ERROR: Expected datetime for {tag}: {e:?}");
})
.ok()
} else {
@ -196,7 +196,7 @@ fn is_date(f: &Field, tag: Tag) -> Option<NaiveDate> {
single_ascii(&f.value)
.and_then(|s| Ok(NaiveDate::parse_from_str(s, "%Y:%m:%d")?))
.map_err(|e| {
println!("ERROR: Expected date for {}: {:?}", tag, e);
println!("ERROR: Expected date for {tag}: {e:?}");
})
.ok()
} else {
@ -233,7 +233,7 @@ fn is_string(f: &Field, tag: Tag) -> Option<&str> {
match single_ascii(&f.value) {
Ok(s) => Some(s),
Err(err) => {
println!("ERROR: Expected string for {}: {:?}", tag, err);
println!("ERROR: Expected string for {tag}: {err:?}");
None
}
}
@ -248,7 +248,7 @@ fn is_u32(f: &Field, tag: Tag) -> Option<u32> {
Value::Long(ref v) if v.len() == 1 => Some(v[0]),
Value::Short(ref v) if v.len() == 1 => Some(u32::from(v[0])),
v => {
println!("ERROR: Unsuppored value for {}: {:?}", tag, v);
println!("ERROR: Unsuppored value for {tag}: {v:?}");
None
}
}
@ -264,16 +264,14 @@ fn single_ascii(value: &Value) -> Result<&str, Error> {
for t in &v[1..] {
if !t.is_empty() {
return Err(Error::Other(format!(
"Got {:?}, expected single ascii value",
v,
"Got {v:?}, expected single ascii value",
)));
}
}
Ok(from_utf8(&v[0])?)
}
v => Err(Error::Other(format!(
"Got {:?}, expected single ascii value",
v,
"Got {v:?}, expected single ascii value",
))),
}
}

View File

@ -57,7 +57,7 @@ impl PhotosDir {
path.to_str().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Non-utf8 path {:?}", path),
format!("Non-utf8 path {path:?}"),
)
})
}

View File

@ -15,7 +15,7 @@ pub fn handle_pid_file(pidfile: &Path, replace: bool) -> Result<(), Error> {
}
}
} else if pidfile.exists() {
return Err(Error::Other(format!("Pid file {:?} exists.", pidfile)));
return Err(Error::Other(format!("Pid file {pidfile:?} exists.")));
}
let pid = process::id();
debug!("Should write pid {} to {:?}", pid, pidfile);

View File

@ -76,27 +76,22 @@ impl GlobalContext {
fn verify_key(&self, jwtstr: &str) -> Result<String, String> {
let token = Token::<Header, ()>::parse(jwtstr)
.map_err(|e| format!("Bad jwt token: {:?}", e))?;
.map_err(|e| format!("Bad jwt token: {e:?}"))?;
if !verify_token(&token, self.jwt_secret.as_ref())? {
return Err(format!("Invalid token {:?}", token));
return Err(format!("Invalid token {token:?}"));
}
let claims = token.payload;
debug!("Verified token for: {:?}", claims);
let now = current_numeric_date();
if let Some(nbf) = claims.nbf {
if now < nbf {
return Err(
format!("Not-yet valid token, {} < {}", now, nbf,),
);
return Err(format!("Not-yet valid token, {now} < {nbf}"));
}
}
if let Some(exp) = claims.exp {
if now > exp {
return Err(format!(
"Got an expired token: {} > {}",
now, exp,
));
return Err(format!("Got an expired token: {now} > {exp}"));
}
}
// the claimed sub is the username
@ -115,7 +110,7 @@ fn verify_token(
) -> Result<bool, String> {
token
.verify(jwt_secret)
.map_err(|e| format!("Failed to verify token {:?}: {}", token, e))
.map_err(|e| format!("Failed to verify token {token:?}: {e}"))
}
/// The request context, providing database, memcache and authorized user.

View File

@ -44,7 +44,7 @@ fn post_login(context: Context, form: LoginForm) -> Result<Response> {
return Ok(Builder::new()
.header(
header::SET_COOKIE,
format!("EXAUTH={}; SameSite=Strict; HttpOnly", token),
format!("EXAUTH={token}; SameSite=Strict; HttpOnly"),
)
.redirect(next.unwrap_or("/")));
}

View File

@ -118,7 +118,7 @@ fn wrap(result: Result<impl Reply>) -> Response {
}
fn redirect_to_img(image: i32) -> Response {
redirect(&format!("/img/{}", image))
redirect(&format!("/img/{image}"))
}
fn redirect(url: &str) -> Response {
@ -187,8 +187,7 @@ pub type Link = Html<String>;
impl Link {
fn year(year: i32) -> Self {
Html(format!(
"<a href='/{0}/' title='Images from {0}' accessKey='y'>{0}</a>",
year,
"<a href='/{year}/' title='Images from {year}' accessKey='y'>{year}</a>",
))
}
fn month(year: i32, month: u32) -> Self {
@ -212,16 +211,14 @@ impl Link {
}
fn prev(from: i32) -> Self {
Html(format!(
"<a href='/prev?from={}' title='Previous image (by time)'>\
"<a href='/prev?from={from}' title='Previous image (by time)'>\
\u{2190}</a>",
from,
))
}
fn next(from: i32) -> Self {
Html(format!(
"<a href='/next?from={}' title='Next image (by time)' \
"<a href='/next?from={from}' title='Next image (by time)' \
accessKey='n'>\u{2192}</a>",
from,
))
}
}

View File

@ -72,7 +72,7 @@ impl PhotoLink {
to_year
};
(
Some(format!("{} - {}", from_year, to_year)),
Some(format!("{from_year} - {to_year}")),
format!(
"{} - {} ({})",
from.format("%F"),

View File

@ -13,7 +13,7 @@ impl BuilderExt for Builder {
fn redirect(self, url: &str) -> Response {
self.status(StatusCode::FOUND)
.header(header::LOCATION, url)
.body(format!("Please refer to {}", url).into())
.body(format!("Please refer to {url}").into())
.unwrap()
}

View File

@ -16,7 +16,7 @@ impl UrlString {
self.separate();
use std::fmt::Write;
self.value
.write_fmt(format_args!("{}={}", name, val))
.write_fmt(format_args!("{name}={val}"))
.expect("a Display implementation returned an error unexpectedly");
self.has_query = true;
}

View File

@ -127,11 +127,11 @@ fn all_years(context: Context) -> Result<Response> {
let photo = photo.first::<Photo>(&mut db)?;
Ok(PhotoLink {
title: Some(
year.map(|y| format!("{}", y))
year.map(|y| format!("{y}"))
.unwrap_or_else(|| "-".to_string()),
),
href: format!("/{}/", year.unwrap_or(0)),
lable: Some(format!("{} images", count)),
lable: Some(format!("{count} images")),
id: photo.id,
size: photo.get_size(SizeTag::Small),
})
@ -146,7 +146,7 @@ fn all_years(context: Context) -> Result<Response> {
fn months_in_year(year: i32, context: Context) -> Result<Response> {
use crate::schema::photos::dsl as p;
let title: String = format!("Photos from {}", year);
let title: String = format!("Photos from {year}");
let mut db = context.db()?;
let m = month_of_timestamp(p::date);
let groups = p::photos
@ -171,8 +171,8 @@ fn months_in_year(year: i32, context: Context) -> Result<Response> {
Ok(PhotoLink {
title: Some(monthname(month).to_string()),
href: format!("/{}/{}/", year, month),
lable: Some(format!("{} pictures", count)),
href: format!("/{year}/{month}/"),
lable: Some(format!("{count} pictures")),
id: photo.id,
size: photo.get_size(SizeTag::Small),
})
@ -246,9 +246,9 @@ fn days_in_month(year: i32, month: u32, context: Context) -> Result<Response> {
.first::<Photo>(&mut db)?;
Ok(PhotoLink {
title: Some(format!("{}", day)),
href: format!("/{}/{}/{}", year, month, day),
lable: Some(format!("{} pictures", count)),
title: Some(format!("{day}")),
href: format!("/{year}/{month}/{day}"),
lable: Some(format!("{count} pictures")),
id: photo.id,
size: photo.get_size(SizeTag::Small),
})
@ -370,9 +370,9 @@ fn on_this_day(context: Context) -> Result<Response> {
.limit(1)
.first::<Photo>(&mut db)?;
Ok(PhotoLink {
title: Some(format!("{}", year)),
href: format!("/{}/{}/{}", year, month, day),
lable: Some(format!("{} pictures", count)),
title: Some(format!("{year}")),
href: format!("/{year}/{month}/{day}"),
lable: Some(format!("{count} pictures")),
id: photo.id,
size: photo.get_size(SizeTag::Small),
})