artifactize_tools/platform/
files.rs1use std::{
4 ffi::{OsStr, OsString},
5 fs::File,
6 io,
7 path::{Component, Path, PathBuf},
8};
9
10mod text;
11use text::native_path_text;
12pub use text::path_from_text;
13
14#[cfg(unix)]
15mod unix;
16#[cfg(windows)]
17mod windows;
18
19#[cfg(unix)]
20pub use unix::{
21 EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
22 open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
23};
24#[cfg(windows)]
25pub use windows::{
26 EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
27 open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
28};
29
30pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
32 first == second
33}
34
35pub fn is_absolute(path: &std::path::Path) -> bool {
37 path.is_absolute()
38}
39
40pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
43 if path.is_absolute() {
44 logical_from_native(&relative_below(root, path)?)
45 } else {
46 logical_from_native(path)
47 }
48}
49
50pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
53 if let Ok(relative) = path.strip_prefix(root) {
54 return Some(relative.to_path_buf());
55 }
56 #[cfg(windows)]
57 {
58 let plain = |path: &Path| windows::plain(path).unwrap_or_else(|| path.to_path_buf());
59 plain(path)
60 .strip_prefix(plain(root))
61 .ok()
62 .map(Path::to_path_buf)
63 }
64 #[cfg(not(windows))]
65 None
66}
67
68pub(crate) fn parent(path: &Path) -> Option<&Path> {
69 path.parent()
70}
71
72pub fn split_root(path: &std::path::Path) -> Option<(&std::path::Path, Vec<&std::ffi::OsStr>)> {
75 use std::path::Component;
76 let root = path.ancestors().last()?;
77 path.components()
78 .filter_map(|component| match component {
79 Component::Prefix(_) | Component::RootDir => None,
80 Component::Normal(name) => Some(Some(name)),
81 Component::CurDir | Component::ParentDir => Some(None),
82 })
83 .collect::<Option<Vec<_>>>()
84 .map(|names| (root, names))
85}
86
87pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
90 std::fs::read_link(path)
91}
92
93pub const ALIASED_NAMES: bool = cfg!(any(windows, target_os = "macos"));
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum FileKind {
100 File,
101 Directory,
102 Symlink,
103 Other,
105}
106
107pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
109 canonicalize(&std::env::current_dir()?)
110}
111
112pub trait PathText {
114 fn path_text(&self) -> String;
115}
116impl<P: AsRef<std::path::Path> + ?Sized> PathText for P {
117 fn path_text(&self) -> String {
118 native_path_text(self.as_ref())
119 }
120}
121pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
123 path.path_text()
124}
125
126pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
129 scoped_relative(path).ok()
130}
131
132pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
134 let text = name.to_str()?;
135 (!matches!(text, "" | "." | "..")
136 && !text
137 .bytes()
138 .any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
139 .then_some(text)
140}
141
142pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
145 let invalid = || {
146 io::Error::new(
147 io::ErrorKind::InvalidInput,
148 "Artifact path must be relative to its declared root and use logical names.",
149 )
150 };
151 let text = path.to_str().ok_or_else(invalid)?;
152 if text
153 .split(|character| character == '/' || cfg!(windows) && character == '\\')
154 .any(|part| matches!(part, "." | ".."))
155 {
156 return Err(invalid());
157 }
158 path.components()
159 .map(|component| match component {
160 Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
161 _ => Err(invalid()),
162 })
163 .collect()
164}
165
166pub fn scoped_relative(path: &Path) -> io::Result<String> {
167 relative_names(path).map(relative_text)
168}
169
170pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
173 if path
174 .components()
175 .all(|component| matches!(component, std::path::Component::CurDir))
176 {
177 return Ok(String::new());
178 }
179 relative_names(path).map(relative_text)
180}
181
182pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
184 names
185 .into_iter()
186 .map(|name| name.to_str().expect("validated logical name"))
187 .collect::<Vec<_>>()
188 .join("/")
189}
190
191pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
193 if matches!(text, "" | ".") {
195 return Ok((PathBuf::new(), Vec::new()));
196 }
197 let names = text
198 .split('/')
199 .map(|name| {
200 logical_entry_name(OsStr::new(name))
201 .map(OsString::from)
202 .ok_or_else(|| {
203 io::Error::new(
204 io::ErrorKind::InvalidInput,
205 "Invalid slash path for an Artifact target.",
206 )
207 })
208 })
209 .collect::<io::Result<Vec<_>>>()?;
210 Ok((names.iter().collect(), names))
211}
212
213pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
217 if actual == reserved {
218 return Ok(true);
219 }
220 let Some(name) = EntryName::new(reserved) else {
221 return Ok(false);
222 };
223 match open_entry(parent, &name) {
224 Ok(alias) => {
226 Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
227 }
228 Err(error)
229 if is_link_refusal(&error)
230 || matches!(
231 error.kind(),
232 io::ErrorKind::NotFound
233 | io::ErrorKind::PermissionDenied
234 | io::ErrorKind::InvalidInput
235 ) =>
236 {
237 Ok(false)
238 }
239 Err(error) => Err(error),
240 }
241}
242
243const MAX_DECLARATION_PATH_UNITS: usize = 1024;
245
246pub fn declaration_path(value: &str) -> Result<(), String> {
248 let drive_rooted = value
249 .as_bytes()
250 .first()
251 .is_some_and(u8::is_ascii_alphabetic)
252 && value.as_bytes().get(1) == Some(&b':')
253 && value.as_bytes().get(2) == Some(&b'/');
254 if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
255 || drive_rooted
256 || value
257 .bytes()
258 .any(|byte| byte.is_ascii_control() || byte == b'\\')
259 || value
260 .split('/')
261 .any(|part| part.is_empty() || part == "." || part == "..")
262 {
263 return Err("Execution input must be a safe project-relative path.".into());
264 }
265 Ok(())
266}
267
268#[cfg(test)]
269mod tests {
270 use super::path_text;
271
272 #[cfg(unix)]
274 #[test]
275 fn literal_backslash_in_a_file_name_is_not_a_separator() {
276 let root = crate::test_os::tempdir();
277 let path = crate::test_os::file_with_backslash(root.path());
278 assert_eq!(
279 path_text(std::path::Path::new(path.file_name().unwrap())),
280 r"input\name"
281 );
282 }
283
284 #[cfg(windows)]
286 #[test]
287 fn pinned_owners_refuse_drive_relative_and_rooted_paths() {
288 use crate::scope::Target;
289 for path in [r"C:owner", r"\owner"] {
290 assert!(
291 Target::try_from(path)
292 .unwrap_err()
293 .to_string()
294 .contains("relative to its declared root")
295 );
296 }
297 }
298
299 #[cfg(windows)]
301 #[test]
302 fn a_pin_with_a_win32_alias_is_not_returned_as_an_ordinary_path() {
303 use crate::scope::{open_scoped, scoped_path};
304 let root = crate::test_os::tempdir();
305 let root = crate::test_os::trailing_dot_alias(root.path());
306 assert!(open_scoped(&root, "literal.").is_ok());
307 assert!(
308 scoped_path(&root, std::path::Path::new("literal."))
309 .unwrap_err()
310 .to_string()
311 .contains("ordinary Windows path")
312 );
313 }
314
315 #[cfg(windows)]
317 #[test]
318 fn native_separators_are_rendered_as_slashes() {
319 assert_eq!(
320 path_text(std::path::Path::new(r"C:\input\name")),
321 "C:/input/name"
322 );
323 }
324
325 #[cfg(windows)]
327 #[test]
328 fn verbatim_paths_render_without_the_native_prefix() {
329 assert_eq!(
330 path_text(std::path::Path::new(r"\\?\C:\input\name")),
331 "C:/input/name"
332 );
333 assert_eq!(
334 path_text(std::path::Path::new(r"\\?\UNC\server\share\input")),
335 "//server/share/input"
336 );
337 }
338}