turboinstall 0.3.2

A simple tool for overlaying directory trees on top of each other
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
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use colored::Colorize;
use lazy_static::__Deref;
use log::{error, info, warn};

use crate::cli::Options;
use crate::profile::Profile;

mod ignore;
pub mod platform;

lazy_static::lazy_static! {
	static ref DEFAULT_IGNORE_FILES: Vec<PathBuf> = [
		".turboinstall/ignore"
	].iter().map(|x| Path::new(x).to_path_buf()).collect();
}

const DEFAULT_IGNORE: &[&str] = &["^/.turboinstall"];

#[derive(Debug, Clone, PartialEq, Eq, clap::ValueEnum)]
pub enum HookType {
	PreInstall,
	PostInstall,
}

impl HookType {
	pub(self) fn hook_dir_name(&self) -> &str {
		match self {
			HookType::PreInstall => "pre-install",
			HookType::PostInstall => "post-install",
		}
	}
}

#[derive(Debug)]
pub struct Overlay {
	src: PathBuf,
	dst: PathBuf,
}

impl Overlay {
	pub fn new(
		src: impl AsRef<Path>,
		dst: impl AsRef<Path>,
	) -> Result<Self> {
		let src = src.as_ref();
		let dst = dst.as_ref();

		let src = src.canonicalize().with_context(move || {
			format!("'{}' does not exist", src.display())
		})?;

		if !src.is_dir() {
			bail!("'{}' is not a directory", src.display())
		}

		let dst = dst.canonicalize().with_context(move || {
			format!("'{}' does not exist", dst.display())
		})?;

		if !dst.is_dir() {
			bail!("'{}' is not a directory", dst.display())
		}

		if src.ancestors().any(|x| x == dst) {
			bail!(
				"source '{}' cannot be in destination '{}'",
				src.display(),
				dst.display()
			)
		}

		if dst.ancestors().any(|x| x == src) {
			bail!(
				"destination '{}' cannot be in source '{}'",
				dst.display(),
				src.display()
			)
		}

		Ok(Self { src, dst })
	}

	pub fn install(
		&mut self,
		profile: &dyn Profile,
		options: &Options,
	) -> Result<()> {
		let mut ignore = ignore::Ignore::empty();

		// default ignores
		for pattern in DEFAULT_IGNORE
			.iter()
			.map(|x| x.deref())
			.chain(options.ignore_patterns.iter().map(|x| x.as_str()))
		{
			ignore.add_pattern(pattern).with_context(|| {
				format!("Pattern '{}' failed to compile!", pattern)
			})?;
		}

		// load ignore files if they exists
		{
			// if the ignore path is absolute it will overwrite the self.src prefix
			// and thus correctly use the absolute path
			for ignore_path in DEFAULT_IGNORE_FILES
				.iter()
				.chain(options.ignore_paths.iter())
			{
				let ignore_path = self.src.join(ignore_path);

				if ignore_path.exists() {
					ignore.add_from_file(ignore_path)?;
				}
			}
		}

		let relative_paths = walkdir::WalkDir::new(&self.src)
			// dont return self.src again
			.min_depth(1)
			.contents_first(false)
			.follow_links(false)
			.sort_by_file_name()
			.into_iter()
			// filter out all the problem entries
			.filter_map(|x| x.ok())
			.filter_map(|x| {
				// convert to path relative to &self.src
				x.path()
					.strip_prefix(&self.src)
					.map(|x| x.to_path_buf())
					.ok()
			})
			.filter(|x| {
				// we add a / in front of the relative path
				// so we can use the leading / to match files
				// in the root of the overlay
				let absolute_path = Path::new("/").join(x);
				!ignore.matches(absolute_path.to_string_lossy())
			});

		for src_rel_path in relative_paths {
			let r = self.install_path(src_rel_path, profile, options);

			if options.no_abort {
				if let Err(e) = r {
					error!("{} {:#}", "[Silent]".dimmed().white(), e);
				}
			} else {
				r?
			}
		}

		Ok(())
	}

	fn install_path(
		&self,
		src_rel_path: PathBuf,
		profile: &dyn Profile,
		options: &Options,
	) -> Result<()> {
		let dst_rel_path = expand_path(&src_rel_path, profile)
			.with_context(|| {
				format!(
					"failed to expand path '{}'",
					src_rel_path.display()
				)
			})?;

		let src = self
			.src
			.join(src_rel_path)
			.canonicalize()
			.context("failed to resolve source path")?;
		let dst = self.dst.join(dst_rel_path);

		let src_metadata = src.metadata().with_context(|| {
			format!("failed to get metadata for '{}'", src.display())
		})?;

		if dst.exists() {
			let dst_metadata = dst.metadata().with_context(|| {
				format!(
					"failed to get metadata for '{}'",
					dst.display()
				)
			})?;

			if options.update {
				let now = std::time::SystemTime::now();

				let src_mtime =
					src_metadata.modified().unwrap_or(now);
				let dst_mtime =
					dst_metadata.modified().unwrap_or(now);

				if src_mtime < dst_mtime {
					warn!(
						"destination '{}' is newer than source '{}'",
						dst.display(),
						src.display(),
					);
					return Ok(());
				} else if src_mtime == dst_mtime {
					// dont do unnecessary operations
					return Ok(());
				}
			}

			if options.no_overwrite {
				warn!(
					"not overwriting existing path '{}'",
					dst.display()
				);
				return Ok(());
			}
		}

		if !options.dry_run {
			if src.is_dir() {
				platform::create_dir_all(&src, &dst, options)
					.with_context(|| {
						format!(
							"failed to create directory '{}'",
							dst.display()
						)
					})?;
			} else {
				if options.hard_link {
					platform::hard_link(&src, &dst, options)
						.with_context(|| {
							format!(
								"failed to hard link '{}' to '{}'",
								src.display(),
								dst.display()
							)
						})?
				} else {
					platform::copy(&src, &dst, options)
						.with_context(|| {
							format!(
								"failed to install '{}' to '{}'",
								src.display(),
								dst.display()
							)
						})?;
				}
			}
		}

		if options.machine_readable {
			println!("{} {}", src.display(), dst.display());
		} else {
			info!(target: "no_fmt", "{:>12} {} {} {}", "Installing".bold().bright_green(), src.display(), "to".bold().bright_cyan(), dst.display());
		}

		Ok(())
	}

