vconfig_rocket/
context.rs

1use rocket::Request;
2use std::path::{Path, PathBuf};
3use vconfig::fs::ConfigStore;
4use vconfig::traits::Variants;
5
6use crate::{VariantsProcessor, builder::VariantsBuilder};
7
8pub struct VConfigContext {
9    configs: ConfigStore,
10    builder: VariantsBuilder,
11}
12
13impl VConfigContext {
14    pub fn new(base_dir: &Path) -> Option<VConfigContext> {
15        // config.
16        let mut config_store = ConfigStore::new(&base_dir.to_string_lossy());
17        config_store.with_ext("toml");
18        config_store.init();
19
20        // variants.
21        let variants_builder = VariantsBuilder::new();
22        Some(Self {
23            configs: config_store,
24            builder: variants_builder,
25        })
26    }
27
28    pub fn get_file(&self, name: &str) -> Option<PathBuf> {
29        let path = std::path::PathBuf::from(name);
30        if path.exists() {
31            return Some(path);
32        }
33
34        let path = self.configs.get_path(name);
35        match path {
36            Some(path) => {
37                if path.exists() {
38                    Some(path.to_owned())
39                } else {
40                    None
41                }
42            }
43            None => None,
44        }
45    }
46
47    pub fn build_variants<'r>(&self, request: &'r Request<'_>, variants: &mut dyn Variants) {
48        self.builder.build(request, variants);
49    }
50
51    pub fn with_processor<P: VariantsProcessor>(&mut self, processor: P) -> &mut Self {
52        self.builder.with_processor(processor);
53        self
54    }
55}