From 38711abc3794c8eb0973001665ffe7b7f2eb81a9 Mon Sep 17 00:00:00 2001 From: Rasmus Kaj Date: Wed, 27 Sep 2017 00:19:03 +0200 Subject: [PATCH] Some lint-style changes suggested by clippy. --- src/adm/findphotos.rs | 23 ++++++++++++----------- src/adm/makepublic.rs | 4 ++-- src/adm/precache.rs | 6 +++--- src/adm/readkpa.rs | 24 ++++++++++-------------- src/adm/result.rs | 18 +++++++++--------- src/adm/users.rs | 10 +++++----- src/main.rs | 4 ++-- src/memcachemiddleware.rs | 14 +++++++------- src/models.rs | 4 ++-- src/nickel_diesel.rs | 2 +- src/photosdir.rs | 28 ++++++++++++---------------- src/pidfiles.rs | 6 ++---- src/requestloggermiddleware.rs | 4 ++-- src/server/mod.rs | 18 +++++++++--------- src/server/views_by_date.rs | 4 ++-- templates/person.rs.html | 2 +- templates/place.rs.html | 2 +- templates/tag.rs.html | 2 +- 18 files changed, 83 insertions(+), 92 deletions(-) diff --git a/src/adm/findphotos.rs b/src/adm/findphotos.rs index b76db04..64bac85 100644 --- a/src/adm/findphotos.rs +++ b/src/adm/findphotos.rs @@ -10,13 +10,14 @@ use std::path::Path; pub fn crawl(db: &PgConnection, photos: &PhotosDir, only_in: &Path) -> Result<(), Error> { - photos.find_files(only_in, - &|path, exif| { - match save_photo(&db, path, &exif) { - Ok(()) => debug!("Saved photo {}", path), - Err(e) => warn!("Failed to save photo {}: {:?}", path, e), - } - })?; + photos.find_files( + only_in, + &|path, exif| { + match save_photo(db, path, exif) { + Ok(()) => debug!("Saved photo {}", path), + Err(e) => warn!("Failed to save photo {}: {:?}", path, e), + } + })?; Ok(()) } @@ -26,8 +27,8 @@ fn save_photo(db: &PgConnection, -> Result<(), Error> { let photo = match Photo::create_or_set_basics(db, file_path, - find_date(&exif).ok(), - find_rotation(&exif)?, + find_date(exif).ok(), + find_rotation(exif)?, find_camera(db, exif)?)? { Modification::Created(photo) => { info!("Created {:?}", photo); @@ -42,7 +43,7 @@ fn save_photo(db: &PgConnection, photo } }; - if let Some((lat, long)) = find_position(&exif)? { + if let Some((lat, long)) = find_position(exif)? { debug!("Position for {} is {} {}", file_path, lat, long); use schema::positions::dsl::*; if let Ok((pos, clat, clong)) = @@ -89,7 +90,7 @@ fn find_camera(db: &PgConnection, } fn find_rotation(exif: &ExifData) -> Result { - if let Some(ref value) = find_entry(exif, &ExifTag::Orientation) { + if let Some(value) = find_entry(exif, &ExifTag::Orientation) { if let TagValue::U16(ref v) = value.value { let n = v[0]; debug!("Raw orientation is {}", n); diff --git a/src/adm/makepublic.rs b/src/adm/makepublic.rs index cd7615b..9087479 100644 --- a/src/adm/makepublic.rs +++ b/src/adm/makepublic.rs @@ -24,7 +24,7 @@ pub fn one(db: &PgConnection, return Err(Error::Other(format!("File {} does not exist", tpath))); } - let photo = register_photo(db, &tpath)?; + let photo = register_photo(db, tpath)?; println!("New photo {:?} is public.", photo); Ok(()) } @@ -47,7 +47,7 @@ fn register_photo(db: &PgConnection, -> Result { use schema::photos::dsl::{photos, is_public}; let photo = - match Photo::create_or_set_basics(&db, &tpath, None, 0, None)? { + match Photo::create_or_set_basics(db, tpath, None, 0, None)? { Modification::Created(photo) => photo, Modification::Updated(photo) => photo, Modification::Unchanged(photo) => photo, diff --git a/src/adm/precache.rs b/src/adm/precache.rs index d9ddc20..53d11dd 100644 --- a/src/adm/precache.rs +++ b/src/adm/precache.rs @@ -24,9 +24,9 @@ pub fn precache(db: &PgConnection, pd: &PhotosDir) -> Result<(), Error> { .load::(db)?; let no_expire = 0; for photo in photos { - n = n + 1; + n += 1; let key = &photo.cache_key(&size); - if cache.get(&key.as_bytes()).is_ok() { + if cache.get(key.as_bytes()).is_ok() { debug!("Cache: {} found for {}", key, photo.path); } else { let size = size.px(); @@ -37,7 +37,7 @@ pub fn precache(db: &PgConnection, pd: &PhotosDir) -> Result<(), Error> { })?; cache.set(key.as_bytes(), &data, 0, no_expire)?; debug!("Cache: stored {} for {}", key, photo.path); - n_stored = n_stored + 1; + n_stored += 1; if n_stored % 64 == 0 { info!("{} images of {} updated in cache ...", n_stored, n); } diff --git a/src/adm/readkpa.rs b/src/adm/readkpa.rs index f23ea1f..8c2e1f0 100644 --- a/src/adm/readkpa.rs +++ b/src/adm/readkpa.rs @@ -35,7 +35,7 @@ pub fn readkpa(db: &PgConnection, dir: &Path) -> Result<()> { .unwrap_or("0") .parse::()?; let date = find_image_date(attributes); - match photo_by_path(db, &file, date, angle) { + match photo_by_path(db, file, date, angle) { Ok(p) => { photo = Some(p) } Err(e) => { error!("{}", e); @@ -53,16 +53,16 @@ pub fn readkpa(db: &PgConnection, dir: &Path) -> Result<()> { option.as_ref().map(|s| s.as_ref()), find_attr("value", attributes)) { (Some(p), Some("Nyckelord"), Some(v)) => { - tag_photo(db, p, &v) + tag_photo(db, p, v) } (Some(p), Some("Personer"), Some(v)) => { - person_photo(db, p, &v) + person_photo(db, p, v) } (Some(p), Some("Platser"), Some(v)) => { - place_photo(db, p, &v) + place_photo(db, p, v) } (Some(p), Some("Betyg"), Some(v)) => { - grade_photo(db, p, &v) + grade_photo(db, p, v) } (None, _option, _value_in_categories) => Ok(()), (p, o, v) => { @@ -79,11 +79,8 @@ pub fn readkpa(db: &PgConnection, dir: &Path) -> Result<()> { } } XmlEvent::EndElement { ref name } => { - match &*name.local_name { - "option" => { - option = None; - } - _ => {} + if name.local_name == "option" { + option = None; } } _ => {} @@ -252,9 +249,8 @@ fn grade_photo(db: &PgConnection, photo: &mut Photo, name: &str) -> Result<()> { fn slugify(val: &str) -> String { val.chars() .map(|c| match c { - c @ '0'...'9' => c, - c @ 'a'...'z' => c, - c @ 'A'...'Z' => (c as u8 - 'A' as u8 + 'a' as u8) as char, + c @ '0'...'9' | c @ 'a'...'z'=> c, + c @ 'A'...'Z' => (c as u8 - b'A' + b'a') as char, 'Å' | 'å' | 'Ä' | 'ä' => 'a', 'Ö' | 'ö' | 'Ô' | 'ô' => 'o', 'É' | 'é' | 'Ë' | 'ë' | 'Ê' | 'ê' => 'e', @@ -264,7 +260,7 @@ fn slugify(val: &str) -> String { .collect() } -fn find_image_date(attributes: &Vec) -> Option { +fn find_image_date(attributes: &[OwnedAttribute]) -> Option { let start_date = find_attr("startDate", attributes).unwrap_or(""); let end_date = find_attr("endDate", attributes).unwrap_or(""); let format = "%FT%T"; diff --git a/src/adm/result.rs b/src/adm/result.rs index 7cb5415..b4eed0c 100644 --- a/src/adm/result.rs +++ b/src/adm/result.rs @@ -20,17 +20,17 @@ pub enum 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::UnknownOrientation(ref o) => { + 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::UnknownOrientation(ref 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::Other(ref s) => write!(f, "Error: {}", s), + 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::Other(ref s) => write!(f, "Error: {}", s), } } } diff --git a/src/adm/users.rs b/src/adm/users.rs index 6a74f27..873bacf 100644 --- a/src/adm/users.rs +++ b/src/adm/users.rs @@ -28,7 +28,7 @@ pub fn passwd(db: &PgConnection, uname: &str) -> Result<(), Error> { 0 => { use models::NewUser; insert(&NewUser { - username: &uname, + username: uname, password: &hashword, }) .into(users) @@ -47,13 +47,13 @@ pub fn passwd(db: &PgConnection, uname: &str) -> Result<(), Error> { fn random_password(len: usize) -> String { let rng = &mut OsRng::new().expect("Init rng"); - let nlc = 'z' as u8 - 'a' as u8 + 1; + let nlc = b'z' - b'a' + 1; let x = Range::new(0, 6 * nlc + 4 * 10 + 1); (0..len) .map(|_| match x.ind_sample(rng) { - n if n < (1 * nlc) => ('A' as u8 + (n % nlc)) as char, - n if n < (6 * nlc) => ('a' as u8 + (n % nlc)) as char, - n => ('0' as u8 + n % 10) as char, + n if n < (1 * nlc) => (b'A' + (n % nlc)) as char, + n if n < (6 * nlc) => (b'a' + (n % nlc)) as char, + n => (b'0' + n % 10) as char, }) .collect() } diff --git a/src/main.rs b/src/main.rs index 599eb2f..9571b7e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -113,7 +113,7 @@ fn main() { before running"))) .get_matches(); - match run(args) { + match run(&args) { Ok(()) => (), Err(err) => { println!("{}", err); @@ -122,7 +122,7 @@ fn main() { } } -fn run(args: ArgMatches) -> Result<(), Error> { +fn run(args: &ArgMatches) -> Result<(), Error> { match args.subcommand() { ("findphotos", Some(args)) => { let pd = PhotosDir::new(photos_dir()); diff --git a/src/memcachemiddleware.rs b/src/memcachemiddleware.rs index de59de0..5751d45 100644 --- a/src/memcachemiddleware.rs +++ b/src/memcachemiddleware.rs @@ -48,22 +48,22 @@ pub enum McError { impl fmt::Display for McError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &McError::UninitializedMiddleware => { + match *self { + McError::UninitializedMiddleware => { write!(f, "middleware not properly initialized") } - &McError::IoError(ref err) => write!(f, "{}", err.description()), + McError::IoError(ref err) => write!(f, "{}", err.description()), } } } impl Error for McError { fn description(&self) -> &str { - match self { - &McError::UninitializedMiddleware => { + match *self { + McError::UninitializedMiddleware => { "middleware not properly initialized" } - &McError::IoError(ref err) => err.description(), + McError::IoError(ref err) => err.description(), } } } @@ -93,7 +93,7 @@ impl<'a, 'b, D> MemcacheRequestExtensions for Request<'a, 'b, D> { { match self.cache() { Ok(mut client) => { - match client.get(&key.as_bytes()) { + match client.get(key.as_bytes()) { Ok((data, _flags)) => { debug!("Cache: {} found", key); return Ok(data); diff --git a/src/models.rs b/src/models.rs index 32fcea4..9c8d017 100644 --- a/src/models.rs +++ b/src/models.rs @@ -86,7 +86,7 @@ impl Photo { .set(rotation.eq(exifrotation)) .get_result::(db)?; } - if let &Some(ref camera) = camera { + if let Some(ref camera) = *camera { if pic.camera_id != Some(camera.id) { change = true; pic = diesel::update(photos.find(pic.id)) @@ -117,7 +117,7 @@ impl Photo { Ok(result) } else { let pic = NewPhoto { - path: &file_path, + path: file_path, date: exifdate, rotation: exifrotation, camera_id: camera.map(|c| c.id), diff --git a/src/nickel_diesel.rs b/src/nickel_diesel.rs index fff76f4..678b7f7 100644 --- a/src/nickel_diesel.rs +++ b/src/nickel_diesel.rs @@ -52,7 +52,7 @@ impl Middleware for DieselMiddleware where T: Connection + Send + Any { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { - req.extensions_mut().insert::>(self.pool.clone()); + req.extensions_mut().insert::>(Arc::clone(&self.pool)); Ok(Continue(res)) } } diff --git a/src/photosdir.rs b/src/photosdir.rs index 07f6cec..c658051 100644 --- a/src/photosdir.rs +++ b/src/photosdir.rs @@ -67,23 +67,19 @@ impl PhotosDir { let path = entry?.path(); if fs::metadata(&path)?.is_dir() { self.find_files(&path, cb)?; + } else if let Ok(exif) = rexif::parse_file(&path) { + let path = path.to_str().unwrap(); + cb(&path[bl..], &exif); + } else if image::open(&path).is_ok() { + let none = ExifData { + mime: "".into(), + entries: vec![], + }; + info!("{:?} seems like a pic with no exif.", path); + let path = path.to_str().unwrap(); + cb(&path[bl..], &none); } else { - if let Ok(exif) = rexif::parse_file(&path) { - let path = path.to_str().unwrap(); - cb(&path[bl..], &exif); - } else { - if image::open(&path).is_ok() { - let none = ExifData { - mime: "".into(), - entries: vec![], - }; - info!("{:?} seems like a pic with no exif.", path); - let path = path.to_str().unwrap(); - cb(&path[bl..], &none); - } else { - debug!("{:?} is no pic.", path) - } - } + debug!("{:?} is no pic.", path) } } } diff --git a/src/pidfiles.rs b/src/pidfiles.rs index 38c0922..3cb4159 100644 --- a/src/pidfiles.rs +++ b/src/pidfiles.rs @@ -9,10 +9,8 @@ pub fn handle_pid_file(pidfile: &str, replace: bool) -> Result<(), String> { info!("Killing old pid {}.", oldpid); unsafe { kill(oldpid, SIGHUP); } } - } else { - if Path::new(pidfile).exists() { - return Err(format!("Pid file {:?} exists.", pidfile)) - } + } else if Path::new(pidfile).exists() { + return Err(format!("Pid file {:?} exists.", pidfile)) } let pid = unsafe { getpid() }; debug!("Should write pid {} to {}", pid, pidfile); diff --git a/src/requestloggermiddleware.rs b/src/requestloggermiddleware.rs index 0558cb2..984a365 100644 --- a/src/requestloggermiddleware.rs +++ b/src/requestloggermiddleware.rs @@ -42,7 +42,7 @@ fn fmt_elapsed(t: Duration) -> String { } else { let ns = t.num_nanoseconds().unwrap(); if ns > 10_000_000 { - format!("{} ms", ns / 1000_000) + format!("{} ms", ns / 1_000_000) } else if ns > 10_000 { format!("{} µs", ns / 1000) } else { @@ -63,7 +63,7 @@ impl Middleware for RequestLoggerMiddleware { let mu = format!("{} {}", req.origin.method, req.origin.uri); let status = Arc::new(Mutex::new(StatusCode::Continue)); req.extensions_mut().insert::( - RequestLogger::new(mu, status.clone())); + RequestLogger::new(mu, Arc::clone(&status))); res.on_send(move |r| { if let Ok(mut sw) = status.lock() { *sw = r.status(); diff --git a/src/server/mod.rs b/src/server/mod.rs index 0988ee6..572e169 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -197,7 +197,7 @@ fn logout<'mw>(_req: &mut Request, res.redirect("/") } -#[derive(Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SizeTag { Small, Medium, @@ -240,7 +240,7 @@ fn show_image<'mw>(req: &Request, return res.send_file(path); } } else { - let data = get_image_data(req, tphoto, size) + let data = get_image_data(req, &tphoto, size) .expect("Get image data"); res.set((MediaType::Jpeg, far_expires())); return res.send(data); @@ -251,13 +251,13 @@ fn show_image<'mw>(req: &Request, } fn get_image_data(req: &Request, - photo: Photo, + photo: &Photo, size: SizeTag) -> Result, image::ImageError> { req.cached_or(&photo.cache_key(&size), || { let size = size.px(); - req.photos().scale_image(&photo, size, size) + req.photos().scale_image(photo, size, size) }) } @@ -304,7 +304,7 @@ fn tag_one<'mw>(req: &mut Request, .order((grade.desc().nulls_last(), date.desc().nulls_last())) .load(c).unwrap(), - tag) + &tag) }) } res.not_found("Not a tag") @@ -365,7 +365,7 @@ fn place_one<'mw>(req: &mut Request, .filter(place_id.eq(place.id)))) .order((grade.desc().nulls_last(), date.desc().nulls_last())) .load(c).unwrap(), - place)); + &place)); } res.not_found("Not a place") } @@ -412,7 +412,7 @@ fn person_one<'mw>(req: &mut Request, .filter(person_id.eq(person.id)))) .order((grade.desc().nulls_last(), date.desc().nulls_last())) .load(c).unwrap(), - person)); + &person)); } res.not_found("Not a person") } @@ -460,8 +460,8 @@ fn photo_details<'mw>(req: &mut Request, .select((latitude, longitude)) .first::<(i32, i32)>(c) { Ok((tlat, tlong)) => Some(Coord { - x: tlat as f64 / 1e6, - y: tlong as f64 / 1e6, + x: f64::from(tlat) / 1e6, + y: f64::from(tlong) / 1e6, }), Err(diesel::NotFound) => None, Err(err) => { diff --git a/src/server/views_by_date.rs b/src/server/views_by_date.rs index 18a79b5..11ff947 100644 --- a/src/server/views_by_date.rs +++ b/src/server/views_by_date.rs @@ -161,7 +161,7 @@ pub fn all_null_date<'mw>(req: &mut Request, res.ok(|o| templates::index( o, req, - &"Photos without a date", + "Photos without a date", &[], &Photo::query(req.authorized_user().is_some()) .filter(date.is_null()) @@ -282,7 +282,7 @@ pub fn part_for_day<'mw>( Link::month(year, month), Link::day(year, month, day), ], - &photos, + photos, )) } else { res.not_found("No such image") diff --git a/templates/person.rs.html b/templates/person.rs.html index 93147b1..c53e4b8 100644 --- a/templates/person.rs.html +++ b/templates/person.rs.html @@ -2,7 +2,7 @@ @use models::{Photo, Person}; @use templates::{page_base, img_link}; -@(req: &Request, photos: &[Photo], person: Person) +@(req: &Request, photos: &[Photo], person: &Person) @:page_base(req, &format!("Photos with {}", person.person_name), &[], {
@for p in photos {@:img_link(p)} diff --git a/templates/place.rs.html b/templates/place.rs.html index 91fd832..2726dac 100644 --- a/templates/place.rs.html +++ b/templates/place.rs.html @@ -2,7 +2,7 @@ @use models::{Photo, Place}; @use templates::{page_base, img_link}; -@(req: &Request, photos: &[Photo], place: Place) +@(req: &Request, photos: &[Photo], place: &Place) @:page_base(req, &format!("Photos from {}", place.place_name), &[], {
@for p in photos {@:img_link(p)} diff --git a/templates/tag.rs.html b/templates/tag.rs.html index 283aacd..05fca4f 100644 --- a/templates/tag.rs.html +++ b/templates/tag.rs.html @@ -2,7 +2,7 @@ @use models::{Photo, Tag}; @use templates::{page_base, img_link}; -@(req: &Request, photos: &[Photo], tag: Tag) +@(req: &Request, photos: &[Photo], tag: &Tag) @:page_base(req, &format!("Photos tagged {}", tag.tag_name), &[], {