mirror of
https://github.com/BurntSushi/ripgrep.git
synced 2025-03-17 20:28:03 +02:00
globset: permit deserializing Glob from String
Closes #2386, Closes #2388
This commit is contained in:
parent
ea05881319
commit
d51c6c005a
@ -1,5 +1,7 @@
|
||||
use serde::de::Error;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde::{
|
||||
de::{Error, Visitor},
|
||||
{Deserialize, Deserializer, Serialize, Serializer},
|
||||
};
|
||||
|
||||
use crate::Glob;
|
||||
|
||||
@ -12,19 +14,67 @@ impl Serialize for Glob {
|
||||
}
|
||||
}
|
||||
|
||||
struct GlobVisitor;
|
||||
|
||||
impl<'a> Visitor<'a> for GlobVisitor {
|
||||
type Value = Glob;
|
||||
|
||||
fn expecting(
|
||||
&self,
|
||||
formatter: &mut std::fmt::Formatter,
|
||||
) -> std::fmt::Result {
|
||||
formatter.write_str("a glob pattern")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
Glob::new(v).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Glob {
|
||||
fn deserialize<D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Self, D::Error> {
|
||||
let glob = <&str as Deserialize>::deserialize(deserializer)?;
|
||||
Glob::new(glob).map_err(D::Error::custom)
|
||||
deserializer.deserialize_str(GlobVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::Glob;
|
||||
|
||||
#[test]
|
||||
fn glob_deserialize_borrowed() {
|
||||
let string = r#"{"markdown": "*.md"}"#;
|
||||
|
||||
let map: HashMap<String, Glob> =
|
||||
serde_json::from_str(&string).unwrap();
|
||||
assert_eq!(map["markdown"], Glob::new("*.md").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_deserialize_owned() {
|
||||
let string = r#"{"markdown": "*.md"}"#;
|
||||
|
||||
let v: serde_json::Value = serde_json::from_str(&string).unwrap();
|
||||
let map: HashMap<String, Glob> = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(map["markdown"], Glob::new("*.md").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_deserialize_error() {
|
||||
let string = r#"{"error": "["}"#;
|
||||
|
||||
let map = serde_json::from_str::<HashMap<String, Glob>>(&string);
|
||||
|
||||
assert!(map.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_json_works() {
|
||||
let test_glob = Glob::new("src/**/*.rs").unwrap();
|
||||
|
Loading…
x
Reference in New Issue
Block a user