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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Models and structs used by and for the deployment process.

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, SystemTimeError};

use serde::{Deserialize, Serialize};

use crate::profile::dotfile::Dotfile;
use crate::profile::Priority;

/// Contains the status of a deployed item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ItemStatus {
	/// The item was successfully created.
	Success,
	/// The item deployment failed.
	Failed(Cow<'static, str>),
	/// The item deployment was skipped.
	Skipped(Cow<'static, str>),
}

impl ItemStatus {
	/// Marks the item operation as successful.
	pub const fn success() -> Self {
		Self::Success
	}

	/// Marks the item operation as failed.
	pub fn failed<S: Into<Cow<'static, str>>>(reason: S) -> Self {
		Self::Failed(reason.into())
	}

	/// Indicates that the item operation was skipped.
	pub fn skipped<S: Into<Cow<'static, str>>>(reason: S) -> Self {
		Self::Skipped(reason.into())
	}

	/// Checks if the item operation was successful.
	pub fn is_success(&self) -> bool {
		self == &Self::Success
	}

	/// Checks if the item operation has failed.
	pub const fn is_failed(&self) -> bool {
		matches!(self, &Self::Failed(_))
	}

	/// Checks if the item operation was skipped.
	pub const fn is_skipped(&self) -> bool {
		matches!(self, &Self::Skipped(_))
	}
}

impl fmt::Display for ItemStatus {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Success => f.write_str("Success"),
			Self::Failed(reason) => write!(f, "Failed: {reason}"),
			Self::Skipped(reason) => write!(f, "Skipped: {reason}"),
		}
	}
}

impl<E> From<E> for ItemStatus
where
	E: std::error::Error,
{
	fn from(value: E) -> Self {
		Self::failed(value.to_string())
	}
}

/// Defines the type of dotfile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeployedDotfileKind {
	/// A normal dotfile.
	Dotfile(Dotfile),
	/// A dotfile that is contained in a directory that is deployed.
	///
	/// PathBuf is the deploy path of the `parent` dotfile.
	/// The parent should always be of type `Dotfile(_)`.
	Child(PathBuf),
}

impl DeployedDotfileKind {
	/// Checks whether the deployed dotfile type is a normal dotfile.
	pub const fn is_dotfile(&self) -> bool {
		matches!(self, Self::Dotfile(_))
	}

	/// Checks whether the deployed dotfile type is a child dotfile.
	pub const fn is_child(&self) -> bool {
		matches!(self, Self::Child(_))
	}
}

/// Stores the result of a dotfile deployment operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeployedDotfile {
	/// The status of the deployed dotfile.
	pub status: ItemStatus,

	/// The kind of the deployed dotfile.
	pub kind: DeployedDotfileKind,
}

impl DeployedDotfile {
	/// Returns the status of the dotfile operation.
	pub const fn status(&self) -> &ItemStatus {
		&self.status
	}

	/// Returns the kind of the dotfile operation.
	pub const fn kind(&self) -> &DeployedDotfileKind {
		&self.kind
	}
}

impl AsRef<ItemStatus> for DeployedDotfile {
	fn as_ref(&self) -> &ItemStatus {
		self.status()
	}
}

/// Stores the result of a symlink deployment operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeployedSymlink {
	/// The status of the deployed symlink.
	pub status: ItemStatus,

	/// The source path of the link.
	pub source: PathBuf,
}

impl DeployedSymlink {
	/// Returns the status of the link operation.
	pub const fn status(&self) -> &ItemStatus {
		&self.status
	}

	/// Returns the source path of the link .
	pub fn source(&self) -> &Path {
		self.source.as_path()
	}
}

impl AsRef<ItemStatus> for DeployedSymlink {
	fn as_ref(&self) -> &ItemStatus {
		self.status()
	}
}

/// Describes the status of a profile deployment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeploymentStatus {
	/// The profile is deployed successfully.
	Success,
	/// There were errors during the deployment.
	Failed(Cow<'static, str>),
}

impl DeploymentStatus {
	/// Returns success.
	pub const fn success() -> Self {
		Self::Success
	}

