Debian Codegraph @

third_party/rust/askama_derive/src/config.rs

raw
1 use std::borrow::{Borrow, Cow};
2 use std::collections::btree_map::{BTreeMap, Entry};
3 use std::mem::ManuallyDrop;
4 use std::ops::Deref;
5 use std::path::{Path, PathBuf};
6 use std::sync::{Arc, OnceLock};
7 use std::{env, fs};
8
9 use parser::node::Whitespace;
10 use parser::{ParseError, Parsed, Syntax, SyntaxBuilder};
11 use proc_macro2::Span;
12 #[cfg(feature = "config")]
13 use serde_derive::Deserialize;
14
15 use crate::{CompileError, FileInfo, OnceMap};
16
17 #[derive(Debug)]
18 pub(crate) struct Config {
19 pub(crate) dirs: Vec<PathBuf>,
20 pub(crate) syntaxes: BTreeMap<String, SyntaxAndCache<'static>>,
21 pub(crate) default_syntax: &'static str,
22 pub(crate) escapers: Vec<(Vec<Cow<'static, str>>, Cow<'static, str>)>,
23 pub(crate) whitespace: Whitespace,
24 pub(crate) full_config_path: Option<PathBuf>,
25 // `Config` is self referential and `_key` owns it data, so it must come last
26 _key: OwnedConfigKey,
27 }
28
29 impl Drop for Config {
30 #[track_caller]
31 fn drop(&mut self) {
32 panic!();
33 }
34 }
35
36 #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
37 struct OwnedConfigKey(&'static ConfigKey<'static>);
38
39 #[derive(Debug, PartialEq, Eq, Hash)]
40 struct ConfigKey<'a> {
41 root: Cow<'a, Path>,
42 source: Cow<'a, str>,
43 config_path: Option<Cow<'a, str>>,
44 template_whitespace: Option<Whitespace>,
45 }
46
47 impl ToOwned for ConfigKey<'_> {
48 type Owned = OwnedConfigKey;
49
50 fn to_owned(&self) -> Self::Owned {
51 let owned_key = ConfigKey {
52 root: Cow::Owned(self.root.as_ref().to_owned()),
53 source: Cow::Owned(self.source.as_ref().to_owned()),
54 config_path: self
55 .config_path
56 .as_ref()
57 .map(|s| Cow::Owned(s.as_ref().to_owned())),
58 template_whitespace: self.template_whitespace,
59 };
60 OwnedConfigKey(Box::leak(Box::new(owned_key)))
61 }
62 }
63
64 impl<'a> Borrow<ConfigKey<'a>> for OwnedConfigKey {
65 #[inline]
66 fn borrow(&self) -> &ConfigKey<'a> {
67 self.0
68 }
69 }
70
71 impl Config {
72 pub(crate) fn new(
73 source: &str,
74 config_path: Option<&str>,
75 template_whitespace: Option<Whitespace>,
76 config_span: Option<Span>,
77 full_config_path: Option<PathBuf>,
78 ) -> Result<&'static Config, CompileError> {
79 static CACHE: ManuallyDrop<OnceLock<OnceMap<OwnedConfigKey, &'static Config>>> =
80 ManuallyDrop::new(OnceLock::new());
81 CACHE.get_or_init(OnceMap::default).get_or_try_insert(
82 &ConfigKey {
83 root: Cow::Owned(manifest_root()),
84 source: source.into(),
85 config_path: config_path.map(Cow::Borrowed),
86 template_whitespace,
87 },
88 |key| {
89 let config = Config::new_uncached(key.to_owned(), config_span, full_config_path)?;
90 let config = &*Box::leak(Box::new(config));
91 Ok((config._key, config))
92 },
93 |config| *config,
94 )
95 }
96 }
97
98 impl Config {
99 fn new_uncached(
100 key: OwnedConfigKey,
101 config_span: Option<Span>,
102 full_config_path: Option<PathBuf>,
103 ) -> Result<Config, CompileError> {
104 let s = key.0.source.as_ref();
105 let config_path = key.0.config_path.as_deref();
106 let root = key.0.root.as_ref();
107
108 let default_dirs = vec![root.join("templates")];
109
110 let mut syntaxes = BTreeMap::new();
111 syntaxes.insert(DEFAULT_SYNTAX_NAME.to_string(), SyntaxAndCache::default());
112
113 let raw = if s.is_empty() {
114 RawConfig::default()
115 } else {
116 RawConfig::from_toml_str(s)?
117 };
118
119 let (dirs, default_syntax, whitespace) = match raw.general {
120 Some(General {
121 dirs,
122 default_syntax,
123 whitespace,
124 }) => (
125 dirs.map_or(default_dirs, |v| {
126 v.into_iter().map(|dir| root.join(dir)).collect()
127 }),
128 default_syntax.unwrap_or(DEFAULT_SYNTAX_NAME),
129 whitespace,
130 ),
131 None => (default_dirs, DEFAULT_SYNTAX_NAME, Whitespace::default()),
132 };
133 let file_info = config_path.map(|path| FileInfo::new(Path::new(path), None, None));
134 let whitespace = key.0.template_whitespace.unwrap_or(whitespace);
135
136 if let Some(raw_syntaxes) = raw.syntax {
137 for raw_s in raw_syntaxes {
138 let name = raw_s.name;
139 match syntaxes.entry(name.to_string()) {
140 Entry::Vacant(entry) => {
141 entry.insert(raw_s.to_syntax().map(SyntaxAndCache::new).map_err(
142 |err| CompileError::new_with_span(err, file_info, config_span),
143 )?);
144 }
145 Entry::Occupied(_) => {
146 return Err(CompileError::new(
147 format_args!("syntax {name:?} is already defined"),
148 file_info,
149 ));
150 }
151 }
152 }
153 }
154
155 if !syntaxes.contains_key(default_syntax) {
156 return Err(CompileError::new(
157 format_args!("default syntax \"{default_syntax}\" not found"),
158 file_info,
159 ));
160 }
161
162 let mut escapers = Vec::new();
163 if let Some(configured) = raw.escaper {
164 for escaper in configured {
165 escapers.push((str_set(&escaper.extensions), escaper.path.into()));
166 }
167 }
168 for (extensions, name) in DEFAULT_ESCAPERS {
169 escapers.push((
170 str_set(extensions),
171 format!("askama::filters::{name}").into(),
172 ));
173 }
174
175 Ok(Config {
176 dirs,
177 syntaxes,
178 default_syntax,
179 escapers,
180 whitespace,
181 full_config_path,
182 _key: key,
183 })
184 }
185
186 pub(crate) fn find_template(
187 &self,
188 path: &str,
189 start_at: Option<&Path>,
190 file_info: Option<FileInfo<'_>>,
191 ) -> Result<Arc<Path>, CompileError> {
192 let path = 'find_path: {
193 if let Some(root) = start_at {
194 let relative = root.with_file_name(path);
195 if relative.exists() {
196 break 'find_path relative;
197 }
198 }
199 for dir in &self.dirs {
200 let rooted = dir.join(path);
201 if rooted.exists() {
202 break 'find_path rooted;
203 }
204 }
205 return Err(CompileError::new(
206 format_args!(
207 "template {:?} not found in directories {:?}",
208 path, self.dirs,
209 ),
210 file_info,
211 ));
212 };
213 match path.canonicalize() {
214 Ok(path) => Ok(path.into()),
215 Err(err) => Err(CompileError::new(
216 format_args!("could not canonicalize path {path:?}: {err}"),
217 file_info,
218 )),
219 }
220 }
221 }
222
223 #[derive(Debug, Default)]
224 pub(crate) struct SyntaxAndCache<'a> {
225 syntax: Syntax<'a>,
226 cache: OnceMap<OwnedSyntaxAndCacheKey, Arc<Parsed>>,
227 }
228
229 impl<'a> Deref for SyntaxAndCache<'a> {
230 type Target = Syntax<'a>;
231
232 fn deref(&self) -> &Self::Target {
233 &self.syntax
234 }
235 }
236
237 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
238 struct OwnedSyntaxAndCacheKey(SyntaxAndCacheKey<'static>);
239
240 impl Deref for OwnedSyntaxAndCacheKey {
241 type Target = SyntaxAndCacheKey<'static>;
242
243 fn deref(&self) -> &Self::Target {
244 &self.0
245 }
246 }
247
248 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
249 struct SyntaxAndCacheKey<'a> {
250 source: Cow<'a, Arc<str>>,
251 source_path: Option<Cow<'a, Arc<Path>>>,
252 }
253
254 impl<'a> Borrow<SyntaxAndCacheKey<'a>> for OwnedSyntaxAndCacheKey {
255 fn borrow(&self) -> &SyntaxAndCacheKey<'a> {
256 &self.0
257 }
258 }
259
260 impl<'a> SyntaxAndCache<'a> {
261 fn new(syntax: Syntax<'a>) -> Self {
262 Self {
263 syntax,
264 cache: OnceMap::default(),
265 }
266 }
267
268 pub(crate) fn parse(
269 &self,
270 source: Arc<str>,
271 source_path: Option<Arc<Path>>,
272 ) -> Result<Arc<Parsed>, ParseError> {
273 self.cache.get_or_try_insert(
274 &SyntaxAndCacheKey {
275 source: Cow::Owned(source),
276 source_path: source_path.map(Cow::Owned),
277 },
278 |key| {
279 let key = OwnedSyntaxAndCacheKey(SyntaxAndCacheKey {
280 source: Cow::Owned(Arc::clone(key.source.as_ref())),
281 source_path: key
282 .source_path
283 .as_deref()
284 .map(|v| Cow::Owned(Arc::clone(v))),
285 });
286 let parsed = Parsed::new(
287 Arc::clone(key.source.as_ref()),
288 key.source_path.as_deref().map(Arc::clone),
289 &self.syntax,
290 )?;
291 Ok((key, Arc::new(parsed)))
292 },
293 Arc::clone,
294 )
295 }
296 }
297
298 #[cfg_attr(feature = "config", derive(Deserialize))]
299 #[derive(Default)]
300 struct RawConfig<'a> {
301 #[cfg_attr(feature = "config", serde(borrow))]
302 general: Option<General<'a>>,
303 syntax: Option<Vec<SyntaxBuilder<'a>>>,
304 escaper: Option<Vec<RawEscaper<'a>>>,
305 }
306
307 impl RawConfig<'_> {
308 #[cfg(feature = "config")]
309 fn from_toml_str(s: &str) -> Result<RawConfig<'_>, CompileError> {
310 basic_toml::from_str(s).map_err(|e| {
311 CompileError::no_file_info(format!("invalid TOML in {CONFIG_FILE_NAME}: {e}"), None)
312 })
313 }
314
315 #[cfg(not(feature = "config"))]
316 fn from_toml_str(_: &str) -> Result<RawConfig<'_>, CompileError> {
317 Err(CompileError::no_file_info(
318 "TOML support not available",
319 None,
320 ))
321 }
322 }
323
324 #[cfg_attr(feature = "config", derive(Deserialize))]
325 struct General<'a> {
326 #[cfg_attr(feature = "config", serde(borrow))]
327 dirs: Option<Vec<&'a str>>,
328 default_syntax: Option<&'a str>,
329 #[cfg_attr(feature = "config", serde(default))]
330 whitespace: Whitespace,
331 }
332
333 #[cfg_attr(feature = "config", derive(Deserialize))]
334 struct RawEscaper<'a> {
335 path: &'a str,
336 extensions: Vec<&'a str>,
337 }
338
339 pub(crate) fn read_config_file(
340 config_path: Option<&str>,
341 span: Option<Span>,
342 ) -> Result<(String, Option<PathBuf>), CompileError> {
343 let root = manifest_root();
344 let filename = match config_path {
345 Some(config_path) => root.join(config_path),
346 None => root.join(CONFIG_FILE_NAME),
347 };
348
349 if filename.exists() {
350 let content = fs::read_to_string(&filename).map_err(|err| {
351 CompileError::no_file_info(
352 format_args!("unable to read {}: {err}", filename.display()),
353 span,
354 )
355 })?;
356 Ok((content, filename.canonicalize().ok()))
357 } else if config_path.is_some() {
358 Err(CompileError::no_file_info(
359 format_args!("`{}` does not exist", filename.display()),
360 span,
361 ))
362 } else {
363 Ok((String::new(), None))
364 }
365 }
366
367 fn manifest_root() -> PathBuf {
368 env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from("."), PathBuf::from)
369 }
370
371 fn str_set(vals: &[&'static str]) -> Vec<Cow<'static, str>> {
372 vals.iter().map(|s| Cow::Borrowed(*s)).collect()
373 }
374
375 static CONFIG_FILE_NAME: &str = "askama.toml";
376 static DEFAULT_SYNTAX_NAME: &str = "default";
377 static DEFAULT_ESCAPERS: &[(&[&str], &str)] = &[
378 (
379 &[
380 "askama", "html", "htm", "j2", "jinja", "jinja2", "rinja", "svg", "xml",
381 ],
382 "Html",
383 ),
384 (&["md", "none", "txt", "yml", ""], "Text"),
385 ];
386
387 #[cfg(test)]
388 mod tests {
389 use std::path::{Path, PathBuf};
390
391 use super::*;
392
393 #[test]
394 fn test_default_config() {
395 let mut root = manifest_root();
396 root.push("templates");
397 let config = Config::new("", None, None, None, None).unwrap();
398 assert_eq!(config.dirs, vec![root]);
399 }
400
401 #[cfg(feature = "config")]
402 #[test]
403 fn test_config_dirs() {
404 let mut root = manifest_root();
405 root = root.join("tpl");
406 let config = Config::new("[general]\ndirs = [\"tpl\"]", None, None, None, None).unwrap();
407 assert_eq!(config.dirs, vec![root]);
408 }
409
410 fn assert_eq_rooted(actual: &Path, expected: &str) {
411 let mut root = manifest_root().canonicalize().unwrap();
412 if root.ends_with("askama_derive_standalone") {
413 root.pop();
414 root.push("askama_derive");
415 }
416
417 root.push("templates");
418 let mut inner = PathBuf::new();
419 inner.push(expected);
420 assert_eq!(actual.strip_prefix(root).unwrap(), inner);
421 }
422
423 #[test]
424 fn find_absolute() {
425 let config = Config::new("", None, None, None, None).unwrap();
426 let root = config.find_template("a.html", None, None).unwrap();
427 let path = config
428 .find_template("sub/b.html", Some(&root), None)
429 .unwrap();
430 assert_eq_rooted(&path, "sub/b.html");
431 }
432
433 #[test]
434 #[should_panic]
435 fn find_relative_nonexistent() {
436 let config = Config::new("", None, None, None, None).unwrap();
437 let root = config.find_template("a.html", None, None).unwrap();
438 config.find_template("c.html", Some(&root), None).unwrap();
439 }
440
441 #[test]
442 fn find_relative() {
443 let config = Config::new("", None, None, None, None).unwrap();
444 let root = config.find_template("sub/b.html", None, None).unwrap();
445 let path = config.find_template("c.html", Some(&root), None).unwrap();
446 assert_eq_rooted(&path, "sub/c.html");
447 }
448
449 #[test]
450 fn find_relative_sub() {
451 let config = Config::new("", None, None, None, None).unwrap();
452 let root = config.find_template("sub/b.html", None, None).unwrap();
453 let path = config
454 .find_template("sub1/d.html", Some(&root), None)
455 .unwrap();
456 assert_eq_rooted(&path, "sub/sub1/d.html");
457 }
458
459 #[cfg(feature = "config")]
460 #[test]
461 fn add_syntax() {
462 let raw_config = r#"
463 [general]
464 default_syntax = "foo"
465
466 [[syntax]]
467 name = "foo"
468 block_start = "{<"
469
470 [[syntax]]
471 name = "bar"
472 expr_start = "{!"
473 "#;
474
475 let default_syntax = Syntax::default();
476 let config = Config::new(raw_config, None, None, None, None).unwrap();
477 assert_eq!(config.default_syntax, "foo");
478
479 let foo = config.syntaxes.get("foo").unwrap();
480 assert_eq!(foo.block_start, "{<");
481 assert_eq!(foo.block_end, default_syntax.block_end);
482 assert_eq!(foo.expr_start, default_syntax.expr_start);
483 assert_eq!(foo.expr_end, default_syntax.expr_end);
484 assert_eq!(foo.comment_start, default_syntax.comment_start);
485 assert_eq!(foo.comment_end, default_syntax.comment_end);
486
487 let bar = config.syntaxes.get("bar").unwrap();
488 assert_eq!(bar.block_start, default_syntax.block_start);
489 assert_eq!(bar.block_end, default_syntax.block_end);
490 assert_eq!(bar.expr_start, "{!");
491 assert_eq!(bar.expr_end, default_syntax.expr_end);
492 assert_eq!(bar.comment_start, default_syntax.comment_start);
493 assert_eq!(bar.comment_end, default_syntax.comment_end);
494 }
495
496 #[cfg(feature = "config")]
497 #[test]
498 fn add_syntax_two() {
499 let raw_config = r#"
500 syntax = [{ name = "foo", block_start = "{<" },
501 { name = "bar", expr_start = "{!" } ]
502
503 [general]
504 default_syntax = "foo"
505 "#;
506
507 let default_syntax = Syntax::default();
508 let config = Config::new(raw_config, None, None, None, None).unwrap();
509 assert_eq!(config.default_syntax, "foo");
510
511 let foo = config.syntaxes.get("foo").unwrap();
512 assert_eq!(foo.block_start, "{<");
513 assert_eq!(foo.block_end, default_syntax.block_end);
514 assert_eq!(foo.expr_start, default_syntax.expr_start);
515 assert_eq!(foo.expr_end, default_syntax.expr_end);
516 assert_eq!(foo.comment_start, default_syntax.comment_start);
517 assert_eq!(foo.comment_end, default_syntax.comment_end);
518
519 let bar = config.syntaxes.get("bar").unwrap();
520 assert_eq!(bar.block_start, default_syntax.block_start);
521 assert_eq!(bar.block_end, default_syntax.block_end);
522 assert_eq!(bar.expr_start, "{!");
523 assert_eq!(bar.expr_end, default_syntax.expr_end);
524 assert_eq!(bar.comment_start, default_syntax.comment_start);
525 assert_eq!(bar.comment_end, default_syntax.comment_end);
526 }
527
528 #[cfg(feature = "config")]
529 #[test]
530 fn longer_delimiters() {
531 let raw_config = r#"
532 [[syntax]]
533 name = "emoji"
534 block_start = "👉🙂👉"
535 block_end = "👈🙃👈"
536 expr_start = "🤜🤜"
537 expr_end = "🤛🤛"
538 comment_start = "👎_(ツ)_👎"
539 comment_end = "👍:D👍"
540
541 [general]
542 default_syntax = "emoji"
543 "#;
544
545 let config = Config::new(raw_config, None, None, None, None).unwrap();
546 assert_eq!(config.default_syntax, "emoji");
547
548 let foo = config.syntaxes.get("emoji").unwrap();
549 assert_eq!(foo.block_start, "👉🙂👉");
550 assert_eq!(foo.block_end, "👈🙃👈");
551 assert_eq!(foo.expr_start, "🤜🤜");
552 assert_eq!(foo.expr_end, "🤛🤛");
553 assert_eq!(foo.comment_start, "👎_(ツ)_👎");
554 assert_eq!(foo.comment_end, "👍:D👍");
555 }
556
557 #[cfg(feature = "config")]
558 #[test]
559 fn illegal_delimiters() {
560 #[track_caller]
561 fn expect_err<T, E>(result: Result<T, E>) -> E {
562 match result {
563 Ok(_) => panic!("should have failed"),
564 Err(err) => err,
565 }
566 }
567
568 let raw_config = r#"
569 [[syntax]]
570 name = "too_short"
571 block_start = "<"
572 "#;
573 let config = Config::new(raw_config, None, None, None, None);
574 assert_eq!(
575 expect_err(config).msg,
576 r#"delimiters must be at least two characters long. The opening block delimiter ("<") is too short"#,
577 );
578
579 let raw_config = r#"
580 [[syntax]]
581 name = "contains_ws"
582 block_start = " {{ "
583 "#;
584 let config = Config::new(raw_config, None, None, None, None);
585 assert_eq!(
586 expect_err(config).msg,
587 r#"delimiters may not contain white spaces. The opening block delimiter (" {{ ") contains white spaces"#,
588 );
589
590 let raw_config = r#"
591 [[syntax]]
592 name = "is_prefix"
593 block_start = "{{"
594 expr_start = "{{$"
595 comment_start = "{{#"
596 "#;
597 let config = Config::new(raw_config, None, None, None, None);
598 assert_eq!(
599 expect_err(config).msg,
600 r#"an opening delimiter may not be the prefix of another delimiter. The block delimiter ("{{") clashes with the expression delimiter ("{{$")"#,
601 );
602 }
603
604 #[cfg(feature = "config")]
605 #[should_panic]
606 #[test]
607 fn use_default_at_syntax_name() {
608 let raw_config = r#"
609 syntax = [{ name = "default" }]
610 "#;
611
612 let _config = Config::new(raw_config, None, None, None, None).unwrap();
613 }
614
615 #[cfg(feature = "config")]
616 #[should_panic]
617 #[test]
618 fn duplicated_syntax_name_on_list() {
619 let raw_config = r#"
620 syntax = [{ name = "foo", block_start = "~<" },
621 { name = "foo", block_start = "%%" } ]
622 "#;
623
624 let _config = Config::new(raw_config, None, None, None, None).unwrap();
625 }
626
627 #[cfg(feature = "config")]
628 #[should_panic]
629 #[test]
630 fn is_not_exist_default_syntax() {
631 let raw_config = r#"
632 [general]
633 default_syntax = "foo"
634 "#;
635
636 let _config = Config::new(raw_config, None, None, None, None).unwrap();
637 }
638
639 #[cfg(feature = "config")]
640 #[test]
641 fn escape_modes() {
642 let config = Config::new(
643 r#"
644 [[escaper]]
645 path = "::my_filters::Js"
646 extensions = ["js"]
647 "#,
648 None,
649 None,
650 None,
651 None,
652 )
653 .unwrap();
654 assert_eq!(
655 config.escapers,
656 vec![
657 (str_set(&["js"]), "::my_filters::Js".into()),
658 (
659 str_set(&[
660 "askama", "html", "htm", "j2", "jinja", "jinja2", "rinja", "svg", "xml"
661 ]),
662 "askama::filters::Html".into()
663 ),
664 (
665 str_set(&["md", "none", "txt", "yml", ""]),
666 "askama::filters::Text".into()
667 ),
668 ]
669 );
670 }
671
672 #[cfg(feature = "config")]
673 #[test]
674 fn test_whitespace_parsing() {
675 let config = Config::new(
676 r#"
677 [general]
678 whitespace = "suppress"
679 "#,
680 None,
681 None,
682 None,
683 None,
684 )
685 .unwrap();
686 assert_eq!(config.whitespace, Whitespace::Suppress);
687
688 let config = Config::new(r#""#, None, None, None, None).unwrap();
689 assert_eq!(config.whitespace, Whitespace::Preserve);
690
691 let config = Config::new(
692 r#"
693 [general]
694 whitespace = "preserve"
695 "#,
696 None,
697 None,
698 None,
699 None,
700 )
701 .unwrap();
702 assert_eq!(config.whitespace, Whitespace::Preserve);
703
704 let config = Config::new(
705 r#"
706 [general]
707 whitespace = "minimize"
708 "#,
709 None,
710 None,
711 None,
712 None,
713 )
714 .unwrap();
715 assert_eq!(config.whitespace, Whitespace::Minimize);
716 }
717
718 #[cfg(feature = "config")]
719 #[test]
720 fn test_whitespace_in_template() {
721 // Checking that template arguments have precedence over general configuration.
722 // So in here, in the template arguments, there is `whitespace = "minimize"` so
723 // the `Whitespace` should be `Minimize` as well.
724 let config = Config::new(
725 r#"
726 [general]
727 whitespace = "suppress"
728 "#,
729 None,
730 Some(Whitespace::Minimize),
731 None,
732 None,
733 )
734 .unwrap();
735 assert_eq!(config.whitespace, Whitespace::Minimize);
736
737 let config = Config::new(r#""#, None, Some(Whitespace::Minimize), None, None).unwrap();
738 assert_eq!(config.whitespace, Whitespace::Minimize);
739 }
740 }