about summary refs log tree commit diff
path: root/wikarden/src/fs/path.rs
blob: 50cb3e2a80603737a0539b6915ba06ce36f69c6e (plain)
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
use std::{fmt, ops::Deref, str::FromStr};

use camino::{Utf8Path, Utf8PathBuf};

use crate::WikError;

#[derive(Clone, Debug, PartialEq)]
pub struct WikName {
	name: String,
}

impl WikName {
	/// Returns a new [WikName] without checking if it is valid
	pub fn new_unchecked(name: String) -> Self {
		Self { name }
	}

	pub fn as_path(&self) -> WikPath {
		self.into()
	}
}

#[derive(Clone, Debug, PartialEq)]
pub struct WikPath {
	name: String,
}

impl WikPath {
	pub fn join(&self, name: &WikName) -> Self {
		Self {
			name: format!("{}/{name}", self.name),
		}
	}

	pub fn name(&self) -> WikName {
		let (_, name) = self.as_parts();
		name
	}

	pub fn parent(&self) -> Option<WikPath> {
		self.name.rsplit_once('/').map(|(parent, _)| parent.into())
	}

	pub fn as_parts(&self) -> (Option<WikPath>, WikName) {
		match self.name.rsplit_once('/') {
			None => (None, WikName::new_unchecked(self.name.clone())),
			Some((section, name)) => (
				Some(section.into()),
				WikName::new_unchecked(name.to_owned()),
			),
		}
	}
}

impl<T> From<T> for WikPath
where
	T: Into<String>,
{
	fn from(value: T) -> Self {
		Self { name: value.into() }
	}
}

impl From<&WikName> for WikPath {
	fn from(name: &WikName) -> Self {
		WikPath {
			name: name.name.to_owned(),
		}
	}
}

impl FromStr for WikName {
	type Err = WikError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		if s.contains('/') {
			Err(WikError::name_has_slashes(s))
		} else {
			Ok(Self { name: s.to_owned() })
		}
	}
}

impl AsRef<str> for WikPath {
	fn as_ref(&self) -> &str {
		&self.name
	}
}

impl AsRef<str> for WikName {
	fn as_ref(&self) -> &str {
		&self.name
	}
}

impl fmt::Display for WikPath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.name)
	}
}

impl fmt::Display for WikName {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.name)
	}
}

#[derive(Clone, Debug, PartialEq)]
pub struct SafePath(pub Utf8PathBuf);

impl Deref for SafePath {
	type Target = Utf8Path;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl AsRef<std::path::Path> for SafePath {
	fn as_ref(&self) -> &std::path::Path {
		self.0.as_std_path()
	}
}

impl fmt::Display for SafePath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.0)
	}
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum EitherPath {
	Wik(WikPath),
	Safe(SafePath),
}

impl EitherPath {
	/// Use when the file does not exist yet, but other components are expected to exist.
	pub fn safe_nonexist(root: &Utf8Path, wik: &WikPath) -> Result<SafePath, WikError> {
		let mut joined = root.join(&wik.name);
		let name = joined.file_name().map(<_>::to_owned);

		if !joined.pop() || name.is_none() {
			return Err(WikError::canonicalization_failed(joined));
		}
		let name = name.unwrap();

		let canon = joined
			.canonicalize_utf8()
			.map_err(|_| WikError::canonicalization_failed(joined))?;

		let path = canon.join(name);
		if !Self::check_fs_path(&path, root) {
			Err(WikError::illegal_path(wik.clone(), path))
		} else {
			Ok(SafePath(path))
		}
	}

	pub fn safe(self, root: &Utf8Path) -> Result<SafePath, WikError> {
		self.as_safe(root)
	}

	fn resolve_path(wik: &WikPath, root: &Utf8Path) -> Result<SafePath, WikError> {
		let fs_path = root.join(&wik.name);
		let fs_canon = fs_path
			.canonicalize_utf8()
			.map_err(|_| WikError::CanonicalizationFailed { path: fs_path })?;

		if !Self::check_fs_path(&fs_canon, root) {
			Err(WikError::illegal_path(wik.clone(), fs_canon))
		} else {
			Ok(SafePath(fs_canon))
		}
	}

	/// Returns `true` if the path is above the root, `false` otherwise
	fn check_fs_path(path: &Utf8Path, root: &Utf8Path) -> bool {
		path.starts_with(root)
	}

	fn as_safe(&self, root: &Utf8Path) -> Result<SafePath, WikError> {
		match self {
			Self::Wik(wik) => Self::resolve_path(wik, root),
			Self::Safe(safe) => Ok(safe.clone()),
		}
	}
}

impl From<WikPath> for EitherPath {
	fn from(value: WikPath) -> Self {
		Self::Wik(value)
	}
}

impl From<SafePath> for EitherPath {
	fn from(value: SafePath) -> Self {
		Self::Safe(value)
	}
}