about summary refs log tree commit diff stats
path: root/pkgs/by-name/mp/mpdpopm/src/messages.rs
diff options
context:
space:
mode:
authorBenedikt Peetz <benedikt.peetz@b-peetz.de>2026-01-25 20:44:40 +0100
committerBenedikt Peetz <benedikt.peetz@b-peetz.de>2026-01-25 20:44:40 +0100
commit42cb2a63a8143c3557b9304c3eed6973acbc7405 (patch)
treeaf43e088da415bc7768898dc57f7972389ec04cd /pkgs/by-name/mp/mpdpopm/src/messages.rs
parentmodules/river/keymap: Make media good/bad ratings once mappings (diff)
downloadnixos-config-42cb2a63a8143c3557b9304c3eed6973acbc7405.zip
pkgs/mpdpopm: Switch error handling from snafu to anyhow
This is not a library, as such we can just use anyhow and provide better
and more concise errors to the user.
Diffstat (limited to '')
-rw-r--r--pkgs/by-name/mp/mpdpopm/src/messages.rs165
1 files changed, 19 insertions, 146 deletions
diff --git a/pkgs/by-name/mp/mpdpopm/src/messages.rs b/pkgs/by-name/mp/mpdpopm/src/messages.rs
index c7c295c8..171a246a 100644
--- a/pkgs/by-name/mp/mpdpopm/src/messages.rs
+++ b/pkgs/by-name/mp/mpdpopm/src/messages.rs
@@ -54,110 +54,11 @@ use crate::{
     filters_ast::{FilterStickerNames, evaluate},
 };
 
-use backtrace::Backtrace;
+use anyhow::{Context, Error, Result, anyhow, bail};
 use boolinator::Boolinator;
 use tracing::debug;
 
 use std::collections::VecDeque;
-use std::path::PathBuf;
-
-#[derive(Debug)]
-pub enum Error {
-    BadPath {
-        pth: PathBuf,
-    },
-    FilterParseError {
-        msg: String,
-    },
-    InvalidChar {
-        c: u8,
-    },
-    NoClosingQuotes,
-    NoCommand,
-    NotImplemented {
-        feature: String,
-    },
-    PlayerStopped,
-    TrailingBackslash,
-    UnknownChannel {
-        chan: String,
-        back: Backtrace,
-    },
-    UnknownCommand {
-        name: String,
-        back: Backtrace,
-    },
-    Client {
-        source: crate::clients::Error,
-        back: Backtrace,
-    },
-    Ratings {
-        source: crate::storage::Error,
-        back: Backtrace,
-    },
-    Playcount {
-        source: crate::storage::Error,
-        back: Backtrace,
-    },
-    Filter {
-        source: crate::filters_ast::Error,
-        back: Backtrace,
-    },
-    Utf8 {
-        source: std::str::Utf8Error,
-        buf: Vec<u8>,
-        back: Backtrace,
-    },
-    ExpectedInt {
-        source: std::num::ParseIntError,
-        text: String,
-        back: Backtrace,
-    },
-}
-
-impl std::fmt::Display for Error {
-    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
-        match self {
-            Error::BadPath { pth } => write!(f, "Bad path: {:?}", pth),
-            Error::FilterParseError { msg } => write!(f, "Parse error: ``{}''", msg),
-            Error::InvalidChar { c } => write!(f, "Invalid unquoted character {}", c),
-            Error::NoClosingQuotes => write!(f, "Missing closing quotes"),
-            Error::NoCommand => write!(f, "No command specified"),
-            Error::NotImplemented { feature } => write!(f, "`{}' not implemented, yet", feature),
-            Error::PlayerStopped => write!(
-                f,
-                "Can't operate on the current track when the player is stopped"
-            ),
-            Error::TrailingBackslash => write!(f, "Trailing backslash"),
-            Error::UnknownChannel { chan, back: _ } => write!(
-                f,
-                "We received messages for an unknown channel `{}'; this is likely a bug; please consider filing a report to sp1ff@pobox.com",
-                chan
-            ),
-            Error::UnknownCommand { name, back: _ } => {
-                write!(f, "We received an unknown message ``{}''", name)
-            }
-            Error::Client { source, back: _ } => write!(f, "Client error: {}", source),
-            Error::Ratings { source, back: _ } => write!(f, "Ratings eror: {}", source),
-            Error::Playcount { source, back: _ } => write!(f, "Playcount error: {}", source),
-            Error::Filter { source, back: _ } => write!(f, "Filter error: {}", source),
-            Error::Utf8 {
-                source,
-                buf,
-                back: _,
-            } => write!(f, "UTF8 error {} ({:#?})", source, buf),
-            Error::ExpectedInt {
-                source,
-                text,
-                back: _,
-            } => write!(f, "``{}''L {}", source, text),
-        }
-    }
-}
-
-pub type Result<T> = std::result::Result<T, Error>;
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
 
 /// Break `buf` up into individual tokens while removing MPD-style quoting.
 ///
