Skip to main content

artifactize_tools/
scope.rs

1//! Logical scope data and path resolution independent of project configuration.
2
3use std::{
4    borrow::Borrow,
5    collections::BTreeMap,
6    fmt,
7    path::{Path, PathBuf},
8};
9
10use serde::{Deserialize, Serialize, Serializer};
11use thiserror::Error;
12
13mod open;
14pub(crate) use open::open_native_scoped;
15pub use open::{OpenError, open_child, open_input, open_scoped, scoped_path};
16mod logical;
17pub use logical::LogicalPath;
18mod target;
19pub use target::{FileTarget, LocalTarget, Target, Uri};
20
21/// Bound logical tool paths in UTF-16 units, matching JSON Schema string limits
22/// across supported clients without tying scoped paths to an OS-specific PATH_MAX.
23pub const MAX_PATH_UNITS: usize = 4096;
24
25/// Bound Artifact IDs like artifactize's Artifact names, so they stay short in tool output.
26pub const MAX_ARTIFACT_ID_BYTES: usize = 64;
27
28#[derive(Debug, Error)]
29#[error("{0}")]
30pub struct ScopeError(pub String);
31
32/// An Artifact's ID: `[A-Za-z0-9][A-Za-z0-9_-]{0,63}`, so it can never smuggle a path
33/// separator, a dot component, or control text into a scope key or a tool result.
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
35#[serde(transparent)]
36pub struct ArtifactId(String);
37
38impl ArtifactId {
39    pub fn new(value: impl Into<String>) -> Result<Self, ScopeError> {
40        let value = value.into();
41        let valid = value.len() <= MAX_ARTIFACT_ID_BYTES
42            && value
43                .bytes()
44                .next()
45                .is_some_and(|first| first.is_ascii_alphanumeric())
46            && value
47                .bytes()
48                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'));
49        if valid {
50            Ok(Self(value))
51        } else {
52            Err(ScopeError(format!(
53                "Artifact ID must match [A-Za-z0-9][A-Za-z0-9_-]{{0,63}}: {value:?}"
54            )))
55        }
56    }
57
58    pub fn as_str(&self) -> &str {
59        &self.0
60    }
61}
62
63/// Lets scope maps be looked up by a borrowed name; the derived order matches `str`'s.
64impl Borrow<str> for ArtifactId {
65    fn borrow(&self) -> &str {
66        &self.0
67    }
68}
69
70impl fmt::Display for ArtifactId {
71    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72        formatter.write_str(&self.0)
73    }
74}
75
76impl PartialEq<str> for ArtifactId {
77    fn eq(&self, other: &str) -> bool {
78        self.0 == other
79    }
80}
81
82impl PartialEq<&str> for ArtifactId {
83    fn eq(&self, other: &&str) -> bool {
84        self.0 == *other
85    }
86}
87
88impl PartialEq<String> for ArtifactId {
89    fn eq(&self, other: &String) -> bool {
90        self.0 == *other
91    }
92}
93
94/// A safe relative logical path below an Artifact: `/`-separated plain names, such as a
95/// child Artifact's folder prefix. It holds no empty, `.` or `..` component.
96macro_rules! logical_name {
97    ($name:ident, $what:literal, $valid:expr) => {
98        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
99        #[serde(transparent)]
100        pub struct $name(String);
101
102        impl $name {
103            pub fn new(value: impl Into<String>) -> Result<Self, ScopeError> {
104                let value = value.into();
105                if !value.is_empty() && logical_path(&value).is_ok() && ($valid)(&value) {
106                    Ok(Self(value))
107                } else {
108                    Err(ScopeError(format!(
109                        concat!("Invalid ", $what, ": {:?}"),
110                        value
111                    )))
112                }
113            }
114
115            pub fn as_str(&self) -> &str {
116                &self.0
117            }
118        }
119
120        impl Borrow<str> for $name {
121            fn borrow(&self) -> &str {
122                &self.0
123            }
124        }
125
126        impl std::ops::Deref for $name {
127            type Target = str;
128            fn deref(&self) -> &str {
129                &self.0
130            }
131        }
132
133        impl fmt::Display for $name {
134            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135                formatter.write_str(&self.0)
136            }
137        }
138    };
139}
140
141logical_name!(ChildPrefix, "child folder prefix", |_: &str| true);
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
144#[serde(rename_all = "camelCase")]
145pub enum ArtifactKind {
146    Folder,
147    File,
148    /// Selected paths below the folder of its declaration.
149    Aspect,
150    Graph,
151    Live,
152}
153
154/// Access data computed by the caller, without declarations, evals, or owner commands.
155#[derive(Debug, Clone)]
156pub struct Artifact {
157    pub path: Target,
158    pub name: String,
159    /// Logical path prefix to the nested folder Artifact that owns it.
160    pub nested: BTreeMap<ChildPrefix, ArtifactId>,
161    /// A folder part whose target contains this entire target's containing folder.
162    pub covering_part: Option<ArtifactId>,
163}
164
165impl Artifact {
166    pub fn kind(&self) -> ArtifactKind {
167        self.path.kind()
168    }
169    pub fn select(&self) -> &[LogicalPath] {
170        self.path.select()
171    }
172    pub fn folder(&self) -> &Path {
173        self.path.folder()
174    }
175
176    /// Whether only some paths below its folder are the Artifact's: a file Artifact's
177    /// target or an aspect's selection, under a virtual root.
178    pub fn selective(&self) -> bool {
179        matches!(self.kind(), ArtifactKind::File | ArtifactKind::Aspect)
180    }
181
182    /// Whether the logical `path` below its folder is the Artifact's: always for a folder,
183    /// and for an aspect a selected path, a path below one, or a folder leading to one.
184    pub fn admits(&self, path: InputPath<&str>) -> bool {
185        let path = path.as_str();
186        if path.is_empty() {
187            return true;
188        }
189        match self.kind() {
190            ArtifactKind::Folder | ArtifactKind::Graph => true,
191            ArtifactKind::Live => false,
192            ArtifactKind::File => self.file_name() == Some(path),
193            ArtifactKind::Aspect => self.select().iter().any(|selected| {
194                let within = |outer: &str, inner: &str| {
195                    inner
196                        .strip_prefix(outer)
197                        .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
198                };
199                within(selected, path) || within(path, selected)
200            }),
201        }
202    }
203
204    pub fn file_name(&self) -> Option<&str> {
205        self.path.file_name()
206    }
207}
208
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct ScopedPath {
211    pub artifact_id: ArtifactId,
212    pub path: InputPath,
213}
214
215#[derive(Debug)]
216pub struct Scope {
217    pub artifacts: BTreeMap<ArtifactId, Artifact>,
218}
219
220impl Scope {
221    pub(crate) fn artifact(&self, id: &ArtifactId) -> Result<&Artifact, ScopeError> {
222        self.artifacts
223            .get(id)
224            .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {id}")))
225    }
226
227    /// Pure logical resolution. Each child hop consumes path components.
228    pub fn resolve_path(
229        &self,
230        artifact_id: &ArtifactId,
231        path: &str,
232    ) -> Result<ScopedPath, ScopeError> {
233        let location = self.locate(artifact_id, InputPath::parse(path)?)?;
234        Ok(ScopedPath {
235            artifact_id: location.artifact_id.clone(),
236            path: location.path.owned(),
237        })
238    }
239
240    pub(crate) fn locate<'a, 'p>(
241        &'a self,
242        artifact_id: &'a ArtifactId,
243        path: InputPath<&'p str>,
244    ) -> Result<Location<'a, 'p>, ScopeError> {
245        let mut current = artifact_id;
246        let mut remaining = path;
247        loop {
248            let artifact = self.artifact(current)?;
249            if artifact.kind() == ArtifactKind::Live {
250                return Err(ScopeError(
251                    "Live Artifacts have no filesystem inputs.".into(),
252                ));
253            }
254            if let Some(part) = &artifact.covering_part
255                && !self.artifacts.contains_key(part)
256            {
257                return Err(ScopeError(format!(
258                    "Artifact {current} is covered by folder part {part}; reference {{{part}}} to read its files."
259                )));
260            }
261            if let Some((target, rest)) = artifact.nested.iter().find_map(|(prefix, target)| {
262                remaining.after(prefix.as_str()).map(|rest| (target, rest))
263            }) {
264                current = target;
265                remaining = rest;
266                continue;
267            }
268            file_input(artifact, remaining)?;
269            return Ok(Location {
270                artifact_id: current,
271                artifact,
272                path: remaining,
273            });
274        }
275    }
276
277    /// Existing file or directory, without traversing links even inside the owner.
278    pub fn resolve_input(
279        &self,
280        root: &Path,
281        artifact_id: &ArtifactId,
282        path: &str,
283    ) -> Result<PathBuf, ScopeError> {
284        self.resolve_parsed(root, artifact_id, InputPath::parse(path)?)
285    }
286
287    /// [`Self::resolve_input`] for a path already validated at its edge.
288    pub(crate) fn resolve_parsed<T: AsRef<str>>(
289        &self,
290        root: &Path,
291        artifact_id: &ArtifactId,
292        path: InputPath<T>,
293    ) -> Result<PathBuf, ScopeError> {
294        self.locate(artifact_id, path.borrowed())?.native_path(root)
295    }
296}
297
298pub(crate) struct Location<'a, 'p> {
299    pub artifact_id: &'a ArtifactId,
300    pub artifact: &'a Artifact,
301    pub path: InputPath<&'p str>,
302}
303
304/// A validated tool path, distinct from declaration selections. Empty denotes the root.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
306pub struct InputPath<T = String>(T);
307
308impl InputPath<String> {
309    /// A native command-line path, its names validated once by the platform layer.
310    pub(crate) fn from_native(path: &Path) -> Result<Self, ScopeError> {
311        let text =
312            crate::files::relative_text_of(path).map_err(|error| ScopeError(error.to_string()))?;
313        if text.encode_utf16().count() > MAX_PATH_UNITS {
314            return Err(ScopeError(
315                "Artifact path must be a safe relative logical path.".into(),
316            ));
317        }
318        Ok(Self(text))
319    }
320}
321
322impl<T: AsRef<str>> InputPath<T> {
323    pub(crate) fn parse(path: T) -> Result<Self, ScopeError> {
324        logical_path(path.as_ref())?;
325        Ok(Self(path))
326    }
327
328    pub fn as_str(&self) -> &str {
329        self.0.as_ref()
330    }
331
332    pub(crate) fn borrowed(&self) -> InputPath<&str> {
333        InputPath(self.as_str())
334    }
335
336    /// A native entry has already been checked as a single logical name by the platform.
337    pub(crate) fn child(&self, name: &str) -> Option<InputPath<String>> {
338        let path = if self.as_str().is_empty() {
339            name.to_owned()
340        } else {
341            format!("{}/{name}", self.as_str())
342        };
343        (path.encode_utf16().count() <= MAX_PATH_UNITS).then_some(InputPath(path))
344    }
345}
346
347impl std::str::FromStr for InputPath<String> {
348    type Err = ScopeError;
349
350    fn from_str(path: &str) -> Result<Self, Self::Err> {
351        InputPath::parse(path).map(InputPath::owned)
352    }
353}
354
355impl<T: AsRef<str>> fmt::Display for InputPath<T> {
356    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
357        formatter.write_str(self.as_str())
358    }
359}
360
361impl<T: AsRef<str>> Serialize for InputPath<T> {
362    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
363        serializer.serialize_str(self.as_str())
364    }
365}
366
367impl<T: AsRef<str>> AsRef<Path> for InputPath<T> {
368    fn as_ref(&self) -> &Path {
369        Path::new(self.as_str())
370    }
371}
372
373impl<'a> InputPath<&'a str> {
374    pub(crate) fn into_str(self) -> &'a str {
375        self.0
376    }
377
378    pub(crate) fn root() -> Self {
379        Self("")
380    }
381
382    fn after(self, prefix: &str) -> Option<Self> {
383        let suffix = self.0.strip_prefix(prefix)?;
384        if suffix.is_empty() {
385            Some(Self::root())
386        } else {
387            suffix.strip_prefix('/').map(Self)
388        }
389    }
390
391    fn names(self) -> impl Iterator<Item = &'a str> {
392        self.0.split('/').filter(|name| !name.is_empty())
393    }
394
395    pub(crate) fn owned(self) -> InputPath<String> {
396        InputPath(self.0.to_owned())
397    }
398}
399
400/// A file Artifact exposes a virtual root containing only its target, and an aspect one
401/// containing only its selected paths.
402fn file_input(artifact: &Artifact, path: InputPath<&str>) -> Result<(), ScopeError> {
403    if artifact.admits(path) {
404        return Ok(());
405    }
406    Err(ScopeError(match artifact.file_name() {
407        Some(target) => format!(
408            "File Artifact {} exposes only its target {target}.",
409            artifact.name
410        ),
411        None => format!(
412            "Aspect {} exposes only its selected paths: {}.",
413            artifact.name,
414            artifact.select().join(", ")
415        ),
416    }))
417}
418
419pub fn logical_path(path: &str) -> Result<(), ScopeError> {
420    if path.encode_utf16().count() > MAX_PATH_UNITS
421        || path
422            .bytes()
423            .any(|byte| byte.is_ascii_control() || matches!(byte, b'\\' | b':'))
424        || (!path.is_empty()
425            && path
426                .split('/')
427                .any(|part| part.is_empty() || part == "." || part == ".."))
428    {
429        return Err(ScopeError(
430            "Artifact path must be a safe relative logical path.".into(),
431        ));
432    }
433    Ok(())
434}
435
436/// The logical form of a native relative path: its components joined with `/`, whatever
437/// separator the platform uses. `None` when a component is not UTF-8 or not a plain name.
438pub fn logical_from_native(path: &Path) -> Option<String> {
439    crate::files::logical_from_native(path)
440}