	/// Returns a failure.
	pub fn failed<S: Into<Cow<'static, str>>>(reason: S) -> Self {
		Self::Failed(reason.into())
	}

	/// Checks if the deployment was successful.
	pub fn is_success(&self) -> bool {
		self == &Self::Success
	}

	/// Checks if the deployment has failed.
	pub const fn is_failed(&self) -> bool {
		matches!(self, &Self::Failed(_))
	}
}

impl fmt::Display for DeploymentStatus {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Success => f.write_str("Success"),
			Self::Failed(reason) => write!(f, "Failed: {reason}"),
		}
	}
}

impl<E> From<E> for DeploymentStatus
where
	E: std::error::Error,
{
	fn from(value: E) -> Self {
		Self::failed(value.to_string())
	}
}

/// Describes the deployment of a profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Deployment {
	/// The time the deployment was started.
	time_start: SystemTime,

	/// The time the deployment was finished.
	time_end: SystemTime,

	/// The status of the deployment.
	status: DeploymentStatus,

	/// The dotfiles that were deployed.
	dotfiles: HashMap<PathBuf, DeployedDotfile>,

	/// The links that were deployed.
	symlinks: HashMap<PathBuf, DeployedSymlink>,
}

impl Deployment {
	/// Returns the time the deployment was started.
	pub const fn time_start(&self) -> &SystemTime {
		&self.time_start
	}

	/// Returns the time the deployment was finished.
	pub const fn time_end(&self) -> &SystemTime {
		&self.time_end
	}

	/// Returns the duration the deployment took.
	pub fn duration(&self) -> Result<Duration, SystemTimeError> {
		self.time_end.duration_since(self.time_start)
	}

	/// Returns the status of the deployment.
	pub const fn status(&self) -> &DeploymentStatus {
		&self.status
	}

	/// Returns the dotfiles.
	pub const fn dotfiles(&self) -> &HashMap<PathBuf, DeployedDotfile> {
		&self.dotfiles
	}

	/// Returns the symlinks.
	pub const fn symlinks(&self) -> &HashMap<PathBuf, DeployedSymlink> {
		&self.symlinks
	}

	/// Builds the deployment.
	pub fn build() -> DeploymentBuilder {
		DeploymentBuilder::default()
	}
}

/// A builder for a [`Deployment`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeploymentBuilder {
	/// The start time of the deployment.
	///
	/// This used to keep track of the total execution time of the deployment
	/// process.
	time_start: SystemTime,

	/// All dotfiles which were already process by the deployment process.
	dotfiles: HashMap<PathBuf, DeployedDotfile>,

	/// All symlinks which were already process by the deployment process.
	symlinks: HashMap<PathBuf, DeployedSymlink>,
}

impl DeploymentBuilder {
	/// Adds a dotfile with the given `status` to the builder.
	pub fn add_dotfile(
		&mut self,
		path: PathBuf,
		dotfile: Dotfile,
		status: ItemStatus,
	) -> &mut Self {
		self.dotfiles.insert(
			path,
			DeployedDotfile {
				kind: DeployedDotfileKind::Dotfile(dotfile),
				status,
			},
		);

		self
	}

	/// Adds the child of a dotfile directory with the given `status` to the
	/// builder.
	pub fn add_child(&mut self, path: PathBuf, parent: PathBuf, status: ItemStatus) -> &mut Self {
		self.dotfiles.insert(
			path,
			DeployedDotfile {
				kind: DeployedDotfileKind::Child(parent),
				status,
			},
		);

		self
	}

	/// Adds a symlink with the given `status` to the builder.
	pub fn add_link(&mut self, source: PathBuf, target: PathBuf, status: ItemStatus) -> &mut Self {
		self.symlinks
			.insert(target, DeployedSymlink { source, status });

		self
	}

	/// Checks if the builder already contains a dotfile for the given `path`.
	pub fn contains<P: AsRef<Path>>(&self, path: P) -> bool {
		self.dotfiles.contains_key(path.as_ref())
	}

