Skip to content

Commit

Permalink
refactor: make clippy pedantic
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanccn committed Nov 12, 2023
1 parent 0dc6b51 commit 31d5336
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 33 deletions.
5 changes: 3 additions & 2 deletions src/cmd/discord/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ struct ActivityConnection {
is_idle: bool,
}

#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
async fn update_presence(
client: &mut DiscordIpcClient,
http_client: &reqwest::Client,
Expand Down Expand Up @@ -95,7 +96,7 @@ async fn update_presence(
&track.artist,
match &metadata {
Ok(metadata) => format!(" {}", metadata.id.dimmed()),
Err(_) => "".to_owned(),
Err(_) => String::new(),
}
);

Expand Down Expand Up @@ -144,7 +145,7 @@ async fn update_presence(
}

pub async fn discord() -> Result<()> {
let mut client = DiscordIpcClient::new("861702238472241162")?;
let mut client = DiscordIpcClient::new("861702238472241162");
client.connect().await?;

println!("{} to Discord", "Connected".green());
Expand Down
25 changes: 14 additions & 11 deletions src/cmd/now.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ async fn update_state(
tx.send(PlaybackStateDelta::Track(track)).await?;
}

if !playlist_name.is_empty() {
if playlist_name.is_empty() {
tx.send(PlaybackStateDelta::Playlist(None)).await?;
} else {
let playlist_duration = music::tell("get {duration} of current playlist")
.await?
.parse::<i32>()?;
Expand All @@ -105,8 +107,6 @@ async fn update_state(
duration: playlist_duration,
})))
.await?;
} else {
tx.send(PlaybackStateDelta::Playlist(None)).await?;
};
}

Expand All @@ -116,19 +116,21 @@ async fn update_state(
}

const BAR_CHAR: &str = "━";
#[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
fn make_bar(n: f64, width: Option<i32>) -> Result<String> {
let width = width.unwrap_or(20);

let part_one = (n * (width as f64)).floor() as i32;
let part_two = width - part_one;

let mut ret = "".to_owned();
let mut ret = String::new();
ret += &BAR_CHAR.repeat(part_one.try_into()?);
ret += &BAR_CHAR.dimmed().to_string().repeat(part_two.try_into()?);

Ok(ret)
}

