use std::fmt;
use std::io;
use std::sync::Arc;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
AddActionsEntry,
AddActionGroup,
InsertActionsEntry,
EntryGroupExists,
EntryGroupNotFound,
RemoveEntry,
RemoveRequiredEntry,
SwapEntry,
Entry(EntryError),
Group(GroupError),
ParseFileDesktop(ParseFileDesktopError),
OpenFile(Arc<io::Error>),
}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::AddActionsEntry, Self::AddActionsEntry)
| (Self::AddActionGroup, Self::AddActionGroup)
| (Self::InsertActionsEntry, Self::InsertActionsEntry)
| (Self::EntryGroupExists, Self::EntryGroupExists)
| (Self::EntryGroupNotFound, Self::EntryGroupNotFound)
| (Self::RemoveEntry, Self::RemoveEntry)
| (Self::RemoveRequiredEntry, Self::RemoveRequiredEntry)
| (Self::SwapEntry, Self::SwapEntry) => true,
(Self::Entry(left), Self::Entry(right)) => left == right,
(Self::Group(left), Self::Group(right)) => left == right,
(Self::ParseFileDesktop(left), Self::ParseFileDesktop(right)) => left == right,
(Self::OpenFile(left), Self::OpenFile(right)) => left.kind() == right.kind(),
_ => false,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AddActionsEntry => f.write_str("entry cannot be added to any group"),
Self::InsertActionsEntry => f.write_str("entry cannot be inserted to any group"),
Self::EntryGroupExists => f.write_str("entry group already exists"),
Self::EntryGroupNotFound => f.write_str("entry group not found"),
Self::AddActionGroup => f.write_str("failed to add an action group"),
Self::RemoveEntry => f.write_str("failed to remove an entry"),
Self::SwapEntry => f.write_str("failed to swap an entry"),
Self::RemoveRequiredEntry => f.write_str("failed to remove required entry"),
Self::Entry(kind) => write!(f, "{kind}"),
Self::Group(kind) => write!(f, "{kind}"),
Self::ParseFileDesktop(kind) => write!(f, "{kind}"),
Self::OpenFile(source) => write!(f, "{source}"),
}
}
}
impl From<AppendKeyValueError> for Error {
fn from(error: AppendKeyValueError) -> Self {
Self::Entry(EntryError::AppendKeyValue(error))
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::OpenFile(Arc::new(error))
}
}
impl From<ParseEntryValueError> for Error {
fn from(error: ParseEntryValueError) -> Self {
Self::Entry(EntryError::Parse(ParseEntryError::ParseValue(error)))
}
}
impl From<ParseKeyError> for Error {
fn from(error: ParseKeyError) -> Self {
Self::Entry(EntryError::Parse(ParseEntryError::ParseKey(error)))
}
}
impl From<ParseEntryError> for Error {
fn from(error: ParseEntryError) -> Self {
Self::Entry(EntryError::Parse(error))
}
}
impl From<ParseFileDesktopError> for Error {
fn from(error: ParseFileDesktopError) -> Self {
Self::ParseFileDesktop(error)
}
}
impl From<GroupError> for Error {
fn from(error: GroupError) -> Self {
Self::Group(error)
}
}
impl From<EntryError> for Error {
fn from(error: EntryError) -> Self {
Self::Entry(error)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Entry(error) => Some(error),
Self::Group(error) => Some(error),
Self::ParseFileDesktop(error) => Some(error),
Self::AddActionsEntry
| Self::AddActionGroup
| Self::InsertActionsEntry
| Self::EntryGroupExists
| Self::EntryGroupNotFound
| Self::RemoveEntry
| Self::RemoveRequiredEntry
| Self::SwapEntry => None,
Self::OpenFile(source) => Some(source),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppendKeyValueError {
NotEscapedStringList,
NotLocaleStringList,
}
impl AppendKeyValueError {
pub(crate) fn as_str(&self) -> &str {
match self {
Self::NotEscapedStringList => "entry does not contain an EscapedStrings value",
Self::NotLocaleStringList => "entry does not contain a LocaleStrings value",
}
}
}
impl fmt::Display for AppendKeyValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::error::Error for AppendKeyValueError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntryError {
AppendKeyValue(AppendKeyValueError),
Value(ValueError),
MutationValue(MutationValueError),
Parse(ParseEntryError),
}
impl fmt::Display for EntryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AppendKeyValue(kind) => write!(f, "{kind}"),
Self::Parse(kind) => write!(f, "{kind}"),
Self::Value(kind) => write!(f, "{kind}"),
Self::MutationValue(kind) => write!(f, "{kind}"),
}
}
}
impl std::error::Error for EntryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::AppendKeyValue(error) => Some(error),
Self::Parse(error) => Some(error),
Self::Value(_) | Self::MutationValue(_) => None,
}
}
}
impl From<AppendKeyValueError> for EntryError {
fn from(err: AppendKeyValueError) -> Self {
Self::AppendKeyValue(err)
}
}
impl From<ValueError> for EntryError {
fn from(err: ValueError) -> Self {
Self::Value(err)
}
}
impl From<MutationValueError> for EntryError {
fn from(err: MutationValueError) -> Self {
Self::MutationValue(err)
}
}
impl From<ParseEntryError> for EntryError {
fn from(err: ParseEntryError) -> Self {
Self::Parse(err)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupError {
Entry(EntryError),
AddActionsEntry,
DuplicatePosition,
EntryExists,
EntryNotFound,
EmptyGroupName,
InvalidGroupName,
InvalidGroupHeader,
PositionNotFound,
}
impl fmt::Display for GroupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Entry(kind) => write!(f, "{kind}"),
Self::AddActionsEntry => f.write_str(""),
Self::DuplicatePosition => {
f.write_str("position key appears more than once in the group")
}
Self::EmptyGroupName => f.write_str("group name is empty"),
Self::EntryExists => f.write_str("entry already exists"),
Self::EntryNotFound => f.write_str("failed to get an entry"),
Self::InvalidGroupName => {
f.write_str("invalid group name (must not contain '[', ']', or control characters)")
}
Self::InvalidGroupHeader => f.write_str("invalid group header"),
Self::PositionNotFound => f.write_str("position key was not found in the group"),
}
}
}
impl std::error::Error for GroupError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Entry(error) => Some(error),
Self::AddActionsEntry
| Self::DuplicatePosition
| Self::EntryExists
| Self::EntryNotFound
| Self::EmptyGroupName
| Self::InvalidGroupName
| Self::InvalidGroupHeader
| Self::PositionNotFound => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError(pub(crate) String);
impl fmt::Display for ValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid value: {}", self.0)
}
}
impl ValueError {
#[inline]
#[must_use]
pub fn value(&self) -> &str {
&self.0
}
}
impl std::error::Error for ValueError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationValueError(pub(crate) String);
impl fmt::Display for MutationValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid value: {}", self.0)
}
}
impl std::error::Error for MutationValueError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseFileDesktopError {
InvalidGroupHeader {
line: usize,
source: GroupError,
},
ParseEntry {
line: usize,
source: ParseEntryError,
},
DuplicateGroup {
line: usize,
},
DuplicateEntry {
line: usize,
},
EntryOutsideGroup {
line: usize,
},
EmptyFile,
EmptyGroupName {
line: usize,
},
InvalidComment {
line: usize,
},
MissingRequiredGroup,
MissingRequiredKeys,
InconsistentActions,
}
impl ParseFileDesktopError {
pub(crate) fn message(&self) -> String {
match self {
Self::InvalidGroupHeader { line, source } => {
format!("failed to parse group header at line {line}: {source}")
}
Self::ParseEntry { line, source } => {
format!("failed to parse entry at line {line}: {source}")
}
Self::DuplicateGroup { line } => {
format!("duplicate group encountered at line {line}")
}
Self::DuplicateEntry { line } => {
format!("duplicate entry encountered at line {line}")
}
Self::InconsistentActions => {
"actions entry does not match desktop action groups".to_string()
}
Self::MissingRequiredGroup => "missing required Desktop Entry group".to_string(),
Self::MissingRequiredKeys => "missing one or more required keys".to_string(),
Self::EntryOutsideGroup { line } => {
format!("desktop entry encountered before any group header at line {line}")
}
Self::EmptyFile => "desktop entry file is empty".to_string(),
Self::EmptyGroupName { line } => format!("desktop group name is empty at line {line}"),
Self::InvalidComment { line } => {
format!("invalid comment syntax at line {line}")
}
}
}
}
impl fmt::Display for ParseFileDesktopError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.message())
}
}
impl std::error::Error for ParseFileDesktopError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidGroupHeader { source, .. } => Some(source),
Self::ParseEntry { source, .. } => Some(source),
Self::DuplicateGroup { .. }
| Self::DuplicateEntry { .. }
| Self::EntryOutsideGroup { .. }
| Self::EmptyFile
| Self::EmptyGroupName { .. }
| Self::InvalidComment { .. }
| Self::InconsistentActions
| Self::MissingRequiredGroup
| Self::MissingRequiredKeys => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseEntryError {
ParseKey(ParseKeyError),
ParseValue(ParseEntryValueError),
MissingSeparator(String),
}
impl fmt::Display for ParseEntryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ParseKey(error) => write!(f, "{error}"),
Self::ParseValue(error) => write!(f, "{error}"),
Self::MissingSeparator(line) => {
write!(f, "entry is missing the '=' separator: '{line}'")
}
}
}
}
impl From<ParseKeyError> for ParseEntryError {
fn from(error: ParseKeyError) -> Self {
Self::ParseKey(error)
}
}
impl From<ParseEntryValueError> for ParseEntryError {
fn from(error: ParseEntryValueError) -> Self {
Self::ParseValue(error)
}
}
impl std::error::Error for ParseEntryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::ParseKey(error) => Some(error),
Self::ParseValue(error) => Some(error),
Self::MissingSeparator(_) => None,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseEntryValueError {
ParseDesktopType,
ParseBool,
ParseVersion,
ParseNumeric,
ParseEscapedString,
ParseLocaleString,
ParseIconString,
ParseEscapedStrings,
ParseLocaleStrings,
ParseExtensionString,
}
impl ParseEntryValueError {
pub(crate) fn as_str(&self) -> &str {
match self {
Self::ParseExtensionString => {
"invalid 'ExtensionString' value: expected UTF-8 characters excluding control characters"
}
Self::ParseDesktopType => {
"invalid value for key 'Type': expected exactly 'Application', 'Link', or 'Directory'"
}
Self::ParseBool => "invalid 'Bool' value: expected exactly 'true' or 'false'",
Self::ParseVersion => {
"invalid 'Version' value: expected '1.0', '1.1', '1.2', '1.3', '1.4', or '1.5'"
}
Self::ParseNumeric => "invalid 'Numeric' value: expected a valid floating-point number",
Self::ParseEscapedString => {
"invalid 'EscapedString' value: expected ASCII characters excluding control characters and unsupported escape sequences"
}
Self::ParseLocaleString => {
"invalid 'LocaleString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
}
Self::ParseIconString => {
"invalid 'IconString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
}
Self::ParseEscapedStrings => {
"invalid 'EscapedStrings' value: expected a semicolon-delimited list of valid 'EscapedString' values"
}
Self::ParseLocaleStrings => {
"invalid 'LocaleStrings' value: expected a semicolon-delimited list of valid 'LocaleString' values"
}
}
}
}
impl fmt::Display for ParseEntryValueError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::error::Error for ParseEntryValueError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseKeyError {
InvalidFormat,
InvalidExtensionKey,
InvalidLocale,
NotLocalizable,
NonStandardKey,
UnknownKey(String),
}
impl fmt::Display for ParseKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFormat => f.write_str("invalid key format"),
Self::InvalidLocale => f.write_str("invalid locale format"),
Self::InvalidExtensionKey => f.write_str("invalid extension key"),
Self::NonStandardKey => f.write_str("key is not a standard desktop entry key"),
Self::NotLocalizable => f.write_str("not localizable key"),
Self::UnknownKey(key) => {
write!(f, "unknown desktop entry key '{key}'")
}
}
}
}
impl std::error::Error for ParseKeyError {}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as StdError;
use std::io::ErrorKind;
#[test]
fn test_parse_file_desktop_error_kind_display_messages() {
assert_eq!(
ParseFileDesktopError::DuplicateGroup { line: 3 }.to_string(),
"duplicate group encountered at line 3"
);
assert_eq!(
ParseFileDesktopError::MissingRequiredGroup.to_string(),
"missing required Desktop Entry group"
);
assert_eq!(
ParseFileDesktopError::MissingRequiredKeys.to_string(),
"missing one or more required keys"
);
assert_eq!(
ParseFileDesktopError::EntryOutsideGroup { line: 2 }.to_string(),
"desktop entry encountered before any group header at line 2"
);
assert_eq!(
ParseFileDesktopError::DuplicateEntry { line: 6 }.to_string(),
"duplicate entry encountered at line 6"
);
assert_eq!(
ParseFileDesktopError::EmptyFile.to_string(),
"desktop entry file is empty"
);
assert_eq!(
ParseFileDesktopError::EmptyGroupName { line: 7 }.to_string(),
"desktop group name is empty at line 7"
);
assert_eq!(
ParseFileDesktopError::InvalidComment { line: 10 }.to_string(),
"invalid comment syntax at line 10"
);
}
#[test]
fn test_parse_entry_value_error_display_messages() {
assert_eq!(
ParseEntryValueError::ParseEscapedString.to_string(),
"invalid 'EscapedString' value: expected ASCII characters excluding control characters and unsupported escape sequences"
);
assert_eq!(
ParseEntryValueError::ParseLocaleString.to_string(),
"invalid 'LocaleString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
);
}
#[test]
fn test_error_display_messages() {
assert_eq!(
Error::from(io::Error::from(ErrorKind::NotFound)).to_string(),
"entity not found"
);
}
#[test]
fn test_from_io_error_for_error_keeps_error_kind() {
let io_error = io::Error::new(ErrorKind::PermissionDenied, "no permission");
let error = Error::from(io_error);
assert!(matches!(
error,
Error::OpenFile(source) if source.kind() == ErrorKind::PermissionDenied
));
}
#[test]
fn io_errors_remain_error_sources() {
let error = Error::from(io::Error::new(ErrorKind::PermissionDenied, "no permission"));
assert_eq!(
StdError::source(&error).unwrap().to_string(),
"no permission"
);
}
#[test]
fn test_from_parse_entry_value_error_for_error() {
let error = Error::from(ParseEntryValueError::ParseBool);
assert_eq!(
error,
Error::Entry(EntryError::Parse(ParseEntryError::ParseValue(
ParseEntryValueError::ParseBool
)))
);
}
#[test]
fn nested_errors_expose_their_sources() {
let error = Error::ParseFileDesktop(ParseFileDesktopError::ParseEntry {
line: 4,
source: ParseEntryError::ParseValue(ParseEntryValueError::ParseBool),
});
let file_error = StdError::source(&error).unwrap();
assert_eq!(
file_error.to_string(),
"failed to parse entry at line 4: invalid 'Bool' value: expected exactly 'true' or 'false'"
);
let entry_error = file_error.source().unwrap();
assert_eq!(
entry_error.to_string(),
"invalid 'Bool' value: expected exactly 'true' or 'false'"
);
let value_error = entry_error.source().unwrap();
assert_eq!(
value_error.to_string(),
"invalid 'Bool' value: expected exactly 'true' or 'false'"
);
assert!(value_error.source().is_none());
let group_error = GroupError::Entry(EntryError::MutationValue(MutationValueError(
"Bool".to_owned(),
)));
assert_eq!(
StdError::source(&group_error).unwrap().to_string(),
"invalid value: Bool"
);
}
}