1use serde::{Deserialize, Serialize};
5use std::fmt;
6use std::path::{Component, Path, PathBuf};
7
8#[macro_export]
9macro_rules! string_newtype {
10 ($(#[$meta:meta])* $name:ident) => {
11 $(#[$meta])*
12 #[derive(
13 ::serde::Serialize, ::serde::Deserialize, Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd,
14 )]
15 #[serde(transparent)]
16 pub struct $name(String);
17
18 impl $name {
19 pub fn as_str(&self) -> &str {
20 &self.0
21 }
22 }
23
24 impl From<String> for $name {
25 fn from(value: String) -> Self {
26 Self(value)
27 }
28 }
29
30 impl From<&str> for $name {
31 fn from(value: &str) -> Self {
32 Self(value.to_owned())
33 }
34 }
35
36 impl AsRef<str> for $name {
37 fn as_ref(&self) -> &str {
38 &self.0
39 }
40 }
41
42 impl ::std::borrow::Borrow<str> for $name {
43 fn borrow(&self) -> &str {
44 &self.0
45 }
46 }
47
48 impl ::std::ops::Deref for $name {
49 type Target = str;
50
51 fn deref(&self) -> &Self::Target {
52 &self.0
53 }
54 }
55
56 impl From<$name> for String {
57 fn from(value: $name) -> Self {
58 value.0
59 }
60 }
61
62 impl ::std::fmt::Display for $name {
63 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
64 f.write_str(&self.0)
65 }
66 }
67
68 impl PartialEq<str> for $name {
69 fn eq(&self, other: &str) -> bool {
70 self.0 == other
71 }
72 }
73
74 impl PartialEq<&str> for $name {
75 fn eq(&self, other: &&str) -> bool {
76 self.0 == *other
77 }
78 }
79
80 impl PartialEq<String> for $name {
81 fn eq(&self, other: &String) -> bool {
82 self.0 == *other
83 }
84 }
85
86 impl PartialEq<$name> for String {
87 fn eq(&self, other: &$name) -> bool {
88 *self == other.0
89 }
90 }
91 };
92}
93
94string_newtype!(
95 ItemName
97);
98
99string_newtype!(
100 SourceName
102);
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum RelativePathError {
107 Empty,
108 Absolute,
109 Escaping,
110}
111
112pub fn normalize_relative(raw: &str) -> Result<String, RelativePathError> {
116 if raw.is_empty() {
117 return Err(RelativePathError::Empty);
118 }
119 let normalized_separators = raw.replace('\\', "/");
120 if is_windows_absolute(&normalized_separators) {
121 return Err(RelativePathError::Absolute);
122 }
123
124 let mut segments = Vec::new();
125 for component in Path::new(&normalized_separators).components() {
126 match component {
127 Component::Normal(seg) => segments.push(seg.to_string_lossy().into_owned()),
128 Component::CurDir => {}
129 Component::ParentDir => return Err(RelativePathError::Escaping),
130 Component::RootDir | Component::Prefix(_) => return Err(RelativePathError::Absolute),
131 }
132 }
133
134 if segments.is_empty() {
135 return Err(RelativePathError::Empty);
136 }
137
138 Ok(segments.join("/"))
139}
140
141fn is_windows_absolute(path: &str) -> bool {
142 let bytes = path.as_bytes();
143 path.starts_with('/')
144 || (bytes.len() >= 3
145 && bytes[0].is_ascii_alphabetic()
146 && bytes[1] == b':'
147 && bytes[2] == b'/')
148}
149
150#[derive(Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
152pub struct SourceSubpath(String);
153
154impl SourceSubpath {
155 pub fn new(value: impl AsRef<str>) -> Result<Self, SourceSubpathError> {
156 let raw = value.as_ref();
157 let normalized = normalize_relative(raw).map_err(|err| match err {
158 RelativePathError::Empty => SourceSubpathError::Empty,
159 RelativePathError::Absolute => SourceSubpathError::Absolute {
160 input: raw.to_string(),
161 },
162 RelativePathError::Escaping => SourceSubpathError::Escaping {
163 input: raw.to_string(),
164 },
165 })?;
166
167 Ok(Self(normalized))
168 }
169
170 pub fn as_str(&self) -> &str {
171 &self.0
172 }
173
174 pub fn as_path(&self) -> &Path {
175 Path::new(&self.0)
176 }
177 pub fn join_under(&self, base: &Path) -> Result<PathBuf, SourceSubpathError> {
179 let mut joined = base.to_path_buf();
180 for component in self.as_path().components() {
181 match component {
182 Component::Normal(seg) => joined.push(seg),
183 Component::CurDir => {}
184 Component::ParentDir => {
185 return Err(SourceSubpathError::Escaping {
186 input: self.0.clone(),
187 });
188 }
189 Component::RootDir | Component::Prefix(_) => {
190 return Err(SourceSubpathError::Absolute {
191 input: self.0.clone(),
192 });
193 }
194 }
195 }
196
197 if joined.strip_prefix(base).is_err() {
198 return Err(SourceSubpathError::Escaping {
199 input: self.0.clone(),
200 });
201 }
202
203 Ok(joined)
204 }
205}
206
207impl fmt::Display for SourceSubpath {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 f.write_str(&self.0)
210 }
211}
212
213impl AsRef<str> for SourceSubpath {
214 fn as_ref(&self) -> &str {
215 self.as_str()
216 }
217}
218
219impl std::str::FromStr for SourceSubpath {
220 type Err = SourceSubpathError;
221
222 fn from_str(s: &str) -> Result<Self, Self::Err> {
223 Self::new(s)
224 }
225}
226
227impl Serialize for SourceSubpath {
228 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
229 self.0.serialize(serializer)
230 }
231}
232
233impl<'de> Deserialize<'de> for SourceSubpath {
234 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
235 let value = String::deserialize(deserializer)?;
236 SourceSubpath::new(value).map_err(serde::de::Error::custom)
237 }
238}
239
240#[derive(Debug, thiserror::Error, PartialEq, Eq)]
241pub enum SourceSubpathError {
242 #[error("subpath cannot be empty")]
243 Empty,
244 #[error("subpath must be relative, got absolute value: {input:?}")]
245 Absolute { input: String },
246 #[error("subpath cannot escape package root: {input:?}")]
247 Escaping { input: String },
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct RenameRule {
252 pub from: ItemName,
253 pub to: ItemName,
254}
255
256#[derive(Debug, Clone, Default, PartialEq, Eq)]
258pub struct RenameMap(Vec<RenameRule>);
259
260impl RenameMap {
261 pub fn new() -> Self {
262 Self(Vec::new())
263 }
264
265 pub fn insert(&mut self, from: ItemName, to: ItemName) {
266 if let Some(existing) = self.0.iter_mut().find(|r| r.from == from) {
267 existing.to = to;
268 return;
269 }
270 self.0.push(RenameRule { from, to });
271 }
272 pub fn get(&self, from: &str) -> Option<&ItemName> {
273 self.0.iter().find(|r| r.from == from).map(|r| &r.to)
274 }
275}
276
277impl Serialize for RenameMap {
278 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
279 use serde::ser::SerializeMap;
280 let mut map = serializer.serialize_map(Some(self.0.len()))?;
281 for rule in &self.0 {
282 map.serialize_entry(rule.from.as_str(), rule.to.as_str())?;
283 }
284 map.end()
285 }
286}
287
288impl<'de> Deserialize<'de> for RenameMap {
289 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
290 let map = indexmap::IndexMap::<String, String>::deserialize(deserializer)?;
291 Ok(Self(
292 map.into_iter()
293 .map(|(from, to)| RenameRule {
294 from: ItemName::from(from),
295 to: ItemName::from(to),
296 })
297 .collect(),
298 ))
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use std::path::PathBuf;
306
307 #[test]
308 fn source_subpath_normalizes_windows_and_unix_separators() {
309 let subpath = SourceSubpath::new(r"plugins\foo/bar\baz").unwrap();
310 assert_eq!(subpath.as_str(), "plugins/foo/bar/baz");
311 }
312
313 #[test]
314 fn source_subpath_rejects_empty() {
315 let err = SourceSubpath::new("").unwrap_err();
316 assert_eq!(err, SourceSubpathError::Empty);
317 }
318
319 #[test]
320 fn source_subpath_rejects_absolute() {
321 let err = SourceSubpath::new("/abs/path").unwrap_err();
322 assert!(matches!(err, SourceSubpathError::Absolute { .. }));
323 }
324
325 #[test]
326 fn source_subpath_rejects_root_only() {
327 let err = SourceSubpath::new("/").unwrap_err();
328 assert!(matches!(err, SourceSubpathError::Absolute { .. }));
329 }
330
331 #[test]
332 fn source_subpath_rejects_windows_absolute() {
333 let err = SourceSubpath::new(r"C:\abs\path").unwrap_err();
334 assert!(matches!(err, SourceSubpathError::Absolute { .. }));
335 }
336
337 #[test]
338 fn source_subpath_rejects_escape() {
339 let err = SourceSubpath::new("../escape").unwrap_err();
340 assert!(matches!(err, SourceSubpathError::Escaping { .. }));
341 }
342
343 #[test]
344 fn source_subpath_accepts_nested_relative_path() {
345 let subpath = SourceSubpath::new("a/b/c").unwrap();
346 assert_eq!(subpath.as_str(), "a/b/c");
347 }
348
349 #[test]
350 fn source_subpath_serializes_with_forward_slashes() {
351 #[derive(Debug, Serialize, Deserialize, PartialEq)]
352 struct SubpathWrapper {
353 subpath: SourceSubpath,
354 }
355
356 let wrapper = SubpathWrapper {
357 subpath: SourceSubpath::new(r"plugins\foo").unwrap(),
358 };
359 let toml = toml::to_string(&wrapper).unwrap();
360 assert!(toml.contains("subpath = \"plugins/foo\""));
361 }
362
363 #[test]
364 fn source_subpath_join_under_base() {
365 let base = PathBuf::from("/tmp/mars");
366 let subpath = SourceSubpath::new("plugins/foo").unwrap();
367 let joined = subpath.join_under(&base).unwrap();
368 assert_eq!(joined, base.join("plugins").join("foo"));
369 }
370
371 #[test]
372 fn source_subpath_join_under_rejects_escape_path() {
373 let escaped = SourceSubpath(String::from("../escape"));
374 let err = escaped.join_under(Path::new("/tmp/base")).unwrap_err();
375 assert!(matches!(err, SourceSubpathError::Escaping { .. }));
376 }
377
378 #[test]
379 fn source_subpath_rejects_windows_drive_forward_slash() {
380 let err = SourceSubpath::new("C:/foo").unwrap_err();
381 assert!(matches!(err, SourceSubpathError::Absolute { .. }));
382 }
383
384 #[test]
385 fn source_subpath_rejects_current_dir_dot() {
386 let err = SourceSubpath::new(".").unwrap_err();
387 assert_eq!(err, SourceSubpathError::Empty);
388 }
389
390 #[test]
391 fn source_subpath_rejects_mid_path_double_parent_escape() {
392 let err = SourceSubpath::new("a/../../escape").unwrap_err();
393 assert!(matches!(err, SourceSubpathError::Escaping { .. }));
394 }
395
396 #[test]
397 fn source_subpath_rejects_harmless_parent_in_middle() {
398 let err = SourceSubpath::new("a/b/../c").unwrap_err();
399 assert!(matches!(err, SourceSubpathError::Escaping { .. }));
400 }
401
402 #[test]
403 fn source_subpath_normalizes_trailing_slash() {
404 let subpath = SourceSubpath::new("plugins/foo/").unwrap();
405 assert_eq!(subpath.as_str(), "plugins/foo");
406 }
407
408 #[test]
409 fn source_subpath_normalizes_leading_dot_slash() {
410 let subpath = SourceSubpath::new("./plugins/foo").unwrap();
411 assert_eq!(subpath.as_str(), "plugins/foo");
412 }
413
414 #[test]
415 fn rename_map_toml_roundtrip_compat() {
416 #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
417 struct RenameWrapper {
418 rename: RenameMap,
419 }
420
421 let input = r#"rename = { "coder" = "cool-coder" }"#;
422 let parsed: RenameWrapper = toml::from_str(input).unwrap();
423 assert_eq!(
424 parsed.rename.get("coder").map(|v| v.as_str()),
425 Some("cool-coder")
426 );
427
428 let serialized = toml::to_string(&parsed).unwrap();
429 let reparsed: RenameWrapper = toml::from_str(&serialized).unwrap();
430 assert_eq!(parsed, reparsed);
431 }
432}