Skip to main content

workyard_core/
paths.rs

1use crate::{Problem, ProblemCode};
2
3/// Check that a branch-shaped task name is safe to use beneath the tasks root.
4pub fn validate_task(task: &str) -> Result<(), Problem> {
5	if task.is_empty() || task.starts_with('-') || task.split('/').any(|part| !safe_component(part))
6	{
7		return Err(Problem::new(
8			ProblemCode::InvalidTask,
9			"Task must be a safe relative branch path.",
10		));
11	}
12
13	Ok(())
14}
15
16/// Check whether a name is safe as one directory component on the current platform.
17pub fn safe_component(name: &str) -> bool {
18	if name.is_empty()
19		|| name == "."
20		|| name == ".."
21		|| name.chars().any(|c| c.is_control() || "/\\".contains(c))
22	{
23		return false;
24	}
25
26	#[cfg(windows)]
27	{
28		if name.ends_with('.')
29			|| name.ends_with(' ')
30			|| name.contains([':', '*', '?', '"', '<', '>', '|'])
31		{
32			return false;
33		}
34
35		let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
36		let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL");
37		let numbered_device = ["COM", "LPT"].iter().any(|prefix| {
38			stem.strip_prefix(prefix).is_some_and(|suffix| {
39				matches!(
40					suffix,
41					"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
42				)
43			})
44		});
45		if device || numbered_device {
46			return false;
47		}
48	}
49
50	true
51}
52
53/// Test whether either path contains the other or both denote the same path.
54pub fn overlaps(left: &std::path::Path, right: &std::path::Path) -> bool {
55	left.starts_with(right) || right.starts_with(left)
56}