git_cliff_core/
embed.rs

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