	pub fn run_hooks(
		&mut self,
		hook_type: HookType,
		options: &Options,
	) -> Result<()> {
		if options.no_hooks {
			return Ok(());
		}

		// if it is empty, then run any hook type
		if !options.hook_types.is_empty()
			&& !options.hook_types.contains(&hook_type)
		{
			return Ok(());
		}

		let hook_dir = self
			.src
			.join(".turboinstall")
			.join(hook_type.hook_dir_name());

		if !hook_dir.exists() {
			return Ok(());
		}

		if !hook_dir.is_dir() {
			bail!(
				"hook directory '{}' is not a directory",
				hook_dir.display()
			)
		}

		// iteratively run hooks in alphanumerical order
		walkdir::WalkDir::new(hook_dir)
			.max_depth(1)
			.follow_links(true)
			.contents_first(true)
			.sort_by_file_name()
			.into_iter()
			.filter_map(|x| x.ok())
			.map(|x| x.into_path())
			.filter(|x| x.is_file())
			.try_for_each(move |hook_path| {
				use std::process::Command;

				info!(target: "no_fmt", "{:>12} {}", "Running".bold().bright_white(), hook_path.display());

				let status = match Command::new(&hook_path)
					.arg(&self.src)
					.arg(&self.dst)
					.status()
				{
					Ok(v) => v,
					Err(_) => {
						warn!(
							"could not run hook '{}'",
							hook_path.display()
						);
						return Ok(());
					},
				};

				if !status.success() {
					if let Some(code) = status.code() {
						bail!(
							"hook '{}' exited with code: {}",
							hook_path.display(),
							code
						)
					} else {
						bail!("hook '{}' failed", hook_path.display())
					}
				}

				Ok(())
			})?;

		Ok(())
	}
}

fn expand_vars(s: &str, profile: &dyn Profile) -> Result<String> {
	let mut ret = s.to_string();

	loop {
		let start = ret.find('{');
		let end = ret.find('}');

		if !(start.is_some() && end.is_some()) {
			break;
		}

		if end <= start {
			break;
		}

		let start = start.expect("the None should have been handled by the above if statements");
		let end = end.expect("the None should have been handled by the above if statements");

		let var_name = &ret[start.saturating_add(1)..end];

		if let Some(value) = profile.var(var_name) {
			if value.is_empty() {
				bail!("Found empty variable.")
			}

			ret = format!(
				"{}{}{}",
				&ret[..start],
				value,
				&ret[end.saturating_add(1)..]
			);
		} else {
			bail!("Variable '{}' not found in profile.", var_name)
		}
	}

	Ok(ret)
}

fn expand_path(
	p: impl AsRef<Path>,
	profile: &dyn Profile,
) -> Result<PathBuf> {
	let mut path = PathBuf::new();

	for component in p
		.as_ref()
		.components()
		.map(|x| x.as_os_str().to_string_lossy())
	{
		let expanded = expand_vars(&component, profile)?;

		let expanded =
			expanded.strip_prefix('/').unwrap_or(&expanded);

		path.push(expanded);
	}

	Ok(path)
}

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

	#[test]
	fn expand_vars_tests() {
		use std::collections::HashMap;

		impl Profile for HashMap<String, String> {
			fn var(&self, s: &str) -> Option<&str> {
				self.get(s).map(|x| x.as_str())
			}
		}

		let mut dummy_profile: HashMap<String, String> =
			HashMap::new();
		dummy_profile
			.insert("var1".to_string(), "variable 1".to_string());
		dummy_profile
			.insert("VAR2".to_string(), "VARIABLE 2".to_string());
		dummy_profile
			.insert("space var".to_string(), " spaced ".to_string());

		assert_eq!(
			expand_vars("..{var1}..", &dummy_profile).unwrap(),
			"..variable 1.."
		);

		assert_eq!(
			expand_vars("{var1}..", &dummy_profile).unwrap(),
			"variable 1.."
		);

		assert_eq!(
			expand_vars("..{var1}", &dummy_profile).unwrap(),
			"..variable 1"
		);

		assert_eq!(
			expand_vars("{VAR2}", &dummy_profile).unwrap(),
			"VARIABLE 2"
		);

		assert_eq!(
			expand_vars("..{space var}..", &dummy_profile).unwrap(),
			".. spaced .."
		);

		assert_eq!(
			expand_vars("{var1} {VAR2}", &dummy_profile).unwrap(),
			"variable 1 VARIABLE 2"
		);

		assert_eq!(
			expand_vars("}var1{", &dummy_profile).unwrap(),
			"}var1{"
		);

		assert!(expand_vars("{}{var1}{}", &dummy_profile).is_err());
		assert!(expand_vars("{}}var1{{}", &dummy_profile).is_err());
	}
}