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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Everthing related to parsing/resolving templates is located in this module or it's submodules.
//!
//! # Syntax
//!
//! The syntax is heavily inspired by <https://handlebarsjs.com/>.
//!
//! ## Comment blocks
//!
//! Document template blocks. Will not be copied over to final output.
//!
//! ### Syntax
//!
//! `{{!-- This is a comment --}}`
//!
//! ## Escape blocks
//!
//! Everything inside will be copied over as is. It can be used to  copied over `{{` or `}}` without it being interpreted as a template block.
//!
//! ### Syntax
//!
//! `{{{ This will be copied over {{ as is }} even with the "{{" inside }}}`
//!
//! ## Variable blocks
//!
//! Define a variable which will be inserted instead of the block. The value of the variable can be gotten from three different environments which can be defined by specifying a prefix:
//!
//! 1) `$`: System environment
//! 2) `#`: Variables defined in the `profile` section
//! 2) `&`: Variables defined in the `profile.dotfile` section
//!
//! To search in more than one environment, these prefixes can be combined. The order they appear in is important, as they will be searched in order of appearance. If one environment does not have a value set for the variable, the next one is searched.
//!
//! If no prefixes are defined, it will default to `&#`.
//!
//! Valid symbols/characters for a variable name are: `(a..z|A..Z|0-9|_)`
//!
//! ### Syntax
//!
//! `{{$&#OS}}`
//!
//! ## Print blocks
//!
//! Print blocks will simply print everything contained within the block to the command line. The content of the print block **won't** be resolved, meaning it will be printed 1 to 1 (e.g. no variables are resolved).
//!
//! ### Syntax
//!
//! `{{@print Hello World}}`
//!
//! ## If blocks
//!
//! Supported are `if`, `elif`, `else` and `fi`. Each `if` block must have a `fi` block as a final closing block.
//! In between the `if` and `fi` block can be zero or multiple `elif` blocks with a final optional `else` block.
//! Each if related block must be prefixed with `{{@` and end with `}}`.
//!
//! Currently the only supported if syntax is:
//!
//! - Check if the value of a variable is (not) equal to the literal given: `{{VAR}} (==|!=) "LITERAL"`
//! - Check if a value for a variable exists: `{{VAR}}`
//!
//! Other blocks can be nested inside the `if`, `elif` and `else` bodies.
//!
//! ### Syntax
//!
//! ```text
//! {{@if {{OS}}}}
//!         {{@if {{&OS}} != "windows"}}
//!             print("OS is not windows")
//!         {{@elif {{OS}} == "windows"}}
//!             {{{!-- This is a nested comment. Below it is a nested variable block. --}}}
//!             print("OS is {{OS}}")
//!         {{@else}}
//!             {{{!-- This is a nested comment. --}}}
//!             print("Can never get here. {{{ {{OS}} is neither `windows` nor not `windows`. }}}")
//!         {{@fi}}
//! {{@else}}
//!     print("No value for variable `OS` set")
//! {{@fi}}
//! ```
//!
//! # Copyright Notice
//!
//! The code for error/diagnostics and source input handling is heavily inspired by
//! [rust's](https://github.com/rust-lang/rust) compiler, which is licensed under the MIT license.
//! While some code is adapted for use with `punktf`, some of it is also a plain copy of it. If a
//! portion of code was copied/adapted from the Rust project there will be an explicit notices
//! above it. For further information and the license please see the `COPYRIGHT` file in the root
//! of this project.
//!
//! Specifically but not limited to:
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/lib.rs>
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/analyze_source_file.rs>
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_parse/src/parser/diagnostics.rs>
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_errors/src/diagnostic.rs>
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_errors/src/diagnostic_builder.rs>
//! - <https://github.com/rust-lang/rust/blob/master/compiler/rustc_errors/src/emitter.rs>

mod block;
mod diagnostic;
mod parse;
mod resolve;
mod session;
pub mod source;
mod span;

use color_eyre::eyre::Result;

use self::block::Block;
use self::parse::Parser;
use self::resolve::Resolver;
use self::source::Source;
use crate::profile::variables::Vars;

/// A `Template` is a file from the Source folder that is not yet deployed. It might contain statements and variables.
#[derive(Debug, Clone)]
pub struct Template<'a> {
	/// The source from which the template was parsed from.
	source: Source<'a>,

	/// All parsed blocks contained in `source`.
	///
	/// These are sorted in the order they occur in `source`.
	blocks: Vec<Block>,
}

impl<'a> Template<'a> {
	/// Parses the source file and returns a `Template` object.
	pub fn parse(source: Source<'a>) -> Result<Self> {
		Parser::new(source).parse()
	}

	/// Resolves the variables in the template and returns a `Template` object.
	pub fn resolve<PV: Vars, DV: Vars>(
		&self,
		profile_vars: Option<&PV>,
		dotfile_vars: Option<&DV>,
	) -> Result<String> {
		Resolver::new(self, profile_vars, dotfile_vars).resolve()
	}
}

#[cfg(test)]
mod tests {
	use std::collections::HashMap;

	use super::*;
	use crate::profile::variables::Variables;

	#[test]
	fn parse_template() -> Result<()> {
		crate::tests::setup_test_env();

		let content = r#"
			[some settings]
			var = 2
			foo = "bar"
			fizz = {{BUZZ}}
			escaped = {{{42}}}

			{{!--
				Sets the message of the day for a specific operating system
				If no os matches it defaults to a generic one.
			--}}
			{{@print Writing motd...}}
			{{@if {{&OS}} == "linux" }}
			{{@print Linux Motd!}}
			[linux]
			motd = "very nice"
			{{@elif {{&#OS}} == "windows" }}
			[windows]
			motd = "nice"
			{{@else}}
			[other]
			motd = "who knows"
			{{@fi}}

			{{!-- Check if not windows --}}
			{{@if {{&OS}} != "windows"}}
			windows = false
			{{@fi}}

			[last]
			num = 23
			threads = 1337
			os_str = "_unkown"
			"#;

		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		// println!("{:#?}", template);

		let mut vars = HashMap::new();
		vars.insert(String::from("BUZZ"), String::from("Hello World"));
		vars.insert(String::from("OS"), String::from("linux"));
		let vars = Variables { inner: vars };

		println!("{}", template.resolve(Some(&vars), Some(&vars))?);

		Ok(())
	}

	#[test]
	fn parse_template_vars() -> Result<()> {
		crate::tests::setup_test_env();

		// Default
		let content = r#"{{OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::set_var("OS", "macos");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"unix"
		);

		// Profile
		let content = r#"{{#OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::set_var("OS", "macos");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"windows"
		);

		// Item
		let content = r#"{{&OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::set_var("OS", "macos");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"unix"
		);

		// Env
		let content = r#"{{$OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::set_var("OS", "macos");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"macos"
		);

		// Mixed - First
		let content = r#"{{$#OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::set_var("OS", "macos");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"macos"
		);

		// Mixed - Last
		let content = r#"{{$&OS}}"#;
		let source = Source::anonymous(content);
		let template = Template::parse(source)?;

		let profile_vars = Variables::from_items(vec![("OS", "windows")]);
		let item_vars = Variables::from_items(vec![("OS", "unix")]);
		std::env::remove_var("OS");

		assert_eq!(
			template.resolve(Some(&profile_vars), Some(&item_vars))?,
			"unix"
		);

		Ok(())
	}
}