]> git.r.bdr.sh - rbdr/lyricli/commitdiff
Run lint / format
authorRuben Beltran del Rio <redacted>
Sun, 26 Jan 2025 16:04:00 +0000 (17:04 +0100)
committerRuben Beltran del Rio <redacted>
Sun, 26 Jan 2025 16:04:00 +0000 (17:04 +0100)
src/configuration.rs
src/lyrics_engine/genius.rs
src/lyrics_engine/mod.rs
src/main.rs
src/sources/apple_music.rs
src/sources/dbus.rs
src/sources/mod.rs
src/sources/spotify.rs

index 55443eb3b7822c47c325842f40e0f16e2dfdd0c3..56d60d93c41280e5a992e8798fba7cae122f7049 100644 (file)
@@ -1,9 +1,9 @@
+use serde::{Deserialize, Serialize};
+use serde_json;
 use std::env;
 use std::fs::{create_dir_all, write, File};
 use std::io::{Read, Result};
 use std::path::PathBuf;
-use serde::{Deserialize, Serialize};
-use serde_json;
 
 const CONFIG_ENV_VARIABLE: &str = "LYRICLI_CONFIG_DIRECTORY";
 const CONFIG_DEFAULT_LOCATION: &str = "XDG_CONFIG_HOME";
@@ -13,13 +13,11 @@ const CONFIG_FILENAME: &str = "lyricli.conf";
 
 #[derive(Serialize, Deserialize, Debug)]
 pub struct Configuration {
-    enabled_sources: Vec<String>
+    enabled_sources: Vec<String>,
 }
 
 impl Configuration {
-
-    pub fn new() -> Self  {
-
+    pub fn new() -> Self {
         if let Some(configuration) = Configuration::read() {
             return configuration;
         }
@@ -56,8 +54,8 @@ impl Configuration {
             enabled_sources: vec![
                 "apple_music".to_string(),
                 "spotify".to_string(),
-                "strawberry".to_string()
-            ]
+                "strawberry".to_string(),
+            ],
         }
     }
 
@@ -91,9 +89,13 @@ impl Configuration {
                 Ok(directory) => PathBuf::from(directory),
                 Err(_) => match env::var("HOME") {
                     Ok(directory) => PathBuf::from(directory).join(CONFIG_FALLBACK_LOCATION),
-                    Err(_) => panic!("Could not find required directory, {} or {} should be set and readable.", CONFIG_ENV_VARIABLE, CONFIG_DEFAULT_LOCATION),
+                    Err(_) => panic!(
+                        "Could not find required directory, {} or {} should be set and readable.",
+                        CONFIG_ENV_VARIABLE, CONFIG_DEFAULT_LOCATION
+                    ),
                 },
             },
-        }.join(CONFIG_SUBDIRECTORY)
+        }
+        .join(CONFIG_SUBDIRECTORY)
     }
 }
index e14589d88ff3c9d972867e8c5926eb8cbe809d01..a8b0468dac1558410b99a9fa09b383769b1159fa 100644 (file)
@@ -1,7 +1,10 @@
-use std::io::{Result, Error, ErrorKind::Other};
-use serde::Deserialize;
 use reqwest::get;
