1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use crate::config::Config;
use anyhow::Result;
use std::{
	fmt, fs,
	path::{Path, PathBuf},
};
use thiserror::Error;

/// Template file
pub struct Template {
	path: PathBuf,
	pub content: String,
}

impl Template {
	pub(crate) fn new(path: impl Into<PathBuf>, content: impl Into<String>) -> Template {
		let path = path.into();
		let content = content.into();
		Template { path, content }
	}

	pub(crate) fn from_str(content: &str, config: &Config) -> Result<Template> {
		let content = config.apply(content);
		let mut lines = content.lines().skip_while(|line| line.is_empty());
		let path: &str = lines
			.next()
			.map(|x| x.trim())
			.ok_or(TemplateError::UnexpectedEOF)?;

		if !path.starts_with('#') {
			return Err(TemplateError::PathSymbolNotFound.into());
		}

		let path: &str = path
			.get(1..)
			.map(|x| x.trim())
			.ok_or(TemplateError::UnexpectedEOF)?;

		let content: String = lines.map(|x| format!("{}\n", x)).collect();
		let result = Template::new(path, content);
		Ok(result)
	}

	/// Remove all whitespace from template. **Should only be used for testing!**
	fn clean_content(&self) -> String {
		self.content.split_whitespace().collect()
	}

	/// Ensure that parent exists before generating the template
	pub(crate) fn ensure_parent(&self, path: impl AsRef<Path>) -> Result<()> {
		if let Some(parent) = path.as_ref().parent() {
			fs::create_dir_all(parent)?;
		}

		Ok(())
	}

	/// Generate template to the given root
	pub fn generate(&self, root: impl AsRef<Path>) -> Result<()> {
		let root = root.as_ref();
		let path = root.join(&self.path);
		self.ensure_parent(&path)?;
		fs::write(path, &self.content)?;
		Ok(())
	}
}

impl PartialEq for Template {
	/// To check for equality, This method will check:
	/// 1. The file path of both templates.
	/// 2. The "clean content" of both templates.
	///
	/// Note: Clean Content is a whitespace-removed content of the template, This is helpful in testing where the indentation can mess up the equality check.
	fn eq(&self, other: &Template) -> bool {
		self.path.eq(&other.path) && self.clean_content().eq(&other.clean_content())
	}
}

impl fmt::Debug for Template {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"Template {{ path: {:?}, content: {:?} }}",
			self.path,
			self.clean_content()
		)
	}
}

#[derive(Debug, Error, PartialEq)]
enum TemplateError {
	#[error("Unexpected End-of-File")]
	UnexpectedEOF,
	#[error("Path symbol not found")]
	PathSymbolNotFound,
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn basic_template() {
		let content = r#"
		# pack.mcmeta
			{
				"pack": {
					"pack_format": 5,
					"description": "This is a description"
				}
			}
		"#;

		let config = Config::new();

		let result = Template::from_str(content, &config).unwrap();
		let expect = Template::new(
			"pack.mcmeta",
			r#"
			{
				"pack": {
					"pack_format": 5,
					"description": "This is a description"
				}
			}
		"#,
		);

		assert_eq!(result, expect);
	}

	#[test]
	fn template_with_config() {
		let content = r#"
		# data/<namespace>/advancements/<datapack>.json
		{
			"display": {
				"title": "<datapack>",
				"description": "<description>",
				"icon": {
					"item": "<display_item>"
				},
				"announce_to_chat": false,
				"show_toast": false
			},
			"parent": "global:<namespace>",
			"criteria": {
				"trigger": {
					"trigger": "minecraft:tick"
				}
			}
		}		
		"#;

		let config = Config::new()
			.insert("<namespace>", "boomber")
			.insert("<datapack>", "explosion_magic")
			.insert("<description>", "Explosion!")
			.insert("<display_item>", "minecraft:tnt");

		let result = Template::from_str(content, &config).unwrap();
		let expect = Template::new(
			"data/boomber/advancements/explosion_magic.json",
			r#"
		{
			"display": {
				"title": "explosion_magic",
				"description": "Explosion!",
				"icon": {
					"item": "minecraft:tnt"
				},
				"announce_to_chat": false,
				"show_toast": false
			},
			"parent": "global:boomber",
			"criteria": {
				"trigger": {
					"trigger": "minecraft:tick"
				}
			}
		}
		"#,
		);

		assert_eq!(result, expect);
	}

	#[test]
	fn with_invalid_syntax() {
		let content = r#"Hello, world!"#;
		let config = Config::new();
		let result: TemplateError = Template::from_str(content, &config)
			.unwrap_err()
			.downcast()
			.unwrap();
		assert_eq!(result, TemplateError::PathSymbolNotFound);
	}
}