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
//! A [`Visitor`](`crate::visit::Visitor`) implementation which creates events for
//! files which differ from the content it would have once deployed.

use crate::{
	profile::LayeredProfile,
	profile::{source::PunktfSource, transform::Transform},
	visit::*,
};
use std::path::Path;

/// Applies any relevant [`Transform`](`crate::profile::transform::Transform`)
/// for the given file.
fn transform_content(profile: &LayeredProfile, file: &File<'_>, content: String) -> String {
	let mut content = content;

	// Copy so we exec_dotfile is not referenced by this in case an error occurs.
	let exec_transformers: Vec<_> = file.dotfile().transformers.to_vec();

	// Apply transformers.
	// Order:
	//   - Transformers which are specified in the profile root
	//   - Transformers which are specified on a specific dotfile of a profile
	for transformer in profile.transformers().chain(exec_transformers.iter()) {
		content = transformer.transform(content).unwrap();
	}

	content
}

/// An event which is emitted for every differing item.
#[derive(Debug)]
pub enum Event<'a> {
	/// File does currently not exist but would be created.
	NewFile(&'a Path),

	/// Directory does currently not exist but would be created.
	NewDirectory(&'a Path),

	/// File does exist but the contents would changed.
	Diff {
		/// Absoulte path to the target location.
		target_path: &'a Path,

		/// Contents of the current file on the filesystem.
		old_content: String,

		/// Contents of the file after a deployment.
		///
		/// #NOTE
		/// If the contents come from a template item, it will be already
		/// fully resolved.
		new_contnet: String,
	},
}

impl Event<'_> {
	/// Returns the absolute target path for the diff.
	pub const fn target_path(&self) -> &Path {
		match self {
			Self::NewFile(p) => p,
			Self::NewDirectory(p) => p,
			Self::Diff { target_path, .. } => target_path,
		}
	}
}

/// A [`Visitor`](`crate::visit::Visitor`) implementation which checks for
/// changes which would be made by a deployment.
/// For each change an [`Event`] is emitted which can be processed by [`Diff.0`].
#[derive(Debug, Clone, Copy)]
pub struct Diff<F>(F);

impl<F> Diff<F>
where
	F: Fn(Event<'_>),
{
	/// Creates a new instance of the visitor.
	pub const fn new(f: F) -> Self {
		Self(f)
	}

	/// Runs the visitor to completion for a given profile.
	pub fn diff(self, source: &PunktfSource, profile: &mut LayeredProfile) {
		let mut resolver = ResolvingVisitor(self);
		let walker = Walker::new(profile);
		walker.walk(source, &mut resolver).unwrap();
	}

	/// Emits the given event.
	fn dispatch(&self, event: Event<'_>) {
		(self.0)(event)
	}
}

impl<F> Visitor for Diff<F>
where
	F: Fn(Event<'_>),
{
	/// Accepts a file item and checks if it differs in any way to the counter
	/// part on the filesystem (deployed item).
	///
	/// If so, a change [`Event::NewFile`]/[`Event::Diff`] is emitted.
	fn accept_file<'a>(
		&mut self,
		_: &PunktfSource,
		profile: &LayeredProfile,
		file: &File<'a>,
	) -> Result {
		if file.target_path.exists() {
			let new = transform_content(
				profile,
				file,
				std::fs::read_to_string(&file.source_path).unwrap(),
			);
			let old = std::fs::read_to_string(&file.target_path).unwrap();

			if new != old {
				self.dispatch(Event::Diff {
					target_path: &file.target_path,
					old_content: old,
					new_contnet: new,
				});
			}
		} else {
			self.dispatch(Event::NewFile(&file.target_path))
		}

		Ok(())
	}

	/// Accepts a directory item and simly checks if it already exists on the filesystem.
	///
	/// If no, a change [`Event::NewDirectory`] is emitted.
	fn accept_directory<'a>(
		&mut self,
		_: &PunktfSource,
		_: &LayeredProfile,
		directory: &Directory<'a>,
	) -> Result {
		if !directory.target_path.exists() {
			self.dispatch(Event::NewDirectory(&directory.target_path))
		}

		Ok(())
	}

	/// Accepts a rejected item and does nothing besides logging an info message.
	///
	/// # NOTE
	/// Links are currently not supported for diffing.
	fn accept_link(&mut self, _: &PunktfSource, _: &LayeredProfile, link: &Symlink) -> Result {
		log::info!(
			"[{}] Symlinks are not supported for diffs",
			link.source_path.display()
		);

		Ok(())
	}

	/// Accepts a rejected item and does nothing besides logging an info message.
	fn accept_rejected<'a>(
		&mut self,
		_: &PunktfSource,
		_: &LayeredProfile,
		rejected: &Rejected<'a>,
	) -> Result {
		log::info!(
			"[{}] Rejected - {}",
			rejected.relative_source_path.display(),
			rejected.reason,
		);

		Ok(())
	}

	/// Accepts a rejected item and does nothing besides logging an error message.
	fn accept_errored<'a>(
		&mut self,
		_: &PunktfSource,
		_: &LayeredProfile,
		errored: &Errored<'a>,
	) -> Result {
		log::error!(
			"[{}] Error - {}",
			errored.relative_source_path.display(),
			errored
		);

		Ok(())
	}
}

impl<F> TemplateVisitor for Diff<F>
where
	F: Fn(Event<'_>),
{
	/// Accepts a file template item and checks if it differs in any way to the
	/// counter part on the filesystem (deployed item).
	///
	/// If so, a change [`Event::NewFile`]/[`Event::Diff`] is emitted.
	fn accept_template<'a>(
		&mut self,
		_: &PunktfSource,
		profile: &LayeredProfile,
		file: &File<'a>,
		// Returns a function to resolve the content to make the resolving lazy
		// for upstream visitors.
		resolve_content: impl FnOnce(&str) -> color_eyre::Result<String>,
	) -> Result {
		if file.target_path.exists() {
			let new = transform_content(
				profile,
				file,
				resolve_content(&std::fs::read_to_string(&file.source_path).unwrap()).unwrap(),
			);
			let old = std::fs::read_to_string(&file.target_path).unwrap();

			if new != old {
				self.dispatch(Event::Diff {
					target_path: &file.target_path,
					old_content: old,
					new_contnet: new,
				});
			}
		} else {
			self.dispatch(Event::NewFile(&file.target_path))
		}

		Ok(())
	}
}