git_cliff_core/
embed.rs

1use std::path::Path;
2use std::str;
3
4use rust_embed::RustEmbed;
5
6use crate::config::Config;
7use crate::error::{Error, Result};
8
9/// Default configuration file embedder/extractor.
10///
11/// Embeds `config/`[`DEFAULT_CONFIG`] into the binary.
12///
13/// [`DEFAULT_CONFIG`]: crate::DEFAULT_CONFIG
14#[derive(Debug, RustEmbed)]
15#[folder = "config/"]
16pub struct EmbeddedConfig;
17
18impl EmbeddedConfig {
19    /// Extracts the embedded content.
20    pub fn get_config() -> Result<String> {
21        match Self::get(crate::DEFAULT_CONFIG) {
22            Some(v) => Ok(str::from_utf8(&v.data)?.to_string()),
23            None => Err(Error::EmbeddedError(String::from(
24                "Embedded config not found",
25            ))),
26        }
27    }
28
29    /// Parses the extracted content into [`Config`].
30    ///
31    /// [`Config`]: Config
32    pub fn parse() -> Result<Config> {
33        Self::get_config()?.parse()
34    }
35}
36
37/// Built-in configuration file embedder/extractor.
38///
39/// Embeds the files under `/examples/` into the binary.
40#[derive(RustEmbed)]
41#[folder = "examples/"]
42pub struct BuiltinConfig;
43
44impl BuiltinConfig {
45    /// Extracts the embedded content.
46    pub fn get_config(mut name: String) -> Result<String> {
47        if !Path::new(&name)
48            .extension()
49            .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
50        {
51            name = format!("{name}.toml");
52        }
53        let contents = match Self::get(&name) {
54            Some(v) => Ok(str::from_utf8(&v.data)?.to_string()),
55            None => Err(Error::EmbeddedError(format!("config {} not found", name,))),
56        }?;
57        Ok(contents)
58    }
59
60    /// Parses the extracted content into [`Config`] along with the name.
61    ///
62    /// [`Config`]: Config
63    pub fn parse(name: String) -> Result<(Config, String)> {
64        let parsed = Self::get_config(name.to_string())?.parse()?;
65        Ok((parsed, name))
66    }
67}