-use scraper::{ElementRef, Html, Selector, node::Node::{Text, Element}};
+use scraper::{
+    node::Node::{Element, Text},
+    ElementRef, Html, Selector,
+};
+use serde::Deserialize;
+use std::io::{Error, ErrorKind::Other, Result};
 
 #[derive(Deserialize, Debug)]
 struct GeniusApiResponse {
@@ -26,11 +29,21 @@ struct GeniusResult {
 }
 
 pub async fn search(url: &str) -> Result<String> {
-    let response = get(url).await
+    let response = get(url)
+        .await
         .map_err(|_| Error::new(Other, "Could not perform lyrics search in engine."))?
-        .json::<GeniusApiResponse>().await
-        .map_err(|_| Error::new(Other, "Lyrics engine returned invalid response from search."))?;
-    let url = response.response.hits.into_iter()
+        .json::<GeniusApiResponse>()
+        .await
+        .map_err(|_| {
+            Error::new(
+                Other,
+                "Lyrics engine returned invalid response from search.",
+            )
+        })?;
+    let url = response
+        .response
+        .hits
+        .into_iter()
         .find(|hit| hit.hit_type == "song")
         .map(|hit| hit.result.url)
         .ok_or_else(|| Error::new(Other, "Could not find a matching track in lyrics engine."))?;
@@ -39,14 +52,18 @@ pub async fn search(url: &str) -> Result<String> {
 }
 
 pub async fn get_lyrics(url: &str) -> Result<String> {
-    let song_html = get(url).await
+    let song_html = get(url)
+        .await
         .map_err(|_| Error::new(Other, "Could not fetch lyrics from engine."))?
-        .text().await
+        .text()
+        .await
         .map_err(|_| Error::new(Other, "Lyrics engine returned invalid response."))?;
 
     let document = Html::parse_document(&song_html);
     let selector = Selector::parse(r#"div[data-lyrics-container="true"]"#).unwrap();
-    let lyrics_div = document.select(&selector).next()
+    let lyrics_div = document
+        .select(&selector)
+        .next()
         .ok_or_else(|| Error::new(Other, "Could not find lyrics in response."))?;
 
     let mut lyrics = String::new();
@@ -61,10 +78,10 @@ pub async fn get_lyrics(url: &str) -> Result<String> {
                         lyrics.push_str(&text);
                     }
                 }
-            },
+            }
             Text(text) => {
                 lyrics.push_str(text);
-            },
+            }
             _ => {}
         }
     }
index f83d219c1153a95248d39555b68cdf5955defd14..325c5234b3a170c38a92ee9e07c0e2d83940381e 100644 (file)
@@ -1,5 +1,5 @@
-use std::io::Result;
 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
+use std::io::Result;
 
 mod genius;
 
