Skip to main content

qubit_fs/path/
path.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Provider-neutral logical paths.
10
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fmt::Result as FmtResult;
14
15use super::PathComponent;
16use super::PathComponents;
17use super::PathSemantics;
18use super::RelativePath;
19use crate::error::FsError;
20use crate::error::FsOperation;
21use crate::error::FsResult;
22
23/// A validated logical path independent of any provider-native representation.
24///
25/// # Examples
26/// ```rust
27/// use qubit_fs::Path;
28/// use qubit_fs::path::RelativePath;
29/// let root = Path::parse("/reports")?;
30/// let report = root.join(&RelativePath::parse("daily.csv")?);
31/// assert_eq!("/reports/daily.csv", report.as_str());
32/// assert!(report.is_absolute());
33/// # Ok::<(), qubit_fs::FsError>(())
34/// ```
35#[derive(Clone, Debug, Eq, Hash, PartialEq)]
36pub struct Path {
37    /// Whether this logical path starts at a provider root.
38    absolute: bool,
39    /// Canonical normalized or provider-literal text.
40    text: String,
41    /// Whether component iteration must preserve literal slash boundaries.
42    literal: bool,
43    /// Semantics used to validate this spelling.
44    semantics: PathSemantics,
45}
46
47impl Path {
48    /// Creates the canonical hierarchical root path.
49    ///
50    /// # Returns
51    /// Returns the absolute hierarchical root path.
52    #[inline]
53    #[must_use]
54    pub fn root() -> Self {
55        Self {
56            absolute: true,
57            text: "/".to_owned(),
58            literal: false,
59            semantics: PathSemantics::Hierarchical,
60        }
61    }
62
63    /// Constructs a hierarchical path from independently validated components.
64    ///
65    /// Each item is validated as one component without reparsing a joined path
66    /// string. An empty absolute sequence produces the root; an empty relative
67    /// sequence returns an invalid-path error.
68    ///
69    /// # Type Parameters
70    /// - `I`: Iterator type yielding the component values.
71    /// - `S`: Component value type borrowing string slices through `AsRef`.
72    ///
73    /// # Parameters
74    /// - `absolute`: Whether the resulting path is rooted at the provider root.
75    /// - `components`: Validated path-component text to join in order.
76    ///
77    /// # Returns
78    /// Returns the validated path containing the joined components.
79    ///
80    /// # Errors
81    /// Returns an invalid-path error when a component is empty, contains a
82    /// separator or traversal marker, or when a relative sequence is empty.
83    #[inline]
84    pub fn from_components<I, S>(absolute: bool, components: I) -> FsResult<Self>
85    where
86        I: IntoIterator<Item = S>,
87        S: AsRef<str>,
88    {
89        let components = components
90            .into_iter()
91            .map(|value| PathComponent::parse(value.as_ref()))
92            .collect::<FsResult<Vec<_>>>()?;
93        if !absolute && components.is_empty() {
94            return Err(invalid_path());
95        }
96        let joined = components
97            .iter()
98            .map(PathComponent::as_str)
99            .collect::<Vec<_>>()
100            .join("/");
101        Ok(Self {
102            absolute,
103            text: if absolute {
104                if joined.is_empty() {
105                    "/".to_owned()
106                } else {
107                    format!("/{joined}")
108                }
109            } else {
110                joined
111            },
112            literal: false,
113            semantics: PathSemantics::Hierarchical,
114        })
115    }
116
117    /// Parses a hierarchical logical path using normalized semantics.
118    ///
119    /// Returns an invalid-path error for empty input, NUL, or root escape.
120    ///
121    /// # Errors
122    /// Returns [`FsError`] with an invalid-path kind when `text` is empty,
123    /// contains NUL, or escapes above the hierarchical root.
124    ///
125    /// # Parameters
126    /// - `text`: Hierarchical path spelling to normalize and validate.
127    ///
128    /// # Returns
129    /// Returns the normalized hierarchical path.
130    #[inline]
131    pub fn parse(text: &str) -> FsResult<Self> {
132        Self::parse_with_semantics(text, PathSemantics::Hierarchical)
133    }
134
135    /// Parses a provider-literal path without interpreting separators or dots.
136    ///
137    /// Returns an invalid-path error for empty input or NUL.
138    ///
139    /// # Errors
140    /// Returns [`FsError`] with an invalid-path kind when `text` is empty or
141    /// contains NUL.
142    ///
143    /// # Parameters
144    /// - `text`: Provider-literal path spelling to retain and validate.
145    ///
146    /// # Returns
147    /// Returns the provider-literal path preserving `text`.
148    #[inline]
149    pub fn parse_literal(text: &str) -> FsResult<Self> {
150        Self::parse_with_semantics(text, PathSemantics::ObjectKey)
151    }
152
153    /// Parses `text` according to explicitly selected provider semantics.
154    ///
155    /// Hierarchical values normalize empty and dot components and reject root
156    /// escapes. Object-key and provider-specific values preserve their text.
157    ///
158    /// # Parameters
159    /// - `text`: Provider path text to validate and normalize.
160    /// - `semantics`: Path semantics controlling normalization and root rules.
161    ///
162    /// # Errors
163    /// Returns an invalid-path error when `text` is empty, contains NUL, or
164    /// escapes above the hierarchical root.
165    ///
166    /// # Returns
167    /// Returns the path using the selected provider semantics.
168    pub fn parse_with_semantics(text: &str, semantics: PathSemantics) -> FsResult<Self> {
169        if text.is_empty() || text.contains('\0') {
170            return Err(invalid_path());
171        }
172        if semantics != PathSemantics::Hierarchical {
173            return Ok(Self {
174                absolute: text.starts_with('/'),
175                text: text.to_owned(),
176                literal: true,
177                semantics,
178            });
179        }
180        let absolute = text.starts_with('/');
181        let mut components = Vec::new();
182        for component in text.split('/') {
183            match component {
184                "" | "." => {}
185                ".." => {
186                    if components.pop().is_none() {
187                        return Err(invalid_path());
188                    }
189                }
190                value => components.push(value),
191            }
192        }
193        let text = if absolute {
194            if components.is_empty() {
195                "/".to_owned()
196            } else {
197                format!("/{}", components.join("/"))
198            }
199        } else {
200            components.join("/")
201        };
202        if text.is_empty() {
203            return Err(invalid_path());
204        }
205        Ok(Self {
206            absolute,
207            text,
208            literal: false,
209            semantics,
210        })
211    }
212
213    /// Returns the validated logical path text.
214    ///
215    /// # Returns
216    /// Returns the canonical or provider-literal spelling borrowed from this
217    /// path.
218    #[inline]
219    #[must_use]
220    pub fn as_str(&self) -> &str {
221        &self.text
222    }
223
224    /// Returns the final non-empty path component, when one is present.
225    ///
226    /// A root path and a literal path ending in a separator have no file
227    /// name. Hierarchical paths are canonicalized during parsing, so their
228    /// final component is always non-empty.
229    ///
230    /// # Returns
231    /// `Some` with the final non-empty component, or `None` for a root or a
232    /// literal path ending in a separator.
233    #[inline]
234    pub fn file_name(&self) -> Option<&str> {
235        if self.text == "/" || (self.literal && self.text.ends_with('/')) {
236            return None;
237        }
238        self.text.rsplit('/').find(|component| !component.is_empty())
239    }
240
241    /// Returns whether this path is absolute.
242    ///
243    /// # Returns
244    /// Returns `true` when this path starts at a provider root.
245    #[inline]
246    #[must_use]
247    pub const fn is_absolute(&self) -> bool {
248        self.absolute
249    }
250
251    /// Returns the semantics used to validate this logical path.
252    ///
253    /// # Returns
254    /// Returns the semantics selected when this path was parsed or constructed.
255    #[inline]
256    #[must_use]
257    pub const fn semantics(&self) -> PathSemantics {
258        self.semantics
259    }
260
261    /// Iterates lexical component boundaries without using an empty root value.
262    ///
263    /// # Returns
264    /// Returns an iterator over lexical components; literal paths preserve
265    /// empty components between separators.
266    #[inline]
267    #[must_use]
268    pub fn components(&self) -> PathComponents<'_> {
269        PathComponents::new(&self.text, self.absolute, self.literal)
270    }
271
272    /// Appends one validated component without re-parsing provider text.
273    ///
274    /// # Parameters
275    /// - `component`: Validated component to append.
276    ///
277    /// # Returns
278    /// Returns a new path with `component` appended.
279    #[inline]
280    #[must_use]
281    pub fn child(&self, component: &PathComponent) -> Self {
282        self.append(component.as_str())
283    }
284
285    /// Appends a safe normalized relative path without re-parsing provider
286    /// text.
287    ///
288    /// # Parameters
289    /// - `relative`: Validated relative path to append.
290    ///
291    /// # Returns
292    /// Returns a new path with `relative` appended.
293    #[inline]
294    #[must_use]
295    pub fn join(&self, relative: &RelativePath) -> Self {
296        self.append(relative.as_str())
297    }
298
299    /// Joins an already validated suffix to this path.
300    ///
301    /// # Parameters
302    /// - `suffix`: Validated suffix text to append after a separator.
303    fn append(&self, suffix: &str) -> Self {
304        let hierarchical_root = self.semantics == PathSemantics::Hierarchical && !self.literal && self.text == "/";
305        let text = if hierarchical_root {
306            format!("/{suffix}")
307        } else {
308            format!("{}/{}", self.text, suffix)
309        };
310        Self {
311            absolute: self.absolute,
312            text,
313            literal: self.literal,
314            semantics: self.semantics,
315        }
316    }
317}
318
319impl Display for Path {
320    /// Formats the validated logical spelling.
321    ///
322    /// # Parameters
323    /// - `formatter`: Destination for the path spelling.
324    #[inline]
325    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
326        formatter.write_str(self.as_str())
327    }
328}
329
330impl AsRef<str> for Path {
331    /// Returns the logical path text for generic text consumers.
332    #[inline]
333    fn as_ref(&self) -> &str {
334        self.as_str()
335    }
336}
337
338/// Builds the shared logical path validation failure.
339fn invalid_path() -> FsError {
340    FsError::invalid_path(
341        FsOperation::ParsePath,
342        "path must be non-empty, NUL-free, and remain within its root",
343    )
344}