	/// Gets any dotfile already deployed at `path`.
	///
	/// This function ignores the status of the dotfile.
	pub fn get_dotfile<P: AsRef<Path>>(&self, path: P) -> Option<&Dotfile> {
		let mut value = self.dotfiles.get(path.as_ref())?;

		loop {
			match &value.kind {
				DeployedDotfileKind::Dotfile(dotfile) => return Some(dotfile),
				DeployedDotfileKind::Child(parent_path) => {
					value = self.dotfiles.get(parent_path)?
				}
			}
		}
	}

	/// Gets any dotfile already deployed at `path`.
	///
	/// This function only returns a dotfile with [`ItemStatus::Success`].
	pub fn get_deployed_dotfile<P: AsRef<Path>>(&self, path: P) -> Option<&Dotfile> {
		let mut value = self.dotfiles.get(path.as_ref())?;

		loop {
			if !value.status.is_success() {
				return None;
			}

			match &value.kind {
				DeployedDotfileKind::Dotfile(dotfile) => return Some(dotfile),
				DeployedDotfileKind::Child(parent_path) => {
					value = self.dotfiles.get(parent_path)?
				}
			}
		}
	}

	/// Gets the priority of the dotfile already deployed at `path`.
	///
	/// This function only evaluates a dotfile with [`ItemStatus::Success`].
	pub fn get_priority<P: AsRef<Path>>(&self, path: P) -> Option<&Priority> {
		self.get_deployed_dotfile(path)
			.and_then(|d| d.priority.as_ref())
	}

	/// Checks if a dotfile was already successfully deployed at `path`.
	///
	/// This function only evaluates a dotfile with [`ItemStatus::Success`].
	pub fn is_deployed<P: AsRef<Path>>(&self, path: P) -> Option<bool> {
		self.dotfiles
			.get(path.as_ref())
			.map(|dotfile| dotfile.status.is_success())
	}

	/// Consumes self and creates a [`Deployment`] from it.
	///
	/// This will try to guess the state of the deployment by looking for any
	/// failed deployed dotfile.
	pub fn finish(self) -> Deployment {
		let failed_dotfiles = self
			.dotfiles
			.values()
			.filter(|d| d.status.is_failed())
			.count();

		let failed_links = self
			.symlinks
			.values()
			.filter(|d| d.status.is_failed())
			.count();

		let status = if failed_dotfiles > 0 {
			DeploymentStatus::failed(format!(
				"Deployment of {failed_dotfiles} dotfiles and {failed_links} links failed"
			))
		} else {
			DeploymentStatus::Success
		};

		Deployment {
			time_start: self.time_start,
			time_end: SystemTime::now(),
			status,
			dotfiles: self.dotfiles,
			symlinks: self.symlinks,
		}
	}

	/// Consumes self and creates a [`Deployment`] from it.
	///
	/// This will mark the deployment as success.
	pub fn success(self) -> Deployment {
		Deployment {
			time_start: self.time_start,
			time_end: SystemTime::now(),
			status: DeploymentStatus::Success,
			dotfiles: self.dotfiles,
			symlinks: self.symlinks,
		}
	}

	/// Consumes self and creates a [`Deployment`] from it.
	///
	/// This will mark the deployment as failed with the reason given with
	/// `reason`.
	pub fn failed<S: Into<Cow<'static, str>>>(self, reason: S) -> Deployment {
		Deployment {
			time_start: self.time_start,
			time_end: SystemTime::now(),
			status: DeploymentStatus::Failed(reason.into()),
			dotfiles: self.dotfiles,
			symlinks: self.symlinks,
		}
	}
}

impl Default for DeploymentBuilder {
	fn default() -> Self {
		Self {
			time_start: SystemTime::now(),
			dotfiles: HashMap::new(),
			symlinks: HashMap::new(),
		}
	}
}

#[cfg(test)]
mod tests {
	use color_eyre::Result;

	use super::*;

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

		let builder = Deployment::build();
		let deployment = builder.success();

		assert!(deployment.status().is_success());
		assert!(deployment.duration()? >= Duration::from_secs(0));

		Ok(())
	}
}