use peg::parser;
use serde::de::{Deserialize, Deserializer, Visitor};
use std::path::PathBuf;
use std::str;
#[derive(Debug, PartialEq)]
pub enum Action {
Delete,
Move { to: PathBuf },
}
parser! {
grammar actions() for str {
rule path() -> PathBuf
= x:$(['a'..='z'|'A'..='Z'|'_'|'-'|'/'|'\\'|' ']+) { PathBuf::from(x) }
rule delete() -> Action
= "delete" { Action::Delete }
rule move_to() -> Action
= "move" " " p:path() { Action::Move { to: p } }
pub rule action() -> Action
= move_to() / delete()
}
}
impl str::FromStr for Action {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(actions::action(s).unwrap())
}
}
struct ActionVisitor;
impl<'de> Visitor<'de> for ActionVisitor {
type Value = Action;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a string containing at least 10 bytes")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(s.parse().unwrap())
}
}
impl<'de> Deserialize<'de> for Action {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(ActionVisitor)
}
}
#[test]
fn can_parse_delete() {
assert_eq!("delete".parse::<Action>().unwrap(), Action::Delete,);
}
#[test]
fn can_parse_move_to() {
assert_eq!(
"move documents".parse::<Action>().unwrap(),
Action::Move {
to: PathBuf::from("documents")
},
);
}