manganis_common/
config.rs

1use serde::{Deserialize, Serialize};
2
3use crate::cache::config_path;
4
5fn default_assets_serve_location() -> String {
6    "/".to_string()
7}
8
9/// The configuration for collecting assets
10#[derive(Serialize, Deserialize, Debug)]
11pub struct Config {
12    #[serde(default = "default_assets_serve_location")]
13    assets_serve_location: String,
14}
15
16impl Config {
17    /// The location where assets will be served from. On web applications, this should be the URL path to the directory where assets are served from.
18    pub fn with_assets_serve_location(&self, assets_serve_location: impl Into<String>) -> Self {
19        Self {
20            assets_serve_location: assets_serve_location.into(),
21        }
22    }
23
24    /// The location where assets will be served from. On web applications, this should be the URL path to the directory where assets are served from.
25    pub fn assets_serve_location(&self) -> &str {
26        &self.assets_serve_location
27    }
28
29    /// Returns the current config
30    pub fn current() -> Self {
31        std::fs::read(config_path())
32            .ok()
33            .and_then(|config| toml::from_str(&String::from_utf8_lossy(&config)).ok())
34            .unwrap_or_default()
35    }
36
37    /// Saves the config globally. This must be run before compiling the application you are collecting assets from.
38    ///
39    /// The assets macro will read the config from the global config file and set the assets serve location to the value in the config.
40    pub fn save(&self) {
41        let config = toml::to_string(&self).unwrap();
42        let config_path = config_path();
43        std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
44        std::fs::write(config_path, config).unwrap();
45    }
46}
47
48impl Default for Config {
49    fn default() -> Self {
50        Self {
51            assets_serve_location: default_assets_serve_location(),
52        }
53    }
54}