Debian Codegraph @

src/placeholder.rs

raw symbols SCIP
1 use crate::error::Error;
2 use crate::format_spec::FormatSpec;
3
4 /// Template placeholder specifications.
5 #[derive(Debug, Clone)]
6 pub struct Placeholder {
7 pub attributes: Option<String>,
8 pub format_spec: FormatSpec,
9 pub replacer: String,
10 }
11
12 impl Placeholder {
13 /// Parse template string and deserialize it to `Self`.
14 pub fn new(template: &str, placeholder: &str) -> Result<Option<Self>, Error> {
15 if let Some(start) = template.find(&format!("{{{}", placeholder)) {
16 let matched = &template[(start + 1)..(start + template[start..].find('}').unwrap())];
17
18 let attributes = if matched.rfind(':').is_some() {
19 let mut attributes = matched.split(':').collect::<Vec<&str>>();
20 let _ = attributes.pop();
21 attributes
22 .join(":")
23 .trim_start_matches(placeholder)
24 .trim()
25 .to_owned()
26 } else {
27 matched.trim_start_matches(placeholder).trim().to_owned()
28 };
29
30 let attributes = if attributes.is_empty() {
31 None
32 } else {
33 Some(attributes)
34 };
35
36 return Ok(Some(Self {
37 attributes,
38 format_spec: FormatSpec::new(matched)?,
39 replacer: format!("{{{}}}", matched),
40 }));
41 }
42
43 Ok(None)
44 }
45
46 /// Get attribute value if present else returns `None`.
47 ///
48 /// Attributes can be defined for as:
49 ///
50 /// ```text
51 /// 1. name=emily -> Some("emily")
52 /// 2. name="emily cooper" -> Some("emily cooper")
53 /// 3. name='emily clarke' -> Some("emily clarke")
54 /// ```
55 pub fn attr(&self, attribute: &str) -> Option<String> {
56 if let Some(attributes) = &self.attributes {
57 let attribute_identifier = format!("{}=", attribute);
58
59 if let Some(attribute_index) = attributes.find(&attribute_identifier) {
60 let value = attributes[attribute_index..].trim_start_matches(&attribute_identifier);
61
62 if let Some(stripped) = value.strip_prefix('\"') {
63 return Some(value[1..(stripped.find('\"')? + 1)].to_owned());
64 } else if let Some(stripped) = value.strip_prefix('\'') {
65 return Some(value[1..(stripped.find('\'')? + 1)].to_owned());
66 } else {
67 return value.split(' ').next().map(|x| x.to_owned());
68 }
69 }
70 }
71
72 None
73 }
74 }