@@ -243,14 +144,14 @@ impl<'a> Iterator for TokenIterator<'a> {
                 if '\\' == self.slice[inp] as char {
                     inp += 1;
                     if inp == nslice {
-                        return Some(Err(Error::TrailingBackslash));
+                        return Some(Err(anyhow!("Trailing backslash")));
                     }
                 }
                 self.slice[out] = self.slice[inp];
                 out += 1;
                 inp += 1;
                 if inp == nslice {
-                    return Some(Err(Error::NoClosingQuotes));
+                    return Some(Err(anyhow!("No closing quote")));
                 }
             }
             // The next token is in self.slice[self.input..out] and self.slice[inp] is "
@@ -273,7 +174,7 @@ impl<'a> Iterator for TokenIterator<'a> {
                     break;
                 }
                 if self.slice[i] as char == '"' || self.slice[i] as char == '\'' {
-                    return Some(Err(Error::InvalidChar { c: self.slice[i] }));
+                    return Some(Err(anyhow!("Invalid char: `{}`", self.slice[i])));
                 }
                 i += 1;
             }
@@ -316,17 +217,11 @@ impl MessageProcessor {
         let m = idle_client
             .get_messages()
             .await
-            .map_err(|err| Error::Client {
-                source: err,
-                back: Backtrace::new(),
-            })?;
+            .context("Failed to `get_messages` from client")?;
 
         for (chan, msgs) in m {
             // Only supporting a single channel, ATM
-            (chan == command_chan).ok_or_else(|| Error::UnknownChannel {
-                chan,
-                back: Backtrace::new(),
-            })?;
+            (chan == command_chan).ok_or_else(|| anyhow!("Unknown chanell: `{}`", chan))?;
             for msg in msgs {
                 self.process(msg, client, &state, stickers).await?;
             }
@@ -365,11 +260,8 @@ impl MessageProcessor {
         let mut buf = msg.into_bytes();
         let args: VecDeque<&str> = tokenize(&mut buf)
             .map(|r| match r {
-                Ok(buf) => Ok(std::str::from_utf8(buf).map_err(|err| Error::Utf8 {
-                    source: err,
-                    buf: buf.to_vec(),
-                    back: Backtrace::new(),
-                })?),
+                Ok(buf) => Ok(std::str::from_utf8(buf)
+                    .context("Failed to interpete `findadd` string as utf8")?),
                 Err(err) => Err(err),
             })
             .collect::<Result<VecDeque<&str>>>()?;
@@ -385,9 +277,7 @@ impl MessageProcessor {
         let ast = match ExpressionParser::new().parse(args[0]) {
             Ok(ast) => ast,
             Err(err) => {
-                return Err(Error::FilterParseError {
-                    msg: format!("{}", err),
-                });
+                bail!("Failed to parse filter: `{}`", err)
             }
         };
 
@@ -396,22 +286,16 @@ impl MessageProcessor {
         let mut results = Vec::new();
         for song in evaluate(&ast, true, client, stickers)
             .await
-            .map_err(|err| Error::Filter {
-                source: err,
-                back: Backtrace::new(),
-            })?
+            .context("Failed to evaluate filter")?
         {
             results.push(client.add(&song).await);
         }
         match results
             .into_iter()
-            .collect::<std::result::Result<Vec<()>, crate::clients::Error>>()
+            .collect::<std::result::Result<Vec<()>, Error>>()
         {
             Ok(_) => Ok(()),
-            Err(err) => Err(Error::Client {
-                source: err,
-                back: Backtrace::new(),
-            }),
+            Err(err) => Err(err),
         }
     }
 
@@ -427,14 +311,11 @@ impl MessageProcessor {
         let mut buf = msg.into_bytes();
         let args: VecDeque<&str> = tokenize(&mut buf)
             .map(|r| match r {
-                Ok(buf) => Ok(std::str::from_utf8(buf).map_err(|err| Error::Utf8 {
-                    source: err,
-                    buf: buf.to_vec(),
-                    back: Backtrace::new(),
-                })?),
+                Ok(buf) => Ok(std::str::from_utf8(buf)
+                    .context("Failed to interpete `searchadd` string as utf8")?),
                 Err(err) => Err(err),
             })
-            .collect::<Result<VecDeque<&str>>>()?;
+            .collect::<Result<VecDeque<_>>>()?;
 
         debug!("searchadd arguments: {:#?}", args);
 
@@ -447,9 +328,7 @@ impl MessageProcessor {
         let ast = match ExpressionParser::new().parse(args[0]) {
             Ok(ast) => ast,
             Err(err) => {
-                return Err(Error::FilterParseError {
-                    msg: format!("{}", err),
-                });
+                bail!("Failed to parse filter: `{err}`")
             }
         };
 
@@ -458,22 +337,16 @@ impl MessageProcessor {
         let mut results = Vec::new();
         for song in evaluate(&ast, false, client, stickers)
             .await
-            .map_err(|err| Error::Filter {
-                source: err,
-                back: Backtrace::new(),
-            })?
+            .context("Failed to evaluate ast")?
         {
             results.push(client.add(&song).await);
         }
         match results
             .into_iter()
-            .collect::<std::result::Result<Vec<()>, crate::clients::Error>>()
+            .collect::<std::result::Result<Vec<()>, Error>>()
         {
             Ok(_) => Ok(()),
-            Err(err) => Err(Error::Client {
-                source: err,
-                back: Backtrace::new(),
-            }),
+            Err(err) => Err(err),
         }
     }
 }