1use std::borrow::Borrow;
11use std::fmt;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
19#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
20#[serde(transparent)]
21pub struct Name(String);
22
23impl Name {
24 pub fn new(text: impl Into<String>) -> Self {
25 Self(text.into())
26 }
27
28 pub fn as_str(&self) -> &str {
29 &self.0
30 }
31
32 pub fn as_path(&self) -> &Path {
34 Path::new(&self.0)
35 }
36}
37
38impl Deref for Name {
39 type Target = str;
40 fn deref(&self) -> &str {
41 &self.0
42 }
43}
44
45impl Borrow<str> for Name {
46 fn borrow(&self) -> &str {
47 &self.0
48 }
49}
50
51impl AsRef<str> for Name {
52 fn as_ref(&self) -> &str {
53 &self.0
54 }
55}
56
57impl PartialEq<str> for Name {
58 fn eq(&self, other: &str) -> bool {
59 self.0 == other
60 }
61}
62
63impl PartialEq<&str> for Name {
64 fn eq(&self, other: &&str) -> bool {
65 self.0 == *other
66 }
67}
68
69impl PartialEq<String> for Name {
70 fn eq(&self, other: &String) -> bool {
71 &self.0 == other
72 }
73}
74
75impl From<&str> for Name {
76 fn from(text: &str) -> Self {
77 Self::new(text)
78 }
79}
80
81impl From<String> for Name {
82 fn from(text: String) -> Self {
83 Self(text)
84 }
85}
86
87impl From<&String> for Name {
88 fn from(text: &String) -> Self {
89 Self(text.clone())
90 }
91}
92
93impl From<Name> for String {
94 fn from(name: Name) -> Self {
95 name.0
96 }
97}
98
99impl fmt::Display for Name {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str(&self.0)
102 }
103}
104
105impl fmt::Debug for Name {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 write!(f, "{:?}", self.0)
108 }
109}
110
111#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
122#[serde(transparent)]
123pub struct RelPath(String);
124
125impl RelPath {
126 pub fn new(path: &Path) -> Self {
130 Self::from(path.display().to_string())
131 }
132
133 pub fn as_str(&self) -> &str {
134 &self.0
135 }
136
137 pub fn as_path(&self) -> &Path {
139 Path::new(&self.0)
140 }
141
142 pub fn short(&self) -> String {
145 let parts: Vec<String> = self
146 .as_path()
147 .components()
148 .map(|c| c.as_os_str().to_string_lossy().into_owned())
149 .collect();
150 let n = parts.len();
151 parts[n.saturating_sub(2)..].join("/")
152 }
153
154 fn separators(text: String) -> String {
156 if std::path::MAIN_SEPARATOR == '/' {
157 text
158 } else {
159 text.replace(std::path::MAIN_SEPARATOR, "/")
160 }
161 }
162}
163
164impl Deref for RelPath {
165 type Target = Path;
166 fn deref(&self) -> &Path {
167 Path::new(&self.0)
168 }
169}
170
171impl AsRef<Path> for RelPath {
172 fn as_ref(&self) -> &Path {
173 self
174 }
175}
176
177impl AsRef<str> for RelPath {
178 fn as_ref(&self) -> &str {
179 &self.0
180 }
181}
182
183impl Borrow<Path> for RelPath {
184 fn borrow(&self) -> &Path {
185 self
186 }
187}
188
189impl PartialEq<Path> for RelPath {
190 fn eq(&self, other: &Path) -> bool {
191 self.as_path() == other
192 }
193}
194
195impl PartialEq<&Path> for RelPath {
196 fn eq(&self, other: &&Path) -> bool {
197 self.as_path() == *other
198 }
199}
200
201impl PartialEq<RelPath> for Path {
202 fn eq(&self, other: &RelPath) -> bool {
203 self == other.as_path()
204 }
205}
206
207impl PartialEq<PathBuf> for RelPath {
208 fn eq(&self, other: &PathBuf) -> bool {
209 self.as_path() == other.as_path()
210 }
211}
212
213impl PartialEq<RelPath> for PathBuf {
214 fn eq(&self, other: &RelPath) -> bool {
215 self.as_path() == other.as_path()
216 }
217}
218
219impl PartialEq<str> for RelPath {
220 fn eq(&self, other: &str) -> bool {
221 self.0 == other
222 }
223}
224
225impl PartialEq<&str> for RelPath {
226 fn eq(&self, other: &&str) -> bool {
227 self.0 == *other
228 }
229}
230
231impl From<&RelPath> for RelPath {
232 fn from(path: &RelPath) -> Self {
233 path.clone()
234 }
235}
236
237impl From<&str> for RelPath {
238 fn from(path: &str) -> Self {
239 Self::from(path.to_owned())
240 }
241}
242
243impl From<String> for RelPath {
244 fn from(path: String) -> Self {
245 Self(RelPath::separators(path))
246 }
247}
248
249impl<'de> Deserialize<'de> for RelPath {
250 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
251 String::deserialize(deserializer).map(Self::from)
252 }
253}
254
255impl From<&Path> for RelPath {
256 fn from(path: &Path) -> Self {
257 Self::new(path)
258 }
259}
260
261impl From<PathBuf> for RelPath {
262 fn from(path: PathBuf) -> Self {
263 Self::new(&path)
264 }
265}
266
267impl From<&PathBuf> for RelPath {
268 fn from(path: &PathBuf) -> Self {
269 Self::new(path)
270 }
271}
272
273impl From<&RelPath> for PathBuf {
274 fn from(path: &RelPath) -> Self {
275 PathBuf::from(&path.0)
276 }
277}
278
279impl fmt::Display for RelPath {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 f.write_str(&self.0)
282 }
283}
284
285impl fmt::Debug for RelPath {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 write!(f, "{:?}", self.0)
288 }
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
294#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
295#[serde(rename_all = "snake_case")]
296pub enum PathHead {
297 Package,
299 Here,
301 Up(u8),
304 SelfType,
306 Named,
310 Root,
312}
313
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
318#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
319#[serde(rename_all = "snake_case")]
320pub enum PathSyntax {
321 Scoped,
323 Posix,
325}
326
327impl PathSyntax {
328 pub const fn separator(self) -> &'static str {
329 match self {
330 Self::Scoped => "::",
331 Self::Posix => "/",
332 }
333 }
334
335 pub fn parse(self, text: &str) -> ModulePath {
338 let mut segments: Vec<&str> = text.split(self.separator()).collect();
339 let head = match self {
340 Self::Scoped => match segments.first().copied() {
341 Some("") if segments.len() > 1 => {
342 segments.remove(0);
343 PathHead::Root
344 }
345 Some("crate") => {
346 segments.remove(0);
347 PathHead::Package
348 }
349 Some("self") => {
350 segments.remove(0);
351 PathHead::Here
352 }
353 Some("Self") => {
354 segments.remove(0);
355 PathHead::SelfType
356 }
357 Some("super") => {
358 let ups = segments.iter().take_while(|s| **s == "super").count();
359 segments.drain(..ups);
360 PathHead::Up(ups as u8)
361 }
362 _ => PathHead::Named,
363 },
364 Self::Posix => match segments.first().copied() {
365 Some("") if segments.len() > 1 => {
366 segments.remove(0);
367 PathHead::Root
368 }
369 Some(".") => {
370 segments.remove(0);
371 PathHead::Here
372 }
373 Some("..") => {
374 let ups = segments.iter().take_while(|s| **s == "..").count();
375 segments.drain(..ups);
376 PathHead::Up(ups as u8)
377 }
378 Some(scope) if scope.starts_with('@') && segments.len() > 1 => {
380 let package = format!("{scope}/{}", segments[1]);
381 segments.drain(..2);
382 segments.insert(0, "");
383 let mut path = ModulePath {
384 syntax: self,
385 head: PathHead::Named,
386 segments: segments.iter().map(|s| Name::new(*s)).collect(),
387 };
388 path.segments[0] = Name::new(package);
389 return path;
390 }
391 _ => PathHead::Named,
392 },
393 };
394 ModulePath {
395 syntax: self,
396 head,
397 segments: segments
398 .into_iter()
399 .filter(|s| !s.is_empty())
400 .map(Name::new)
401 .collect(),
402 }
403 }
404
405 pub fn spell(self, path: &ModulePath) -> String {
407 let sep = self.separator();
408 let segments = path
409 .segments
410 .iter()
411 .map(Name::as_str)
412 .collect::<Vec<_>>()
413 .join(sep);
414 match (self, &path.head) {
415 (Self::Scoped, PathHead::Package) => Self::joined("crate", sep, &segments),
416 (Self::Scoped, PathHead::Here) => Self::joined("self", sep, &segments),
417 (Self::Scoped, PathHead::SelfType) => Self::joined("Self", sep, &segments),
418 (Self::Scoped, PathHead::Up(n)) => {
419 let ups = vec!["super"; *n as usize].join(sep);
420 Self::joined(&ups, sep, &segments)
421 }
422 (Self::Scoped, PathHead::Named) => segments,
423 (Self::Scoped, PathHead::Root) => format!("::{segments}"),
424 (Self::Posix, PathHead::Here) => Self::joined(".", sep, &segments),
425 (Self::Posix, PathHead::Up(n)) => {
426 let ups = vec![".."; *n as usize].join(sep);
427 Self::joined(&ups, sep, &segments)
428 }
429 (Self::Posix, PathHead::Root) => format!("/{segments}"),
430 (Self::Posix, PathHead::Package | PathHead::SelfType | PathHead::Named) => segments,
431 }
432 }
433
434 fn joined(head: &str, sep: &str, segments: &str) -> String {
435 if segments.is_empty() {
436 head.to_owned()
437 } else {
438 format!("{head}{sep}{segments}")
439 }
440 }
441}
442
443#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
447#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
448#[cfg_attr(feature = "schema", schemars(with = "String"))]
449pub struct ModulePath {
450 syntax: PathSyntax,
451 pub head: PathHead,
452 pub segments: Vec<Name>,
453}
454
455impl ModulePath {
456 pub fn new(
457 syntax: PathSyntax,
458 head: PathHead,
459 segments: impl IntoIterator<Item = impl Into<Name>>,
460 ) -> Self {
461 Self {
462 syntax,
463 head,
464 segments: segments.into_iter().map(Into::into).collect(),
465 }
466 }
467
468 pub fn syntax(&self) -> PathSyntax {
469 self.syntax
470 }
471
472 pub fn first(&self) -> Option<&Name> {
473 self.segments.first()
474 }
475
476 pub fn last(&self) -> Option<&Name> {
477 self.segments.last()
478 }
479
480 pub fn is_empty(&self) -> bool {
481 self.segments.is_empty()
482 }
483
484 pub fn strip_prefix(&self, prefix: &ModulePath) -> Option<&[Name]> {
487 (self.head == prefix.head)
488 .then(|| self.segments.strip_prefix(prefix.segments.as_slice()))
489 .flatten()
490 }
491
492 pub fn continues(&self, prefix: &ModulePath) -> bool {
494 self.strip_prefix(prefix)
495 .is_some_and(|rest| !rest.is_empty())
496 }
497
498 pub fn with_segments(&self, segments: impl IntoIterator<Item = impl Into<Name>>) -> Self {
500 Self::new(self.syntax, self.head.clone(), segments)
501 }
502
503 pub fn prefix(&self, index: usize) -> Self {
506 self.with_segments(self.segments[..=index].iter().cloned())
507 }
508
509 pub fn segment_at(&self, offset: usize) -> Option<usize> {
512 let sep = self.syntax.separator().len();
513 let head = self
514 .syntax
515 .spell(&self.with_segments(std::iter::empty::<Name>()));
516 let mut at = match (&self.head, head.len()) {
517 (PathHead::Root, n) => n,
518 (_, 0) => 0,
519 (_, n) => n + sep,
520 };
521 for (i, segment) in self.segments.iter().enumerate() {
522 if (at..at + segment.len()).contains(&offset) {
523 return Some(i);
524 }
525 at += segment.len() + sep;
526 }
527 None
528 }
529
530 pub fn spell_segments(&self, segments: &[Name]) -> String {
533 segments
534 .iter()
535 .map(Name::as_str)
536 .collect::<Vec<_>>()
537 .join(self.syntax.separator())
538 }
539}
540
541impl fmt::Display for ModulePath {
542 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543 f.write_str(&self.syntax.spell(self))
544 }
545}
546
547impl fmt::Debug for ModulePath {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 write!(f, "ModulePath({:?})", self.to_string())
550 }
551}
552
553impl Serialize for ModulePath {
554 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
555 serializer.serialize_str(&self.to_string())
556 }
557}
558
559impl<'de> Deserialize<'de> for ModulePath {
562 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
563 let text = String::deserialize(deserializer)?;
564 let syntax = if text.contains("::") {
565 PathSyntax::Scoped
566 } else {
567 PathSyntax::Posix
568 };
569 Ok(syntax.parse(&text))
570 }
571}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576
577 fn round_trip(syntax: PathSyntax, text: &str) -> ModulePath {
578 let path = syntax.parse(text);
579 assert_eq!(syntax.spell(&path), text, "{path:?}");
580 path
581 }
582
583 #[test]
584 fn scoped_absolute_paths_preserve_their_root_through_the_wire() {
585 let path = PathSyntax::Scoped.parse("::dependency::LIMIT");
586 assert_eq!(path.head, PathHead::Root);
587 assert_eq!(PathSyntax::Scoped.spell(&path), "::dependency::LIMIT");
588 let encoded = serde_json::to_string(&path).unwrap();
589 let decoded: ModulePath = serde_json::from_str(&encoded).unwrap();
590 assert_eq!(decoded, path);
591 }
592
593 #[test]
594 fn scoped_paths_parse_and_spell_losslessly() {
595 assert_eq!(
596 round_trip(PathSyntax::Scoped, "crate::a::b").head,
597 PathHead::Package
598 );
599 assert_eq!(
600 round_trip(PathSyntax::Scoped, "self::a").head,
601 PathHead::Here
602 );
603 assert_eq!(
604 round_trip(PathSyntax::Scoped, "super::super::x").head,
605 PathHead::Up(2)
606 );
607 assert_eq!(round_trip(PathSyntax::Scoped, "super").segments.len(), 0);
608 assert_eq!(
609 round_trip(PathSyntax::Scoped, "Self::X").head,
610 PathHead::SelfType
611 );
612 let named = round_trip(PathSyntax::Scoped, "serde::Serialize");
613 assert_eq!(named.head, PathHead::Named);
614 assert_eq!(named.first().map(Name::as_str), Some("serde"));
615 assert_eq!(round_trip(PathSyntax::Scoped, "Foo").segments.len(), 1);
616 }
617
618 #[test]
619 fn workspace_path_wire_round_trip_uses_the_constructor_policy() {
620 let native = PathBuf::from("src").join("café").join("lib.rs");
621 let native_text = native.to_str().unwrap();
622 let wire = serde_json::to_string(native_text).unwrap();
623 let decoded: RelPath = serde_json::from_str(&wire).unwrap();
624 assert_eq!(decoded, RelPath::new(&native));
625 assert_eq!(decoded.as_str(), "src/café/lib.rs");
626 assert_eq!(decoded.as_path(), native.as_path());
627 assert_eq!(
628 serde_json::to_string(&decoded).unwrap(),
629 serde_json::to_string("src/café/lib.rs").unwrap()
630 );
631 let again: RelPath =
632 serde_json::from_str(&serde_json::to_string(&decoded).unwrap()).unwrap();
633 assert_eq!(again, decoded);
634 }
635
636 #[cfg(windows)]
637 #[test]
638 fn workspace_paths_normalize_mixed_windows_separators_on_input() {
639 let text = r"src\nested/café\lib.rs";
640 let decoded: RelPath = serde_json::from_str(&serde_json::to_string(text).unwrap()).unwrap();
641 assert_eq!(decoded, RelPath::from(text));
642 assert_eq!(decoded.as_str(), "src/nested/café/lib.rs");
643 assert_eq!(decoded.short(), "café/lib.rs");
644 }
645
646 #[cfg(unix)]
647 #[test]
648 fn workspace_paths_preserve_literal_backslashes_in_unix_filenames() {
649 let native = Path::new(r"src/name\part.rs");
650 let decoded: RelPath =
651 serde_json::from_str(&serde_json::to_string(native.to_str().unwrap()).unwrap())
652 .unwrap();
653 assert_eq!(decoded, RelPath::new(native));
654 assert_eq!(decoded.as_path(), native);
655 assert_eq!(decoded.as_str(), r"src/name\part.rs");
656 assert_eq!(decoded.short(), r"src/name\part.rs");
657 }
658
659 #[test]
660 fn posix_paths_parse_and_spell_losslessly() {
661 assert_eq!(round_trip(PathSyntax::Posix, "./x.js").head, PathHead::Here);
662 assert_eq!(round_trip(PathSyntax::Posix, ".").segments.len(), 0);
663 assert_eq!(
664 round_trip(PathSyntax::Posix, "../../a/b").head,
665 PathHead::Up(2)
666 );
667 assert_eq!(round_trip(PathSyntax::Posix, "../..").head, PathHead::Up(2));
668 assert_eq!(round_trip(PathSyntax::Posix, "/etc/x").head, PathHead::Root);
669 let scoped = round_trip(PathSyntax::Posix, "@scope/pkg/sub");
670 assert_eq!(scoped.first().map(Name::as_str), Some("@scope/pkg"));
671 assert_eq!(scoped.segments.len(), 2);
672 assert_eq!(
673 round_trip(PathSyntax::Posix, "react/jsx-runtime").head,
674 PathHead::Named
675 );
676 }
677
678 #[test]
679 fn prefixes_compare_by_head_and_segments() {
680 let group = PathSyntax::Scoped.parse("crate::util");
681 let entry = PathSyntax::Scoped.parse("crate::util::parse::X");
682 assert_eq!(
683 entry.strip_prefix(&group).map(|r| entry.spell_segments(r)),
684 Some("parse::X".to_owned())
685 );
686 assert!(!PathSyntax::Scoped.parse("crate::util").continues(&group));
687 assert!(
688 PathSyntax::Scoped
689 .parse("self::util::x")
690 .strip_prefix(&group)
691 .is_none()
692 );
693 }
694
695 #[test]
696 fn segments_are_found_by_offset() {
697 let path = PathSyntax::Scoped.parse("crate::commands::batch::BatchCmd");
698 assert_eq!(path.segment_at(0), None, "the head");
699 assert_eq!(path.segment_at(7), Some(0));
700 assert_eq!(path.segment_at(17), Some(1));
701 assert_eq!(path.segment_at(24), Some(2));
702 assert_eq!(path.segment_at(15), None, "a separator");
703 assert_eq!(path.prefix(1).to_string(), "crate::commands::batch");
704 let bare = PathSyntax::Scoped.parse("a::b");
705 assert_eq!(bare.segment_at(0), Some(0));
706 assert_eq!(bare.segment_at(3), Some(1));
707 let posix = PathSyntax::Posix.parse("../x/y.ts");
708 assert_eq!(posix.segment_at(3), Some(0));
709 assert_eq!(posix.segment_at(5), Some(1));
710 assert_eq!(PathSyntax::Posix.parse("/etc/x").segment_at(1), Some(0));
711 }
712
713 #[test]
714 fn serialises_as_text() {
715 let path = PathSyntax::Scoped.parse("crate::a");
716 assert_eq!(serde_json::to_string(&path).unwrap(), "\"crate::a\"");
717 let back: ModulePath = serde_json::from_str("\"../x/y\"").unwrap();
718 assert_eq!(back, PathSyntax::Posix.parse("../x/y"));
719 }
720}