Skip to main content

litcheck_core/diagnostics/
filename.rs

1use std::{borrow::Cow, fmt, path::Path, sync::Arc};
2
3use crate::{StaticCow, diagnostics::SourceLanguage};
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6pub enum FileName {
7    Stdin,
8    Path(Arc<Path>),
9    Virtual(StaticCow<str>),
10}
11
12impl FileName {
13    pub fn from_static_str(name: &'static str) -> Self {
14        Self::Virtual(Cow::Borrowed(name))
15    }
16
17    pub fn as_str(&self) -> &str {
18        match self {
19            Self::Stdin => "stdin",
20            Self::Path(path) => path.to_str().unwrap_or("<invalid>"),
21            Self::Virtual(name) => name.as_ref(),
22        }
23    }
24
25    pub fn language(&self) -> SourceLanguage {
26        let extension = match self {
27            Self::Path(path) => path.extension().and_then(|ext| ext.to_str()).unwrap_or(""),
28            Self::Stdin | Self::Virtual(_) => "",
29        };
30        SourceLanguage::from_extension(extension)
31    }
32}
33
34impl PartialOrd for FileName {
35    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
36        Some(self.cmp(other))
37    }
38}
39
40impl Ord for FileName {
41    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
42        self.as_str().cmp(other.as_str())
43    }
44}
45
46impl From<&Path> for FileName {
47    fn from(path: &Path) -> Self {
48        if path.as_os_str() == "-" {
49            Self::Stdin
50        } else {
51            Self::Path(path.to_path_buf().into_boxed_path().into())
52        }
53    }
54}
55
56impl From<Box<Path>> for FileName {
57    fn from(path: Box<Path>) -> Self {
58        if path.as_os_str() == "-" {
59            Self::Stdin
60        } else {
61            Self::Path(path.into())
62        }
63    }
64}
65
66impl From<std::path::PathBuf> for FileName {
67    fn from(path: std::path::PathBuf) -> Self {
68        path.into_boxed_path().into()
69    }
70}
71
72impl From<&str> for FileName {
73    fn from(name: &str) -> Self {
74        if name == "-" {
75            Self::Stdin
76        } else {
77            Self::Virtual(Cow::Owned(name.to_string()))
78        }
79    }
80}
81
82impl From<String> for FileName {
83    fn from(name: String) -> Self {
84        if name == "-" {
85            Self::Stdin
86        } else {
87            Self::Virtual(Cow::Owned(name))
88        }
89    }
90}
91
92impl fmt::Display for FileName {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        match self {
95            Self::Stdin => f.write_str("stdin"),
96            Self::Path(path) => write!(f, "{}", path.display()),
97            Self::Virtual(name) => f.write_str(name),
98        }
99    }
100}