tramlines_md/markdown/
dialect.rs1use std::collections::BTreeMap;
5
6use crate::grammar::{Condition, Only};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Dialect {
14 pub namespace: &'static str,
16 pub region: Option<&'static str>,
19 pub trailer: Option<&'static str>,
22 pub scheme: Option<&'static str>,
25}
26impl Default for Dialect {
30 fn default() -> Self {
32 Dialect {
33 namespace: "tramlines",
34 region: None,
35 trailer: None,
36 scheme: None,
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Marker {
44 Open(String),
46 Close,
48 Trailer,
50}
51
52pub(super) fn comment(line: &str) -> Option<&str> {
54 line.trim()
55 .strip_prefix("<!--")
56 .and_then(|s| s.strip_suffix("-->"))
57 .map(str::trim)
58}
59
60fn names(text: &str, ns: &str, name: &str) -> bool {
62 text.strip_prefix(ns)
63 .and_then(|t| t.strip_prefix(':'))
64 .is_some_and(|t| t.starts_with(name))
65}
66
67impl Dialect {
68 pub fn spell(&self, name: &str) -> String {
70 format!("{}:{name}", self.namespace)
71 }
72
73 pub fn marker(&self, line: &str) -> Option<Marker> {
76 let inner = comment(line)?;
77 if let Some(region) = self.region {
78 if inner == format!("/{}", self.spell(region)) {
79 return Some(Marker::Close);
80 }
81 if let Some(target) = inner.strip_prefix(&self.spell(region)) {
82 let target = target.trim();
83 if target.is_empty() || target.contains(char::is_whitespace) {
84 return None;
85 }
86 return Some(Marker::Open(target.to_string()));
87 }
88 }
89 if self.trailer.is_some_and(|t| inner == self.spell(t)) {
90 return Some(Marker::Trailer);
91 }
92 None
93 }
94
95 pub fn is_only_marker(&self, line: &str) -> bool {
98 let only = format!("{} ", self.spell("only"));
99 if let Some(inner) = comment(line) {
100 return inner.starts_with(&only);
101 }
102 let t = line.trim();
103 match t.rfind('#') {
104 Some(i) => t[i + 1..].trim().starts_with(&only),
105 None => false,
106 }
107 }
108
109 pub fn is_guidance_marker(&self, line: &str) -> bool {
115 if let Some(inner) = comment(line) {
116 return names(inner, self.namespace, "guidance");
117 }
118 line.trim()
119 .strip_prefix('#')
120 .is_some_and(|rest| names(rest.trim_start(), self.namespace, "guidance"))
121 }
122
123 pub fn is_optional_marker(&self, line: &str) -> bool {
129 comment(line) == Some(self.spell("optional").as_str())
130 }
131
132 pub fn is_optional_close(&self, line: &str) -> bool {
134 comment(line).and_then(|c| c.strip_prefix('/')) == Some(self.spell("optional").as_str())
135 }
136
137 pub fn is_optional_mark(&self, line: &str) -> bool {
139 self.is_optional_marker(line) || self.is_optional_close(line)
140 }
141
142 pub fn only_marker(&self, line: &str) -> Option<Condition> {
147 if !self.is_only_marker(line) {
148 return None;
149 }
150 let only = format!("{} ", self.spell("only"));
151 let i = line.find(&only)?;
152 let rest = line[i + only.len()..].trim_end_matches("-->").trim();
153 if rest.is_empty() {
154 return Some(Condition::default());
155 }
156 let words: Vec<&str> = rest.split_whitespace().collect();
159 let mut maps = Vec::new();
160 for part in words.split(|w| *w == "|") {
161 let mut map = BTreeMap::new();
162 for pair in part {
163 let (k, v) = pair.split_once('=')?;
164 if k.is_empty() || v.is_empty() || k.contains('|') {
167 return None;
168 }
169 map.insert(k.to_string(), v.split(',').map(str::to_string).collect());
170 }
171 if map.is_empty() {
172 return None;
173 }
174 maps.push(Only(map));
175 }
176 Some(Condition::new(maps))
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 const HOST: Dialect = Dialect {
185 namespace: "host",
186 region: Some("include"),
187 trailer: Some("links"),
188 scheme: Some("host"),
189 };
190
191 #[test]
193 fn markers() {
194 let m = |l: &str| HOST.marker(l);
195 assert_eq!(m("<!-- host:include x -->"), Some(Marker::Open("x".into())));
196 assert_eq!(
197 m(" <!--host:include /a/b.rs#r-->"),
198 Some(Marker::Open("/a/b.rs#r".into()))
199 );
200 assert_eq!(m("<!-- /host:include -->"), Some(Marker::Close));
201 assert_eq!(m("<!-- host:links -->"), Some(Marker::Trailer));
202 assert_eq!(m("<!-- host:include -->"), None);
203 assert_eq!(m("<!-- host:include a b -->"), None);
204 assert_eq!(m("<!-- host:includes x -->"), None);
205 assert_eq!(m("text <!-- host:links -->"), None);
206 let plain = Dialect::default();
207 assert_eq!(plain.marker("<!-- host:include x -->"), None);
208 assert_eq!(plain.marker("<!-- tramlines:links -->"), None);
209 }
210
211 fn map(pairs: &[(&str, &[&str])]) -> Only {
213 Only(
214 pairs
215 .iter()
216 .map(|(k, v)| (k.to_string(), v.iter().map(ToString::to_string).collect()))
217 .collect(),
218 )
219 }
220
221 #[test]
222 fn only_markers() {
223 assert!(HOST.is_only_marker("<!-- host:only state=closed -->"));
224 assert!(HOST.is_only_marker("resolution: none # host:only state=closed"));
225 assert!(!HOST.is_only_marker("<!-- host:links -->"));
226 assert!(!HOST.is_only_marker("plain # comment"));
227 assert!(!HOST.is_only_marker("plain"));
228 assert!(HOST.is_optional_marker("<!-- host:optional -->"));
229 assert!(HOST.is_optional_close("<!-- /host:optional -->"));
230 assert!(HOST.is_optional_mark("<!-- /host:optional -->"));
231 assert!(!HOST.is_optional_marker("<!-- /host:optional -->"));
232 assert!(!HOST.is_optional_close("<!-- host:optional -->"));
233 assert!(!HOST.is_optional_marker("<!-- host:only state=closed -->"));
234 assert!(!HOST.is_optional_marker("<!-- host:optionally -->"));
235 assert!(!HOST.is_only_marker("<!-- host:optional -->"));
236 assert!(!Dialect::default().is_only_marker("<!-- host:only state=closed -->"));
237 assert!(Dialect::default().is_only_marker("<!-- tramlines:only state=closed -->"));
238 assert_eq!(
239 HOST.only_marker("<!-- host:only state=open,done kind=bug -->"),
240 Some(Condition(vec![map(&[
241 ("kind", &["bug"]),
242 ("state", &["open", "done"])
243 ])]))
244 );
245 }
246
247 #[test]
252 fn an_only_marker_joins_the_maps_of_a_condition() {
253 let two = HOST.only_marker("<!-- host:only plan=planned | state=closed kind=bug -->");
254 assert_eq!(
255 two,
256 Some(Condition(vec![
257 map(&[("kind", &["bug"]), ("state", &["closed"])]),
258 map(&[("plan", &["planned"])]),
259 ]))
260 );
261 assert_eq!(
264 two.unwrap().render(),
265 "kind=bug state=closed | plan=planned"
266 );
267 assert_eq!(HOST.only_marker("<!-- host:only a=x | -->"), None);
268 assert_eq!(HOST.only_marker("<!-- host:only | a=x -->"), None);
269 assert_eq!(HOST.only_marker("<!-- host:only a=x || b=y -->"), None);
270 assert_eq!(HOST.only_marker("<!-- host:only a=x |b=y -->"), None);
271 assert_eq!(
272 HOST.only_marker("<!-- host:only state=a|b -->"),
273 Some(Condition(vec![map(&[("state", &["a|b"])])]))
274 );
275 }
276
277 #[test]
278 fn guidance_markers() {
279 assert!(HOST.is_guidance_marker("<!-- host:guidance Say what the part is for. -->"));
280 assert!(HOST.is_guidance_marker(" # host:guidance The states, in order."));
281 assert!(!HOST.is_guidance_marker("<!-- host:guidance spans"));
282 assert!(!HOST.is_guidance_marker("title: x # host:guidance trailing"));
283 assert!(!HOST.is_guidance_marker("<!-- host:only state=done -->"));
284 }
285}