artifactize_tools/platform/
files.rs1use std::{
4 ffi::{OsStr, OsString},
5 fs::File,
6 io,
7 path::{Component, Path, PathBuf},
8};
9
10pub use artifactize_foundation::platform::files::*;
11
12pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
14 first == second
15}
16
17pub fn is_absolute(path: &std::path::Path) -> bool {
19 path.is_absolute()
20}
21
22pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
25 if path.is_absolute() {
26 logical_from_native(&relative_below(root, path)?)
27 } else {
28 logical_from_native(path)
29 }
30}
31
32pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
35 if let Ok(relative) = path.strip_prefix(root) {
36 return Some(relative.to_path_buf());
37 }
38 let ancestor = path
39 .ancestors()
40 .find(|ancestor| artifactize_foundation::platform::paths::paths_equal(ancestor, root))?;
41 path.strip_prefix(ancestor).ok().map(Path::to_path_buf)
42}
43
44pub(crate) fn parent(path: &Path) -> Option<&Path> {
45 path.parent()
46}
47
48pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
51 scoped_relative(path).ok()
52}
53
54pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
56 let text = name.to_str()?;
57 (!matches!(text, "" | "." | "..")
58 && !text
59 .bytes()
60 .any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
61 .then_some(text)
62}
63
64pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
67 let invalid = || {
68 io::Error::new(
69 io::ErrorKind::InvalidInput,
70 "Artifact path must be relative to its declared root and use logical names.",
71 )
72 };
73 let text = path.to_str().ok_or_else(invalid)?;
74 if text
75 .split(|character| character == '/' || cfg!(windows) && character == '\\')
76 .any(|part| matches!(part, "." | ".."))
77 {
78 return Err(invalid());
79 }
80 path.components()
81 .map(|component| match component {
82 Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
83 _ => Err(invalid()),
84 })
85 .collect()
86}
87
88pub fn scoped_relative(path: &Path) -> io::Result<String> {
89 relative_names(path).map(relative_text)
90}
91
92pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
95 if path
96 .components()
97 .all(|component| matches!(component, std::path::Component::CurDir))
98 {
99 return Ok(String::new());
100 }
101 relative_names(path).map(relative_text)
102}
103
104pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
106 names
107 .into_iter()
108 .map(|name| name.to_str().expect("validated logical name"))
109 .collect::<Vec<_>>()
110 .join("/")
111}
112
113pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
115 if matches!(text, "" | ".") {
117 return Ok((PathBuf::new(), Vec::new()));
118 }
119 let names = text
120 .split('/')
121 .map(|name| {
122 logical_entry_name(OsStr::new(name))
123 .map(OsString::from)
124 .ok_or_else(|| {
125 io::Error::new(
126 io::ErrorKind::InvalidInput,
127 "Invalid slash path for an Artifact target.",
128 )
129 })
130 })
131 .collect::<io::Result<Vec<_>>>()?;
132 Ok((names.iter().collect(), names))
133}
134
135pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
139 if actual == reserved {
140 return Ok(true);
141 }
142 let Some(name) = EntryName::new(reserved) else {
143 return Ok(false);
144 };
145 match open_entry(parent, &name) {
146 Ok(alias) => {
148 Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
149 }
150 Err(error)
151 if is_link_refusal(&error)
152 || matches!(
153 error.kind(),
154 io::ErrorKind::NotFound
155 | io::ErrorKind::PermissionDenied
156 | io::ErrorKind::InvalidInput
157 ) =>
158 {
159 Ok(false)
160 }
161 Err(error) => Err(error),
162 }
163}
164
165const MAX_DECLARATION_PATH_UNITS: usize = 1024;
167
168pub fn declaration_path(value: &str) -> Result<(), String> {
170 let drive_rooted = value
171 .as_bytes()
172 .first()
173 .is_some_and(u8::is_ascii_alphabetic)
174 && value.as_bytes().get(1) == Some(&b':')
175 && value.as_bytes().get(2) == Some(&b'/');
176 if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
177 || drive_rooted
178 || value
179 .bytes()
180 .any(|byte| byte.is_ascii_control() || byte == b'\\')
181 || value
182 .split('/')
183 .any(|part| part.is_empty() || part == "." || part == "..")
184 {
185 return Err("Execution input must be a safe project-relative path.".into());
186 }
187 Ok(())
188}
189
190#[cfg(test)]
191mod tests;