use std::fmt;
use crate::types::name::PackName;
use crate::types::op::{ApiFunction, ItemId, OpError};
use crate::types::tree::TreePath;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkipReason(String);
impl SkipReason {
pub fn new(text: &str) -> Result<Self, OpError> {
if text.trim().is_empty() {
return Err(OpError::Empty {
function: ApiFunction::Skip,
field: "reason".to_owned(),
});
}
Ok(Self(text.to_owned()))
}
pub(in crate::types::op) const fn core(text: String) -> Self {
Self(text)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for SkipReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkipSubject {
Item(ItemId),
RootFile {
pack: PackName,
rel: TreePath,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoreSkip {
subject: SkipSubject,
reason: SkipReason,
}
impl CoreSkip {
#[must_use]
pub const fn new(subject: SkipSubject, reason: SkipReason) -> Self {
Self { subject, reason }
}
#[must_use]
pub const fn subject(&self) -> &SkipSubject {
&self.subject
}
#[must_use]
pub const fn reason(&self) -> &SkipReason {
&self.reason
}
}
#[cfg(test)]
mod tests {
use super::*;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[test]
fn skip_reason_refuses_empty_and_blank() -> TestResult {
for text in ["", " ", "\t\n"] {
let refused = SkipReason::new(text).err().ok_or("a blank reason")?;
assert_eq!(refused.to_string(), "skip: reason: empty", "{text:?}");
}
let kept = SkipReason::new("not for this tool")?;
assert_eq!(kept.as_str(), "not for this tool");
assert_eq!(kept.to_string(), "not for this tool");
Ok(())
}
#[test]
fn core_skip_holds_its_subject_and_reason() -> TestResult {
let subject = SkipSubject::RootFile {
pack: PackName::new("core")?,
rel: TreePath::from_parts(&["hooks", "x.lua"]),
};
let skip = CoreSkip::new(subject.clone(), SkipReason::new("why")?);
assert_eq!(skip.subject(), &subject);
assert_eq!(skip.reason().as_str(), "why");
Ok(())
}
}