From ec69a3568feeaacd8dc9e37725dcd6c562b6eaeb Mon Sep 17 00:00:00 2001 From: Antoine Gersant <antoine.gersant@lesforges.org> Date: Sat, 6 Oct 2018 16:29:46 -0700 Subject: [PATCH] Fixed clippy lints --- src/api.rs | 30 +++++++++++------------------- src/config.rs | 9 ++++----- src/db/mod.rs | 2 +- src/ddns.rs | 20 ++++++++++---------- src/index.rs | 36 ++++++++++++++++++------------------ src/lastfm.rs | 6 +++--- src/main.rs | 10 +++++----- src/metadata.rs | 40 ++++++++++++++++++++-------------------- src/playlist.rs | 4 ++-- src/serve.rs | 6 +++--- src/thumbnails.rs | 2 +- src/user.rs | 2 +- src/vfs.rs | 34 ++++++++++++++-------------------- 13 files changed, 93 insertions(+), 108 deletions(-) diff --git a/src/api.rs b/src/api.rs index 48d3635..b9d54eb 100644 --- a/src/api.rs +++ b/src/api.rs @@ -54,8 +54,8 @@ where Ok(misc.auth_secret.to_owned()) } -pub fn get_handler(db: Arc<DB>, index: Arc<Mutex<Sender<index::Command>>>) -> Result<Chain> { - let api_handler = get_endpoints(db.clone(), index); +pub fn get_handler(db: &Arc<DB>, index: &Arc<Mutex<Sender<index::Command>>>) -> Result<Chain> { + let api_handler = get_endpoints(&db.clone(), &index); let mut api_chain = Chain::new(api_handler); let auth_secret = get_auth_secret(db.deref())?; @@ -72,7 +72,7 @@ pub fn get_handler(db: Arc<DB>, index: Arc<Mutex<Sender<index::Command>>>) -> Re Ok(api_chain) } -fn get_endpoints(db: Arc<DB>, index_channel: Arc<Mutex<Sender<index::Command>>>) -> Mount { +fn get_endpoints(db: &Arc<DB>, index_channel: &Arc<Mutex<Sender<index::Command>>>) -> Mount { let mut api_handler = Mount::new(); { @@ -259,7 +259,7 @@ impl AroundMiddleware for AuthRequirement { fn around(self, handler: Box<Handler>) -> Box<Handler> { Box::new(AuthHandler { db: self.db, - handler: handler, + handler, }) as Box<Handler> } } @@ -272,12 +272,8 @@ struct AuthHandler { impl Handler for AuthHandler { fn handle(&self, req: &mut Request) -> IronResult<Response> { { - let mut auth_success = false; - // Skip auth for first time setup - if user::count(self.db.deref())? == 0 { - auth_success = true; - } + let mut auth_success = user::count(self.db.deref())? == 0; // Auth via Authorization header if !auth_success { @@ -317,7 +313,7 @@ impl AroundMiddleware for AdminRequirement { fn around(self, handler: Box<Handler>) -> Box<Handler> { Box::new(AdminHandler { db: self.db, - handler: handler, + handler, }) as Box<Handler> } } @@ -330,12 +326,8 @@ struct AdminHandler { impl Handler for AdminHandler { fn handle(&self, req: &mut Request) -> IronResult<Response> { { - let mut auth_success = false; - // Skip auth for first time setup - if user::count(self.db.deref())? == 0 { - auth_success = true; - } + let mut auth_success = user::count(self.db.deref())? == 0; if !auth_success { match req.extensions.get::<SessionKey>() { @@ -674,10 +666,10 @@ fn read_playlist(request: &mut Request, db: &DB) -> IronResult<Response> { }; let params = request.extensions.get::<Router>().unwrap(); - let ref playlist_name = match params.find("playlist_name") { + let playlist_name = &(match params.find("playlist_name") { Some(s) => s, _ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()), - }; + }); let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() { Ok(s) => s, @@ -701,10 +693,10 @@ fn delete_playlist(request: &mut Request, db: &DB) -> IronResult<Response> { }; let params = request.extensions.get::<Router>().unwrap(); - let ref playlist_name = match params.find("playlist_name") { + let playlist_name = &(match params.find("playlist_name") { Some(s) => s, _ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()), - }; + }); let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() { Ok(s) => s, diff --git a/src/config.rs b/src/config.rs index 240c68f..ac22c12 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,7 +119,7 @@ where found_users .into_iter() .map(|(name, admin)| ConfigUser { - name: name, + name, password: "".to_owned(), admin: admin != 0, }).collect::<_>(), @@ -193,7 +193,7 @@ where .find(|old_name| *old_name == &u.name) .is_none() }).collect::<_>(); - for ref config_user in insert_users { + for config_user in &insert_users { let new_user = User::new(&config_user.name, &config_user.password); diesel::insert_into(users::table) .values(&new_user) @@ -201,7 +201,7 @@ where } // Update users - for ref user in config_users { + for user in config_users.iter() { // Update password if provided if !user.password.is_empty() { let salt: Vec<u8> = users::table @@ -282,8 +282,7 @@ fn _get_test_db(name: &str) -> DB { fs::remove_file(&db_path).unwrap(); } - let db = DB::new(&db_path).unwrap(); - db + DB::new(&db_path).unwrap() } #[test] diff --git a/src/db/mod.rs b/src/db/mod.rs index 05f15c4..c79f3ef 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -13,7 +13,7 @@ mod schema; pub use self::schema::*; #[allow(dead_code)] -const DB_MIGRATIONS_PATH: &'static str = "src/db/migrations"; +const DB_MIGRATIONS_PATH: &str = "src/db/migrations"; embed_migrations!("src/db/migrations"); pub trait ConnectionSource { diff --git a/src/ddns.rs b/src/ddns.rs index e6de3ae..dcf69bc 100644 --- a/src/ddns.rs +++ b/src/ddns.rs @@ -34,38 +34,38 @@ impl DDNSConfigSource for DB { #[derive(Debug)] enum DDNSError { - InternalError(errors::Error), - IoError(io::Error), - ReqwestError(reqwest::Error), - UpdateError(reqwest::StatusCode), + Internal(errors::Error), + Io(io::Error), + Reqwest(reqwest::Error), + Update(reqwest::StatusCode), } impl From<io::Error> for DDNSError { fn from(err: io::Error) -> DDNSError { - DDNSError::IoError(err) + DDNSError::Io(err) } } impl From<errors::Error> for DDNSError { fn from(err: errors::Error) -> DDNSError { - DDNSError::InternalError(err) + DDNSError::Internal(err) } } impl From<reqwest::Error> for DDNSError { fn from(err: reqwest::Error) -> DDNSError { - DDNSError::ReqwestError(err) + DDNSError::Reqwest(err) } } -const DDNS_UPDATE_URL: &'static str = "https://ydns.io/api/v1/update/"; +const DDNS_UPDATE_URL: &str = "https://ydns.io/api/v1/update/"; fn update_my_ip<T>(config_source: &T) -> Result<(), DDNSError> where T: DDNSConfigSource, { let config = config_source.get_ddns_config()?; - if config.host.len() == 0 || config.username.len() == 0 { + if config.host.is_empty() || config.username.is_empty() { info!("Skipping DDNS update because credentials are missing"); return Ok(()); } @@ -78,7 +78,7 @@ where let client = reqwest::Client::new()?; let res = client.get(full_url.as_str()).header(auth_header).send()?; if !res.status().is_success() { - return Err(DDNSError::UpdateError(*res.status())); + return Err(DDNSError::Update(*res.status())); } Ok(()) } diff --git a/src/index.rs b/src/index.rs index b589ba2..7fddf2c 100644 --- a/src/index.rs +++ b/src/index.rs @@ -120,10 +120,10 @@ impl<'conn> IndexBuilder<'conn> { new_songs.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE); new_directories.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE); Ok(IndexBuilder { - new_songs: new_songs, - new_directories: new_directories, - connection: connection, - album_art_pattern: album_art_pattern, + new_songs, + new_directories, + connection, + album_art_pattern, }) } @@ -197,7 +197,7 @@ impl<'conn> IndexBuilder<'conn> { let metadata = fs::metadata(path_string)?; let created = metadata .created() - .or(metadata.modified())? + .or_else(|_| metadata.modified())? .duration_since(time::UNIX_EPOCH)? .as_secs() as i32; @@ -237,17 +237,17 @@ impl<'conn> IndexBuilder<'conn> { if tags.album.is_some() { inconsistent_directory_album |= directory_album.is_some() && directory_album != tags.album; - directory_album = tags.album.as_ref().map(|a| a.clone()); + directory_album = tags.album.as_ref().cloned(); } if tags.album_artist.is_some() { inconsistent_directory_artist |= directory_artist.is_some() && directory_artist != tags.album_artist; - directory_artist = tags.album_artist.as_ref().map(|a| a.clone()); + directory_artist = tags.album_artist.as_ref().cloned(); } else if tags.artist.is_some() { inconsistent_directory_artist |= directory_artist.is_some() && directory_artist != tags.artist; - directory_artist = tags.artist.as_ref().map(|a| a.clone()); + directory_artist = tags.artist.as_ref().cloned(); } let song = NewSong { @@ -261,7 +261,7 @@ impl<'conn> IndexBuilder<'conn> { album_artist: tags.album_artist, album: tags.album, year: tags.year, - artwork: artwork.as_ref().map(|s| s.to_owned()), + artwork: artwork.as_ref().cloned(), }; self.push_song(song)?; @@ -283,7 +283,7 @@ impl<'conn> IndexBuilder<'conn> { let directory = NewDirectory { path: path_string.to_owned(), parent: parent_string, - artwork: artwork, + artwork, album: directory_album, artist: directory_artist, year: directory_year, @@ -373,7 +373,7 @@ where let connection_mutex = db.get_connection_mutex(); let mut builder = IndexBuilder::new(connection_mutex.deref(), album_art_pattern)?; - for (_, target) in mount_points { + for target in mount_points.values() { builder.populate_directory(None, target.as_path())?; } builder.flush_songs()?; @@ -396,7 +396,7 @@ where Ok(()) } -pub fn update_loop<T>(db: &T, command_buffer: Receiver<Command>) +pub fn update_loop<T>(db: &T, command_buffer: &Receiver<Command>) where T: ConnectionSource + VFSSource, { @@ -426,7 +426,7 @@ where } } -pub fn self_trigger<T>(db: &T, command_buffer: Arc<Mutex<Sender<Command>>>) +pub fn self_trigger<T>(db: &T, command_buffer: &Arc<Mutex<Sender<Command>>>) where T: ConnectionSource, { @@ -503,7 +503,7 @@ where output.extend( virtual_directories .into_iter() - .map(|d| CollectionFile::Directory(d)), + .map(CollectionFile::Directory), ); } else { // Browse sub-directory @@ -517,7 +517,7 @@ where let virtual_directories = real_directories .into_iter() .filter_map(|s| virtualize_directory(&vfs, s)); - output.extend(virtual_directories.map(|d| CollectionFile::Directory(d))); + output.extend(virtual_directories.map(CollectionFile::Directory)); let real_songs: Vec<Song> = songs::table .filter(songs::parent.eq(&real_path_string)) @@ -526,7 +526,7 @@ where let virtual_songs = real_songs .into_iter() .filter_map(|s| virtualize_song(&vfs, s)); - output.extend(virtual_songs.map(|s| CollectionFile::Song(s))); + output.extend(virtual_songs.map(CollectionFile::Song)); } Ok(output) @@ -614,7 +614,7 @@ where .into_iter() .filter_map(|s| virtualize_directory(&vfs, s)); - output.extend(virtual_directories.map(|d| CollectionFile::Directory(d))); + output.extend(virtual_directories.map(CollectionFile::Directory)); } // Find songs with matching title/album/artist and non-matching parent @@ -634,7 +634,7 @@ where .into_iter() .filter_map(|s| virtualize_song(&vfs, s)); - output.extend(virtual_songs.map(|s| CollectionFile::Song(s))); + output.extend(virtual_songs.map(CollectionFile::Song)); } Ok(output) diff --git a/src/lastfm.rs b/src/lastfm.rs index d4c4e6f..64858bd 100644 --- a/src/lastfm.rs +++ b/src/lastfm.rs @@ -53,9 +53,9 @@ where { let song = index::get_song(db, track)?; Ok(Scrobble::new( - song.artist.unwrap_or("".into()), - song.title.unwrap_or("".into()), - song.album.unwrap_or("".into()), + song.artist.unwrap_or_else(|| "".into()), + song.title.unwrap_or_else(|| "".into()), + song.album.unwrap_or_else(|| "".into()), )) } diff --git a/src/main.rs b/src/main.rs index 2b190e7..fb525e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -218,22 +218,22 @@ fn run() -> Result<()> { let db_ref = db.clone(); std::thread::spawn(move || { let db = db_ref.deref(); - index::update_loop(db, index_receiver); + index::update_loop(db, &index_receiver); }); // Trigger auto-indexing let db_ref = db.clone(); let sender_ref = index_sender.clone(); std::thread::spawn(move || { - index::self_trigger(db_ref.deref(), sender_ref); + index::self_trigger(db_ref.deref(), &sender_ref); }); // Mount API - let prefix_url = config.prefix_url.unwrap_or("".to_string()); + let prefix_url = config.prefix_url.unwrap_or_else(|| "".to_string()); let api_url = format!("{}/api", &prefix_url); info!("Mounting API on {}", api_url); let mut mount = Mount::new(); - let handler = api::get_handler(db.clone(), index_sender)?; + let handler = api::get_handler(&db.clone(), &index_sender)?; mount.mount(&api_url, handler); // Mount static files @@ -252,7 +252,7 @@ fn run() -> Result<()> { info!("Starting up server"); let port: u16 = matches .opt_str("p") - .unwrap_or("5050".to_owned()) + .unwrap_or_else(|| "5050".to_owned()) .parse() .or(Err("invalid port number"))?; diff --git a/src/metadata.rs b/src/metadata.rs index 57bf7cc..f5db638 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -48,18 +48,18 @@ fn read_id3(path: &Path) -> Result<SongTags> { let year = tag .year() .map(|y| y as i32) - .or(tag.date_released().and_then(|d| Some(d.year))) - .or(tag.date_recorded().and_then(|d| Some(d.year))); + .or_else(|| tag.date_released().and_then(|d| Some(d.year))) + .or_else(|| tag.date_recorded().and_then(|d| Some(d.year))); Ok(SongTags { - artist: artist, - album_artist: album_artist, - album: album, - title: title, - duration: duration, - disc_number: disc_number, - track_number: track_number, - year: year, + artist, + album_artist, + album, + title, + duration, + disc_number, + track_number, + year, }) } @@ -101,14 +101,14 @@ fn read_ape(path: &Path) -> Result<SongTags> { let disc_number = tag.item("Disc").and_then(read_ape_x_of_y); let track_number = tag.item("Track").and_then(read_ape_x_of_y); Ok(SongTags { - artist: artist, - album_artist: album_artist, - album: album, - title: title, + artist, + album_artist, + album, + title, duration: None, - disc_number: disc_number, - track_number: track_number, - year: year, + disc_number, + track_number, + year, }) } @@ -163,10 +163,10 @@ fn read_flac(path: &Path) -> Result<SongTags> { album_artist: vorbis.album_artist().map(|v| v[0].clone()), album: vorbis.album().map(|v| v[0].clone()), title: vorbis.title().map(|v| v[0].clone()), - duration: duration, - disc_number: disc_number, + duration, + disc_number, track_number: vorbis.track(), - year: year, + year, }) } diff --git a/src/playlist.rs b/src/playlist.rs index 7c1f5d0..ad2e7e0 100644 --- a/src/playlist.rs +++ b/src/playlist.rs @@ -73,7 +73,7 @@ pub fn list_playlists<T>(owner: &str, db: &T) -> Result<Vec<String>> pub fn save_playlist<T>(playlist_name: &str, owner: &str, - content: &Vec<String>, + content: &[String], db: &T) -> Result<()> where T: ConnectionSource + VFSSource @@ -124,7 +124,7 @@ pub fn save_playlist<T>(playlist_name: &str, .and_then(|p| p.to_str().map(|s| s.to_owned())) { new_songs.push(NewPlaylistSong { playlist: playlist.id, - path: real_path.into(), + path: real_path, ordering: i as i32, }); } diff --git a/src/serve.rs b/src/serve.rs index f40e17c..d7959b5 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -27,7 +27,7 @@ pub fn deliver(path: &Path, range_header: Option<&Range>) -> IronResult<Response }; let accept_range_header = Header(AcceptRanges(vec![RangeUnit::Bytes])); - let range_header = range_header.map(|h| h.clone()); + let range_header = range_header.cloned(); match range_header { None => Ok(Response::with((status::Ok, path, accept_range_header))), @@ -85,8 +85,8 @@ impl PartialFile { { let range = range.into(); PartialFile { - file: file, - range: range, + file, + range, } } diff --git a/src/thumbnails.rs b/src/thumbnails.rs index 4ddceb5..40af6b4 100644 --- a/src/thumbnails.rs +++ b/src/thumbnails.rs @@ -12,7 +12,7 @@ use std::path::*; use errors::*; use utils; -const THUMBNAILS_PATH: &'static str = "thumbnails"; +const THUMBNAILS_PATH: &str = "thumbnails"; fn hash(path: &Path, dimension: u32) -> u64 { let path_string = path.to_string_lossy(); diff --git a/src/user.rs b/src/user.rs index d798897..ef83f2a 100644 --- a/src/user.rs +++ b/src/user.rs @@ -35,7 +35,7 @@ impl User { } } -pub fn hash_password(salt: &Vec<u8>, password: &str) -> Vec<u8> { +pub fn hash_password(salt: &[u8], password: &str) -> Vec<u8> { let mut hash: PasswordHash = [0; CREDENTIAL_LEN]; pbkdf2::derive( DIGEST_ALG, diff --git a/src/vfs.rs b/src/vfs.rs index 6ab395e..8469c2b 100644 --- a/src/vfs.rs +++ b/src/vfs.rs @@ -53,16 +53,13 @@ impl VFS { pub fn real_to_virtual(&self, real_path: &Path) -> Result<PathBuf> { for (name, target) in &self.mount_points { - match real_path.strip_prefix(target) { - Ok(p) => { - let mount_path = Path::new(&name); - return if p.components().count() == 0 { - Ok(mount_path.to_path_buf()) - } else { - Ok(mount_path.join(p)) - }; - } - Err(_) => (), + if let Ok(p) = real_path.strip_prefix(target) { + let mount_path = Path::new(&name); + return if p.components().count() == 0 { + Ok(mount_path.to_path_buf()) + } else { + Ok(mount_path.join(p)) + }; } } bail!("Real path has no match in VFS") @@ -71,22 +68,19 @@ impl VFS { pub fn virtual_to_real(&self, virtual_path: &Path) -> Result<PathBuf> { for (name, target) in &self.mount_points { let mount_path = Path::new(&name); - match virtual_path.strip_prefix(mount_path) { - Ok(p) => { - return if p.components().count() == 0 { - Ok(target.clone()) - } else { - Ok(target.join(p)) - }; - } - Err(_) => (), + if let Ok(p) = virtual_path.strip_prefix(mount_path) { + return if p.components().count() == 0 { + Ok(target.clone()) + } else { + Ok(target.join(p)) + }; } } bail!("Virtual path has no match in VFS") } pub fn get_mount_points(&self) -> &HashMap<String, PathBuf> { - return &self.mount_points; + &self.mount_points } }