Skip to main content

pray_core/
paths.rs

1use crate::{PrayError, PrayResult};
2use std::fs;
3use std::path::{Component, Path, PathBuf};
4
5/// Repository-relative path that cannot escape a project root when joined.
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub struct ProjectRelativePath(PathBuf);
8
9impl ProjectRelativePath {
10    pub fn parse(value: &str) -> PrayResult<Self> {
11        let trimmed = value.trim();
12        if trimmed.is_empty() {
13            return Err(PrayError::Manifest(
14                "project path must not be empty".to_string(),
15            ));
16        }
17        let path = Path::new(trimmed);
18        if path.is_absolute() {
19            return Err(PrayError::Manifest(format!(
20                "project path must be repository-relative: {trimmed}"
21            )));
22        }
23        let mut relative = PathBuf::new();
24        for component in path.components() {
25            match component {
26                Component::Normal(part) => relative.push(part),
27                Component::CurDir => {}
28                _ => {
29                    return Err(PrayError::Manifest(format!(
30                        "project path escapes repository root: {trimmed}"
31                    )));
32                }
33            }
34        }
35        if relative.as_os_str().is_empty() {
36            return Err(PrayError::Manifest(format!(
37                "project path must be repository-relative: {trimmed}"
38            )));
39        }
40        Ok(Self(relative))
41    }
42
43    pub fn as_path(&self) -> &Path {
44        &self.0
45    }
46
47    pub fn as_str(&self) -> &str {
48        self.0.to_str().unwrap_or("")
49    }
50
51    pub fn join_root(&self, root: &Path) -> PathBuf {
52        root.join(&self.0)
53    }
54}
55
56pub fn validate_project_relative_path(value: &str) -> PrayResult<ProjectRelativePath> {
57    ProjectRelativePath::parse(value)
58}
59
60pub fn validate_destination_path(value: &str) -> PrayResult<ProjectRelativePath> {
61    if value.trim().starts_with('~') {
62        return Err(PrayError::Manifest(format!(
63            "project path must be repository-relative: {}",
64            value.trim()
65        )));
66    }
67    ProjectRelativePath::parse(value)
68}
69
70pub fn find_prayspec_file(root: &Path) -> PrayResult<PathBuf> {
71    let mut prayspec_files = Vec::new();
72    for entry in fs::read_dir(root)? {
73        let entry = entry?;
74        let path = entry.path();
75        if path.extension().and_then(|value| value.to_str()) == Some("prayspec") {
76            prayspec_files.push(path);
77        }
78    }
79    match prayspec_files.len() {
80        1 => Ok(prayspec_files.remove(0)),
81        0 => Err(PrayError::Resolution(format!(
82            "no prayspec file found in {:?}",
83            root
84        ))),
85        _ => Err(PrayError::Resolution(format!(
86            "multiple prayspec files found in {:?}",
87            root
88        ))),
89    }
90}
91
92pub fn validate_package_relative_path(path: &Path) -> PrayResult<()> {
93    if path.is_absolute() {
94        return Err(PrayError::Integrity(format!(
95            "package path must be relative: {}",
96            path.display()
97        )));
98    }
99    for component in path.components() {
100        match component {
101            Component::Normal(_) | Component::CurDir => {}
102            _ => {
103                return Err(PrayError::Integrity(format!(
104                    "package path escapes package root: {}",
105                    path.display()
106                )));
107            }
108        }
109    }
110    Ok(())
111}
112
113pub fn sanitize_relative_path(path: &str) -> PrayResult<PathBuf> {
114    let path = path.trim_start_matches('/');
115    let mut relative = PathBuf::new();
116    for component in Path::new(path).components() {
117        match component {
118            Component::Normal(part) => relative.push(part),
119            Component::CurDir => {}
120            _ => {
121                return Err(PrayError::Resolution(format!(
122                    "invalid relative path: {path}"
123                )));
124            }
125        }
126    }
127    if relative.as_os_str().is_empty() {
128        return Err(PrayError::Resolution(format!(
129            "invalid relative path: {path}"
130        )));
131    }
132    Ok(relative)
133}
134
135pub fn remove_path_if_exists(path: &Path) -> PrayResult<()> {
136    match fs::symlink_metadata(path) {
137        Ok(metadata) if metadata.is_dir() => {
138            fs::remove_dir_all(path)?;
139            Ok(())
140        }
141        Ok(_) => {
142            fs::remove_file(path)?;
143            Ok(())
144        }
145        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
146        Err(error) => Err(error.into()),
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn sanitize_relative_path_rejects_parent_dir() {
156        let error = sanitize_relative_path("../escape.praypkg").expect_err("parent dir");
157        assert!(error.to_string().contains("invalid relative path"));
158    }
159
160    #[test]
161    fn sanitize_relative_path_accepts_nested_artifact() {
162        let path = sanitize_relative_path("v1/artifacts/sample/base/1.0.0/package.praypkg")
163            .expect("nested path");
164        assert_eq!(
165            path,
166            PathBuf::from("v1/artifacts/sample/base/1.0.0/package.praypkg")
167        );
168    }
169
170    #[test]
171    fn validate_package_relative_path_rejects_parent_escape() {
172        let error =
173            validate_package_relative_path(Path::new("../escape.md")).expect_err("parent escape");
174        assert!(error.to_string().contains("escapes package root"));
175    }
176
177    #[test]
178    fn validate_package_relative_path_rejects_absolute() {
179        let absolute = if cfg!(windows) {
180            Path::new(r"C:\escape.md")
181        } else {
182            Path::new("/escape.md")
183        };
184        let error = validate_package_relative_path(absolute).expect_err("absolute");
185        assert!(error.to_string().contains("must be relative"));
186    }
187
188    #[test]
189    fn validate_package_relative_path_accepts_nested_file() {
190        validate_package_relative_path(Path::new("exports/guidance.md")).expect("nested file");
191    }
192
193    #[test]
194    fn project_relative_path_rejects_parent_and_absolute() {
195        let parent = ProjectRelativePath::parse("../escape.md").expect_err("parent");
196        assert!(parent.to_string().contains("escapes repository root"));
197        let absolute = if cfg!(windows) {
198            ProjectRelativePath::parse(r"C:\escape.md")
199        } else {
200            ProjectRelativePath::parse("/tmp/escape.md")
201        }
202        .expect_err("absolute");
203        assert!(absolute.to_string().contains("repository-relative"));
204        let tilde = validate_destination_path("~/.zshrc").expect_err("tilde");
205        assert!(tilde.to_string().contains("repository-relative"));
206    }
207
208    #[test]
209    fn project_relative_path_joins_under_root() {
210        let relative = ProjectRelativePath::parse("docs/AGENTS.md").expect("relative");
211        assert_eq!(
212            relative.join_root(Path::new("/repo")),
213            PathBuf::from("/repo/docs/AGENTS.md")
214        );
215    }
216}