#[allow(clippy::unused_async, clippy::cast_possible_truncation)]
async fn update_display(data: &PlaybackState, options: &NowOptions) -> Result<()> {
if options.watch {
execute!(
Expand All @@ -152,14 +154,14 @@ async fn update_display(data: &PlaybackState, options: &NowOptions) -> Result<()
println!("{}", track.name.bold());
println!(
"{} {} {} {}",
if !options.no_nerd_fonts {
data.state.to_icon()
} else {
if options.no_nerd_fonts {
data.state.to_string()
} else {
data.state.to_icon()
},
format::format_duration(&(position as i32), false),
format::format_duration(position as i32, false),
make_bar(position / track.duration, options.bar_width)?,
format::format_duration(&(track.duration as i32), true),
format::format_duration(track.duration as i32, true),
);
println!("{} · {}", track.artist.blue(), track.album.magenta());

Expand All @@ -169,7 +171,7 @@ async fn update_display(data: &PlaybackState, options: &NowOptions) -> Result<()
format!(
"Playlist: {} ({})",
playlist.name,
format::format_duration_plain(&playlist.duration)
format::format_duration_plain(playlist.duration)
)
.dimmed()
);
Expand Down Expand Up @@ -221,14 +223,15 @@ async fn receive_delta(

PlaybackStateDelta::Render => {
if let Err(err) = update_display(data, options).await {
eprintln!("{}", err);
eprintln!("{err}");
};
}
};

Ok(())
}

#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub async fn now(options: NowOptions) -> Result<()> {
let watch = options.watch;

Expand Down
12 changes: 6 additions & 6 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use owo_colors::OwoColorize;
const HOUR: i32 = 60 * 60;
const MINUTE: i32 = 60;

pub fn format_duration(duration_secs: &i32, yellow: bool) -> String {
let mut duration_secs = *duration_secs;
let mut str = "".to_owned();
pub fn format_duration(duration_secs: i32, yellow: bool) -> String {
let mut duration_secs = duration_secs;
let mut str = String::new();
let mut has_started = false;

if has_started || duration_secs >= HOUR {
Expand Down Expand Up @@ -48,9 +48,9 @@ pub fn format_duration(duration_secs: &i32, yellow: bool) -> String {
str
}

pub fn format_duration_plain(duration_secs: &i32) -> String {
let mut duration_secs = *duration_secs;
let mut str = "".to_owned();
pub fn format_duration_plain(duration_secs: i32) -> String {
let mut duration_secs = duration_secs;
let mut str = String::new();
let mut has_started = false;

if has_started || duration_secs > HOUR {
Expand Down
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
#![deny(unsafe_code)]

use std::io::stdout;

use anyhow::{anyhow, Result};
Expand Down Expand Up @@ -74,6 +78,7 @@ enum DiscordCommands {
#[cfg(not(target_os = "macos"))]
compile_error!("am doesn't work on non-macOS platforms!");

#[allow(clippy::cast_possible_truncation)]
async fn concise_now_playing() -> Result<()> {
let track_data = music::tell_raw(&[
"set output to \"\"",
Expand Down Expand Up @@ -111,7 +116,7 @@ async fn concise_now_playing() -> Result<()> {
println!(
"{} {}\n{} · {}",
name.bold(),
format::format_duration_plain(&(duration as i32)).dimmed(),
format::format_duration_plain(duration as i32).dimmed(),
artist.blue(),
album.magenta(),
);
Expand Down
10 changes: 4 additions & 6 deletions src/rich_presence/ipc_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ impl DiscordIpcClient {
/// ```
/// let ipc_client = DiscordIpcClient::new("<some client id>")?;
/// ```
pub fn new(client_id: &str) -> Result<Self> {
let client = Self {
pub fn new(client_id: &str) -> Self {
Self {
client_id: client_id.to_string(),
connected: false,
socket: None,
};

Ok(client)
}
}

fn get_pipe_pattern() -> PathBuf {
Expand All @@ -64,7 +62,7 @@ impl DiscordIpcClient {
impl DiscordIpc for DiscordIpcClient {
async fn connect_ipc(&mut self) -> Result<()> {
for i in 0..10 {
let path = DiscordIpcClient::get_pipe_pattern().join(format!("discord-ipc-{}", i));
let path = DiscordIpcClient::get_pipe_pattern().join(format!("discord-ipc-{i}"));

match UnixStream::connect(&path).await {
Ok(socket) => {
Expand Down
7 changes: 4 additions & 3 deletions src/rich_presence/ipc_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use uuid::Uuid;
/// A client that connects to and communicates with the Discord IPC.
///
/// Implemented via the [`DiscordIpcClient`](struct@crate::rich_presence::DiscordIpcClient) struct.
#[allow(clippy::cast_possible_truncation)]
#[async_trait]
pub trait DiscordIpc {
/// Connects the client to the Discord IPC.
Expand Down Expand Up @@ -112,7 +113,7 @@ pub trait DiscordIpc {
/// ```
async fn send(&mut self, data: Value, opcode: u8) -> Result<()> {
let data_string = data.to_string();
let header = pack(opcode.into(), data_string.len() as u32)?;
let header = pack(opcode.into(), data_string.len() as u32);

self.write(&header).await?;
self.write(data_string.as_bytes()).await?;
Expand Down Expand Up @@ -143,12 +144,12 @@ pub trait DiscordIpc {
let mut header = [0; 8];

self.read(&mut header).await?;
let (op, length) = unpack(header.to_vec())?;
let (op, length) = unpack(&header)?;

let mut data = vec![0u8; length as usize];
self.read(&mut data).await?;

let response = String::from_utf8(data.to_vec())?;
let response = String::from_utf8(data.clone())?;
let json_data = serde_json::from_str::<Value>(&response)?;

Ok((op, json_data))
Expand Down
7 changes: 3 additions & 4 deletions src/rich_presence/pack_unpack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ use anyhow::Result;
use std::convert::TryInto;

// Re-implement some packing methods in Rust
pub fn pack(opcode: u32, data_len: u32) -> Result<Vec<u8>> {
pub fn pack(opcode: u32, data_len: u32) -> Vec<u8> {
let mut bytes = Vec::new();

for byte_array in &[opcode.to_le_bytes(), data_len.to_le_bytes()] {
bytes.extend_from_slice(byte_array);
}

Ok(bytes)
bytes
}

pub fn unpack(data: Vec<u8>) -> Result<(u32, u32)> {
let data = data.as_slice();
pub fn unpack(data: &[u8]) -> Result<(u32, u32)> {
let (opcode, header) = data.split_at(std::mem::size_of::<u32>());

let opcode = u32::from_le_bytes(opcode.try_into()?);
Expand Down

0 comments on commit 31d5336

Please sign in to comment.