Some lint-style changes suggested by clippy.

This commit is contained in:
Rasmus Kaj 2017-09-27 00:19:03 +02:00
parent cde078317a
commit 38711abc37
18 changed files with 83 additions and 92 deletions

View File

@ -10,9 +10,10 @@ use std::path::Path;
pub fn crawl(db: &PgConnection, photos: &PhotosDir, only_in: &Path)
-> Result<(), Error> {
photos.find_files(only_in,
photos.find_files(
only_in,
&|path, exif| {
match save_photo(&db, path, &exif) {
match save_photo(db, path, exif) {
Ok(()) => debug!("Saved photo {}", path),
Err(e) => warn!("Failed to save photo {}: {:?}", path, e),
}
@ -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<i16, Error> {
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);

View File

@ -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<Photo, DieselError> {
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,

View File

@ -24,9 +24,9 @@ pub fn precache(db: &PgConnection, pd: &PhotosDir) -> Result<(), Error> {
.load::<Photo>(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);
}

View File

@ -35,7 +35,7 @@ pub fn readkpa(db: &PgConnection, dir: &Path) -> Result<()> {
.unwrap_or("0")
.parse::<i16>()?;
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,12 +79,9 @@ pub fn readkpa(db: &PgConnection, dir: &Path) -> Result<()> {
}
}
XmlEvent::EndElement { ref name } => {
match &*name.local_name {
"option" => {
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<OwnedAttribute>) -> Option<NaiveDateTime> {
fn find_image_date(attributes: &[OwnedAttribute]) -> Option<NaiveDateTime> {
let start_date = find_attr("startDate", attributes).unwrap_or("");
let end_date = find_attr("endDate", attributes).unwrap_or("");
let format = "%FT%T";

View File

@ -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),
}
}
}

View File

@ -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()
}

View File

@ -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());

View File

@ -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);

View File

@ -86,7 +86,7 @@ impl Photo {
.set(rotation.eq(exifrotation))
.get_result::<Photo>(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),

View File

@ -52,7 +52,7 @@ impl<T, D> Middleware<D> for DieselMiddleware<T> 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::<DieselMiddleware<T>>(self.pool.clone());
req.extensions_mut().insert::<DieselMiddleware<T>>(Arc::clone(&self.pool));
Ok(Continue(res))
}
}

View File

@ -67,12 +67,10 @@ 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) {
} 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() {
} else if image::open(&path).is_ok() {
let none = ExifData {
mime: "".into(),
entries: vec![],
@ -85,8 +83,6 @@ impl PhotosDir {
}
}
}
}
}
Ok(())
}
}

View File

@ -9,11 +9,9 @@ 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() {
} else if Path::new(pidfile).exists() {
return Err(format!("Pid file {:?} exists.", pidfile))
}
}
let pid = unsafe { getpid() };
debug!("Should write pid {} to {}", pid, pidfile);
File::create(pidfile)

View File

@ -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<D> Middleware<D> for RequestLoggerMiddleware {
let mu = format!("{} {}", req.origin.method, req.origin.uri);
let status = Arc::new(Mutex::new(StatusCode::Continue));
req.extensions_mut().insert::<RequestLoggerMiddleware>(
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();

View File

@ -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<Vec<u8>, 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) => {

View File

@ -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")

View File

@ -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), &[], {
<div class="group">
@for p in photos {@:img_link(p)}

View File

@ -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), &[], {
<div class="group">
@for p in photos {@:img_link(p)}

View File

@ -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), &[], {
<div class="group">