1use crate::{PrayError, PrayResult};
2use std::fs;
3use std::path::{Component, Path, PathBuf};
4
5#[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 validate_registry_cache_identity<'a>(
114 package_name: &'a str,
115 version: &str,
116) -> PrayResult<(&'a str, &'a str)> {
117 let mut segments = package_name.split('/');
118 let namespace = segments.next().unwrap_or_default();
119 let name = segments.next().unwrap_or_default();
120 if segments.next().is_some()
121 || !registry_cache_segment_is_safe(namespace)
122 || !registry_cache_segment_is_safe(name)
123 {
124 return Err(PrayError::Integrity(format!(
125 "invalid registry package name: {package_name}"
126 )));
127 }
128 if !registry_cache_segment_is_safe(version) {
129 return Err(PrayError::Integrity(format!(
130 "invalid registry package version: {version}"
131 )));
132 }
133 Ok((namespace, name))
134}
135
136fn registry_cache_segment_is_safe(value: &str) -> bool {
137 !value.is_empty() && value != "." && value != ".." && !value.contains(['/', '\\', '\0'])
138}
139
140pub fn sanitize_relative_path(path: &str) -> PrayResult<PathBuf> {
141 let path = path.trim_start_matches('/');
142 let mut relative = PathBuf::new();
143 for component in Path::new(path).components() {
144 match component {
145 Component::Normal(part) => relative.push(part),
146 Component::CurDir => {}
147 _ => {
148 return Err(PrayError::Resolution(format!(
149 "invalid relative path: {path}"
150 )));
151 }
152 }
153 }
154 if relative.as_os_str().is_empty() {
155 return Err(PrayError::Resolution(format!(
156 "invalid relative path: {path}"
157 )));
158 }
159 Ok(relative)
160}
161
162pub fn remove_path_if_exists(path: &Path) -> PrayResult<()> {
163 match fs::symlink_metadata(path) {
164 Ok(metadata) if metadata.is_dir() => {
165 fs::remove_dir_all(path)?;
166 Ok(())
167 }
168 Ok(_) => {
169 fs::remove_file(path)?;
170 Ok(())
171 }
172 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
173 Err(error) => Err(error.into()),
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn sanitize_relative_path_rejects_parent_dir() {
183 let error = sanitize_relative_path("../escape.praypkg").expect_err("parent dir");
184 assert!(error.to_string().contains("invalid relative path"));
185 }
186
187 #[test]
188 fn sanitize_relative_path_accepts_nested_artifact() {
189 let path = sanitize_relative_path("v1/artifacts/sample/base/1.0.0/package.praypkg")
190 .expect("nested path");
191 assert_eq!(
192 path,
193 PathBuf::from("v1/artifacts/sample/base/1.0.0/package.praypkg")
194 );
195 }
196
197 #[test]
198 fn validate_package_relative_path_rejects_parent_escape() {
199 let error =
200 validate_package_relative_path(Path::new("../escape.md")).expect_err("parent escape");
201 assert!(error.to_string().contains("escapes package root"));
202 }
203
204 #[test]
205 fn validate_package_relative_path_rejects_absolute() {
206 let absolute = if cfg!(windows) {
207 Path::new(r"C:\escape.md")
208 } else {
209 Path::new("/escape.md")
210 };
211 let error = validate_package_relative_path(absolute).expect_err("absolute");
212 assert!(error.to_string().contains("must be relative"));
213 }
214
215 #[test]
216 fn validate_package_relative_path_accepts_nested_file() {
217 validate_package_relative_path(Path::new("exports/guidance.md")).expect("nested file");
218 }
219
220 #[test]
221 fn project_relative_path_rejects_parent_and_absolute() {
222 let parent = ProjectRelativePath::parse("../escape.md").expect_err("parent");
223 assert!(parent.to_string().contains("escapes repository root"));
224 let absolute = if cfg!(windows) {
225 ProjectRelativePath::parse(r"C:\escape.md")
226 } else {
227 ProjectRelativePath::parse("/tmp/escape.md")
228 }
229 .expect_err("absolute");
230 assert!(absolute.to_string().contains("repository-relative"));
231 let tilde = validate_destination_path("~/.zshrc").expect_err("tilde");
232 assert!(tilde.to_string().contains("repository-relative"));
233 }
234
235 #[test]
236 fn project_relative_path_joins_under_root() {
237 let relative = ProjectRelativePath::parse("docs/AGENTS.md").expect("relative");
238 assert_eq!(
239 relative.join_root(Path::new("/repo")),
240 PathBuf::from("/repo/docs/AGENTS.md")
241 );
242 }
243}