@@ -16,7 +16,10 @@ pub async fn print_lyrics(track: Track, show_title: bool) -> Result<()> {
 
     let artist = utf8_percent_encode(&track.artist, NON_ALPHANUMERIC).to_string();
     let name = utf8_percent_encode(&track.name, NON_ALPHANUMERIC).to_string();
-    let url = format!("{}?access_token={}&q={}%20{}", GENIUS_API_URL, GENIUS_CLIENT_TOKEN, artist, name);
+    let url = format!(
+        "{}?access_token={}&q={}%20{}",
+        GENIUS_API_URL, GENIUS_CLIENT_TOKEN, artist, name
+    );
 
     let song_url = search(&url).await?;
     let lyrics = get_lyrics(&song_url).await?;
index d3b3334e44228b1999309a5b9ae9568b0059cf35..96569d98ff7b99a83f04503fc4a96e8d79be8593 100644 (file)
@@ -2,17 +2,16 @@ mod configuration;
 mod lyrics_engine;
 mod sources;
 
-use std::io::{Result, Error, ErrorKind::Other};
 use clap::Parser;
+use std::io::{Error, ErrorKind::Other, Result};
 
 use configuration::Configuration;
-use sources::{enable, disable, get_track, reset, list};
 use lyrics_engine::print_lyrics;
+use sources::{disable, enable, get_track, list, reset};
 
 #[derive(Parser, Debug)]
 #[command(version, about, long_about = None)]
 struct Arguments {
-
     // Positional Arguments
     /// Specify the artist.
     artist: Option<String>,
@@ -41,7 +40,7 @@ struct Arguments {
 
 pub struct Track {
     pub name: String,
-    pub artist: String
+    pub artist: String,
 }
 
 #[tokio::main]
@@ -99,11 +98,11 @@ async fn run() -> Result<()> {
     if let Some(artist) = arguments.artist {
         current_track = Track {
             name: arguments.track_name.unwrap_or("".to_string()),
-            artist: artist
+            artist: artist,
         };
     } else {
-        current_track = get_track()
-            .ok_or_else(|| Error::new(Other, "No Artist/Song could be found :("))?
+        current_track =
+            get_track().ok_or_else(|| Error::new(Other, "No Artist/Song could be found :("))?
     }
 
     print_lyrics(current_track, arguments.show_title).await
index 06412b88a02a7cbf114c9f746c17eb678b94cafb..6279a509db3be2fc33cf77dfcc433a83c6d74d46 100644 (file)
@@ -1,8 +1,15 @@
 use std::ffi::CStr;
 use std::io::Result;
 
-use cocoa::{base::{nil, id}, foundation::NSString};
-use objc::{class, msg_send, sel, sel_impl, runtime::{Class, Object}};
+use cocoa::{
+    base::{id, nil},
+    foundation::NSString,
+};
+use objc::{
+    class, msg_send,
+    runtime::{Class, Object},
+    sel, sel_impl,
+};
 use objc_id::Id;
 
 use crate::Track;
@@ -18,7 +25,6 @@ impl AppleMusic {
 }
 
 impl LyricsSource for AppleMusic {
-
     fn name(&self) -> String {
         "apple_music".to_string()
     }
@@ -27,17 +33,18 @@ impl LyricsSource for AppleMusic {
         unsafe {
             let app: Id<Object> = {
                 let cls = class!(SBApplication);
-                let bundle_identifier = NSString::alloc(nil).init_str("com.apple.Music"); 
+                let bundle_identifier = NSString::alloc(nil).init_str("com.apple.Music");
 
                 let workspace_class = Class::get("NSWorkspace").unwrap();
                 let shared_workspace: id = msg_send![workspace_class, sharedWorkspace];
                 let app_url: id = msg_send![shared_workspace, URLForApplicationWithBundleIdentifier:bundle_identifier];
 
                 if app_url != nil {
-                    let app: *mut Object = msg_send![cls, applicationWithBundleIdentifier:bundle_identifier];
+                    let app: *mut Object =
+                        msg_send![cls, applicationWithBundleIdentifier:bundle_identifier];
                     Id::from_ptr(app)
                 } else {
-                    return None
+                    return None;
                 }
             };
 
@@ -53,11 +60,7 @@ impl LyricsSource for AppleMusic {
                     let name = CStr::from_ptr(name_ptr).to_string_lossy().into_owned();
                     let artist = CStr::from_ptr(artist_ptr).to_string_lossy().into_owned();
 
-
-                    return Some(Track {
-                        name,
-                        artist
-                    })
+                    return Some(Track { name, artist });
                 }
             }
         }
@@ -76,5 +79,3 @@ impl LyricsSource for AppleMusic {
         Ok(())
     }
 }
-
-
index 57c585381b27c5adc4804d237263d3de1564ae6c..2f6bccd2d945d79ae5978df4a5569f3b0c0f7eef 100644 (file)
@@ -1,5 +1,5 @@
-use std::io::Result;
 use mpris::PlayerFinder;
+use std::io::Result;
 
 use crate::Track;
 
@@ -14,24 +14,19 @@ impl Dbus {
 }
 
 impl LyricsSource for Dbus {
-
     fn name(&self) -> String {
         "dbus".to_string()
     }
 
     fn current_track(&self) -> Option<Track> {
-        let player = PlayerFinder::new().ok()?
-            .find_active().ok()?;
+        let player = PlayerFinder::new().ok()?.find_active().ok()?;
 
         let metadata = player.get_metadata().ok()?;
         let name = metadata.title()?.to_string();
         let artists = metadata.artists()?;
         let artist = artists.get(0)?.to_string();
 
-        Some(Track {
-            name,
-            artist
-        })
+        Some(Track { name, artist })
     }
 
     fn disable(&self) -> Result<()> {
index 087a87f4a6cfb553888320ea1784746d17f590d8..47c25d00880e07df69b84184e289d6de3a014772 100644 (file)
@@ -1,4 +1,4 @@
-use std::io::{Result, Error, ErrorKind::Other};
+use std::io::{Error, ErrorKind::Other, Result};
 
 #[cfg(target_os = "macos")]
 mod apple_music;
@@ -29,14 +29,17 @@ pub trait LyricsSource {
 }
 
 pub fn list() -> Vec<String> {
-    available_sources().into_iter().map(|source| source.name()).collect()
+    available_sources()
+        .into_iter()
+        .map(|source| source.name())
+        .collect()
 }
 
 pub fn enable(source_name: &String) -> Result<()> {
     let sources = available_sources();
     for source in sources {
         if &source.name() == source_name {
-            return source.enable()
+            return source.enable();
         }
     }
     Err(Error::new(Other, "No such source was available."))
@@ -46,7 +49,7 @@ pub fn disable(source_name: &String) -> Result<()> {
     let sources = available_sources();
     for source in sources {
         if &source.name() == source_name {
-            return source.disable()
+            return source.disable();
         }
     }
     Err(Error::new(Other, "No such source was available."))
@@ -56,7 +59,7 @@ pub fn reset(source_name: &String) -> Result<()> {
     let sources = available_sources();
     for source in sources {
         if &source.name() == source_name {
-            return source.reset()
+            return source.reset();
         }
     }
     Err(Error::new(Other, "No such source was available."))
@@ -69,7 +72,7 @@ pub fn get_track() -> Option<Track> {
             return Some(track);
         }
     }
-    return None
+    return None;
 }
 
 pub fn available_sources() -> Vec<Box<dyn LyricsSource>> {
index e4bf19ce687ba42b2c6ffc99153b573a8933f773..bd627dba10e41d47909d3bed024a61627315b3dc 100644 (file)
@@ -1,8 +1,15 @@
 use std::ffi::CStr;
 use std::io::Result;
 
-use cocoa::{base::{nil, id}, foundation::NSString};
-use objc::{class, msg_send, sel, sel_impl, runtime::{Class, Object}};
+use cocoa::{
+    base::{id, nil},
+    foundation::NSString,
+};
+use objc::{
+    class, msg_send,
+    runtime::{Class, Object},
+    sel, sel_impl,
+};
 use objc_id::Id;
 
 use crate::Track;
@@ -18,7 +25,6 @@ impl Spotify {
 }
 
 impl LyricsSource for Spotify {
-
     fn name(&self) -> String {
         "spotify".to_string()
     }
@@ -27,17 +33,18 @@ impl LyricsSource for Spotify {
         unsafe {
             let app: Id<Object> = {
                 let cls = class!(SBApplication);
-                let bundle_identifier = NSString::alloc(nil).init_str("com.spotify.Client"); 
+                let bundle_identifier = NSString::alloc(nil).init_str("com.spotify.Client");
 
                 let workspace_class = Class::get("NSWorkspace").unwrap();
                 let shared_workspace: id = msg_send![workspace_class, sharedWorkspace];
                 let app_url: id = msg_send![shared_workspace, URLForApplicationWithBundleIdentifier:bundle_identifier];
 
                 if app_url != nil {
-                    let app: *mut Object = msg_send![cls, applicationWithBundleIdentifier:bundle_identifier];
+                    let app: *mut Object =
+                        msg_send![cls, applicationWithBundleIdentifier:bundle_identifier];
                     Id::from_ptr(app)
                 } else {
-                    return None
+                    return None;
                 }
             };
 
@@ -53,11 +60,7 @@ impl LyricsSource for Spotify {
                     let name = CStr::from_ptr(name_ptr).to_string_lossy().into_owned();
                     let artist = CStr::from_ptr(artist_ptr).to_string_lossy().into_owned();
 
-
-                    return Some(Track {
-                        name,
-                        artist
-                    })
+                    return Some(Track { name, artist });
                 }
             }
         }