Skip to main content

artifactize_tools/scope/
target.rs

1//! A target is a filesystem path or an opaque, validated Live address; never both.
2use super::{LogicalPath, ScopeError};
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use std::{
5    borrow::Cow,
6    ffi::{OsStr, OsString},
7    fmt,
8    path::{Path, PathBuf},
9};
10
11// The declaration grammar distinguishes a URI by at least two scheme letters.
12const MIN_SCHEME_BYTES: usize = 2;
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
14pub struct Uri(String);
15impl Uri {
16    pub fn has_scheme(value: &str) -> bool {
17        value.split_once(':').is_some_and(|(scheme, _)| {
18            scheme.len() >= MIN_SCHEME_BYTES
19                && scheme.bytes().all(|byte| byte.is_ascii_alphabetic())
20        })
21    }
22    pub fn as_str(&self) -> &str {
23        &self.0
24    }
25}
26impl std::str::FromStr for Uri {
27    type Err = ScopeError;
28    fn from_str(value: &str) -> Result<Self, Self::Err> {
29        if !Self::has_scheme(value)
30            || value.chars().any(|character| {
31                character.is_control() || character.is_whitespace() || character == '\\'
32            })
33        {
34            return Err(ScopeError("A Live URI needs a scheme of at least two letters and no whitespace, controls or backslashes.".into()));
35        }
36        Ok(Self(value.into()))
37    }
38}
39impl fmt::Display for Uri {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        formatter.write_str(&self.0)
42    }
43}
44impl Serialize for Uri {
45    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
46        serializer.serialize_str(&self.0)
47    }
48}
49impl<'de> Deserialize<'de> for Uri {
50    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
51        String::deserialize(deserializer)?
52            .parse()
53            .map_err(serde::de::Error::custom)
54    }
55}
56
57/// A project-relative native path with verified logical entry names. Retain the names so
58/// scoped opens can walk pinned directories without reparsing the trusted owner target.
59#[derive(Debug, Clone)]
60pub struct LocalTarget {
61    path: PathBuf,
62    names: Vec<OsString>,
63}
64
65impl TryFrom<PathBuf> for LocalTarget {
66    type Error = ScopeError;
67
68    fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
69        let names = crate::files::relative_names(&path)
70            .map_err(|error| ScopeError(error.to_string()))?
71            .into_iter()
72            .map(OsStr::to_owned)
73            .collect();
74        Ok(Self { path, names })
75    }
76}
77
78/// A local target with at least one entry name. The project root cannot be a file target.
79#[derive(Debug, Clone)]
80pub struct FileTarget(LocalTarget);
81
82/// Kind and local selection travel with the target, so a Live URI cannot be a folder.
83#[derive(Debug, Clone)]
84pub enum Target {
85    Folder(LocalTarget),
86    File(FileTarget),
87    Aspect {
88        path: LocalTarget,
89        select: Vec<LogicalPath>,
90    },
91    /// Historical saved graphs and the migration reader only.
92    Graph(LocalTarget),
93    Live(Uri),
94}
95impl Target {
96    pub fn kind(&self) -> super::ArtifactKind {
97        use super::ArtifactKind;
98        match self {
99            Self::Folder(_) => ArtifactKind::Folder,
100            Self::File(_) => ArtifactKind::File,
101            Self::Aspect { .. } => ArtifactKind::Aspect,
102            Self::Graph(_) => ArtifactKind::Graph,
103            Self::Live(_) => ArtifactKind::Live,
104        }
105    }
106    pub fn local(&self) -> Option<&Path> {
107        self.local_target().map(|local| local.path.as_path())
108    }
109    fn local_target(&self) -> Option<&LocalTarget> {
110        match self {
111            Self::Folder(path) | Self::Graph(path) | Self::Aspect { path, .. } => Some(path),
112            Self::File(path) => Some(&path.0),
113            Self::Live(_) => None,
114        }
115    }
116    pub fn uri(&self) -> Option<&Uri> {
117        match self {
118            Self::Live(uri) => Some(uri),
119            _ => None,
120        }
121    }
122    pub fn select(&self) -> &[LogicalPath] {
123        match self {
124            Self::Aspect { select, .. } => select,
125            _ => &[],
126        }
127    }
128    pub fn folder(&self) -> &Path {
129        match self {
130            Self::Folder(local) | Self::Graph(local) | Self::Aspect { path: local, .. } => {
131                &local.path
132            }
133            Self::File(file) => crate::files::parent(&file.0.path).expect("file has a parent"),
134            Self::Live(_) => Path::new(""),
135        }
136    }
137    pub(super) fn folder_names(&self) -> Option<&[OsString]> {
138        match self {
139            Self::File(file) => Some(file.0.names.split_last().expect("file has a name").1),
140            _ => self.local_target().map(|local| local.names.as_slice()),
141        }
142    }
143    pub(super) fn file_name(&self) -> Option<&str> {
144        match self {
145            Self::File(file) => Some(
146                file.0
147                    .names
148                    .last()
149                    .expect("file has a name")
150                    .to_str()
151                    .expect("validated name"),
152            ),
153            _ => None,
154        }
155    }
156    /// Join the separate fields of an existing local declaration or saved wire record.
157    pub fn with_kind(
158        self,
159        kind: super::ArtifactKind,
160        select: Vec<LogicalPath>,
161    ) -> Result<Self, ScopeError> {
162        use super::ArtifactKind;
163        if kind != ArtifactKind::Aspect && !select.is_empty() {
164            return Err(ScopeError(
165                "Only an aspect target has selected paths.".into(),
166            ));
167        }
168        let path = match self {
169            Self::Folder(path) | Self::Graph(path) | Self::Aspect { path, .. } => path,
170            Self::File(path) => path.0,
171            Self::Live(_) if kind == ArtifactKind::Live => return Ok(self),
172            Self::Live(_) => {
173                return Err(ScopeError(
174                    "A Live URI cannot have a filesystem kind.".into(),
175                ));
176            }
177        };
178        match kind {
179            ArtifactKind::Folder => Ok(Self::Folder(path)),
180            ArtifactKind::File if path.names.is_empty() => Err(ScopeError(
181                "A File Artifact must name a file, not the project root.".into(),
182            )),
183            ArtifactKind::File => Ok(Self::File(FileTarget(path))),
184            ArtifactKind::Aspect => Ok(Self::Aspect { path, select }),
185            ArtifactKind::Graph => Ok(Self::Graph(path)),
186            ArtifactKind::Live => Err(ScopeError("A Live target needs a URI.".into())),
187        }
188    }
189    pub fn text(&self) -> Cow<'_, str> {
190        match self {
191            Self::Live(uri) => Cow::Borrowed(uri.as_str()),
192            _ => Cow::Owned(crate::files::relative_text(
193                self.local_target()
194                    .expect("local variant")
195                    .names
196                    .iter()
197                    .map(OsString::as_os_str),
198            )),
199        }
200    }
201}
202impl TryFrom<PathBuf> for Target {
203    type Error = ScopeError;
204
205    fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
206        LocalTarget::try_from(path).map(Self::Folder)
207    }
208}
209impl TryFrom<&str> for Target {
210    type Error = ScopeError;
211
212    fn try_from(path: &str) -> Result<Self, Self::Error> {
213        Self::try_from(PathBuf::from(path))
214    }
215}
216impl fmt::Display for Target {
217    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
218        formatter.write_str(&self.text())
219    }
220}
221impl Serialize for Target {
222    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
223        serializer.serialize_str(&self.text())
224    }
225}
226impl<'de> Deserialize<'de> for Target {
227    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
228        let value = String::deserialize(deserializer)?;
229        if Uri::has_scheme(&value) {
230            value
231                .parse()
232                .map(Self::Live)
233                .map_err(serde::de::Error::custom)
234        } else {
235            let (path, names) =
236                crate::files::parse_target_path(&value).map_err(serde::de::Error::custom)?;
237            Ok(Self::Folder(LocalTarget { path, names }))
238        }
239    }
240}
241impl crate::files::PathText for Target {
242    fn path_text(&self) -> String {
243        self.to_string()
244    }
245}
246impl PartialEq for Target {
247    fn eq(&self, other: &Self) -> bool {
248        match (self, other) {
249            (Self::Folder(first), Self::Folder(second))
250            | (Self::File(FileTarget(first)), Self::File(FileTarget(second)))
251            | (Self::Graph(first), Self::Graph(second)) => {
252                crate::files::paths_equal(&first.path, &second.path)
253            }
254            (
255                Self::Aspect {
256                    path: first,
257                    select,
258                },
259                Self::Aspect {
260                    path: second,
261                    select: other,
262                },
263            ) => crate::files::paths_equal(&first.path, &second.path) && select == other,
264            (Self::Live(first), Self::Live(second)) => first == second,
265            _ => false,
266        }
267    }
268}
269impl Eq for Target {}
270
271impl PartialEq<PathBuf> for Target {
272    fn eq(&self, other: &PathBuf) -> bool {
273        self.local()
274            .is_some_and(|path| crate::files::paths_equal(path, other))
275    }
276}