use std::{
ffi::{OsStr, OsString},
fs::File,
io,
path::{Component, Path, PathBuf},
};
mod text;
use text::native_path_text;
pub use text::path_from_text;
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(unix)]
pub use unix::{
EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
};
#[cfg(windows)]
pub use windows::{
EntryName, canonicalize, case_sensitive, entry_kind, exact_name, is_link_refusal,
open_directory, open_entry, open_no_follow, open_nonblocking, read_dir, verified_path,
};
pub(crate) fn paths_equal(first: &Path, second: &Path) -> bool {
first == second
}
pub fn is_absolute(path: &std::path::Path) -> bool {
path.is_absolute()
}
pub fn logical_below(root: &Path, path: &Path) -> Option<String> {
if path.is_absolute() {
logical_from_native(&relative_below(root, path)?)
} else {
logical_from_native(path)
}
}
pub(crate) fn relative_below(root: &Path, path: &Path) -> Option<PathBuf> {
if let Ok(relative) = path.strip_prefix(root) {
return Some(relative.to_path_buf());
}
#[cfg(windows)]
{
let plain = |path: &Path| windows::plain(path).unwrap_or_else(|| path.to_path_buf());
plain(path)
.strip_prefix(plain(root))
.ok()
.map(Path::to_path_buf)
}
#[cfg(not(windows))]
None
}
pub(crate) fn parent(path: &Path) -> Option<&Path> {
path.parent()
}
pub fn split_root(path: &std::path::Path) -> Option<(&std::path::Path, Vec<&std::ffi::OsStr>)> {
use std::path::Component;
let root = path.ancestors().last()?;
path.components()
.filter_map(|component| match component {
Component::Prefix(_) | Component::RootDir => None,
Component::Normal(name) => Some(Some(name)),
Component::CurDir | Component::ParentDir => Some(None),
})
.collect::<Option<Vec<_>>>()
.map(|names| (root, names))
}
pub fn link_target(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
std::fs::read_link(path)
}
pub const ALIASED_NAMES: bool = cfg!(any(windows, target_os = "macos"));
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
File,
Directory,
Symlink,
Other,
}
pub fn current_directory() -> std::io::Result<std::path::PathBuf> {
canonicalize(&std::env::current_dir()?)
}
pub trait PathText {
fn path_text(&self) -> String;
}
impl<P: AsRef<std::path::Path> + ?Sized> PathText for P {
fn path_text(&self) -> String {
native_path_text(self.as_ref())
}
}
pub fn path_text<P: PathText + ?Sized>(path: &P) -> String {
path.path_text()
}
pub fn logical_from_native(path: &std::path::Path) -> Option<String> {
scoped_relative(path).ok()
}
pub(crate) fn logical_entry_name(name: &OsStr) -> Option<&str> {
let text = name.to_str()?;
(!matches!(text, "" | "." | "..")
&& !text
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'/' | b'\\' | b':')))
.then_some(text)
}
pub(crate) fn relative_names(path: &Path) -> io::Result<Vec<&OsStr>> {
let invalid = || {
io::Error::new(
io::ErrorKind::InvalidInput,
"Artifact path must be relative to its declared root and use logical names.",
)
};
let text = path.to_str().ok_or_else(invalid)?;
if text
.split(|character| character == '/' || cfg!(windows) && character == '\\')
.any(|part| matches!(part, "." | ".."))
{
return Err(invalid());
}
path.components()
.map(|component| match component {
Component::Normal(name) if logical_entry_name(name).is_some() => Ok(name),
_ => Err(invalid()),
})
.collect()
}
pub fn scoped_relative(path: &Path) -> io::Result<String> {
relative_names(path).map(relative_text)
}
pub(crate) fn relative_text_of(path: &Path) -> io::Result<String> {
if path
.components()
.all(|component| matches!(component, std::path::Component::CurDir))
{
return Ok(String::new());
}
relative_names(path).map(relative_text)
}
pub(crate) fn relative_text<'a>(names: impl IntoIterator<Item = &'a OsStr>) -> String {
names
.into_iter()
.map(|name| name.to_str().expect("validated logical name"))
.collect::<Vec<_>>()
.join("/")
}
pub(crate) fn parse_target_path(text: &str) -> io::Result<(PathBuf, Vec<OsString>)> {
if matches!(text, "" | ".") {
return Ok((PathBuf::new(), Vec::new()));
}
let names = text
.split('/')
.map(|name| {
logical_entry_name(OsStr::new(name))
.map(OsString::from)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid slash path for an Artifact target.",
)
})
})
.collect::<io::Result<Vec<_>>>()?;
Ok((names.iter().collect(), names))
}
pub(crate) fn same_entry_name(parent: &File, actual: &OsStr, reserved: &OsStr) -> io::Result<bool> {
if actual == reserved {
return Ok(true);
}
let Some(name) = EntryName::new(reserved) else {
return Ok(false);
};
match open_entry(parent, &name) {
Ok(alias) => {
Ok(!exact_name(parent, &alias, reserved)? && exact_name(parent, &alias, actual)?)
}
Err(error)
if is_link_refusal(&error)
|| matches!(
error.kind(),
io::ErrorKind::NotFound
| io::ErrorKind::PermissionDenied
| io::ErrorKind::InvalidInput
) =>
{
Ok(false)
}
Err(error) => Err(error),
}
}
const MAX_DECLARATION_PATH_UNITS: usize = 1024;
pub fn declaration_path(value: &str) -> Result<(), String> {
let drive_rooted = value
.as_bytes()
.first()
.is_some_and(u8::is_ascii_alphabetic)
&& value.as_bytes().get(1) == Some(&b':')
&& value.as_bytes().get(2) == Some(&b'/');
if value.encode_utf16().count() > MAX_DECLARATION_PATH_UNITS
|| drive_rooted
|| value
.bytes()
.any(|byte| byte.is_ascii_control() || byte == b'\\')
|| value
.split('/')
.any(|part| part.is_empty() || part == "." || part == "..")
{
return Err("Execution input must be a safe project-relative path.".into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::path_text;
#[cfg(unix)]
#[test]
fn literal_backslash_in_a_file_name_is_not_a_separator() {
let root = crate::test_os::tempdir();
let path = crate::test_os::file_with_backslash(root.path());
assert_eq!(
path_text(std::path::Path::new(path.file_name().unwrap())),
r"input\name"
);
}
#[cfg(windows)]
#[test]
fn pinned_owners_refuse_drive_relative_and_rooted_paths() {
use crate::scope::Target;
for path in [r"C:owner", r"\owner"] {
assert!(
Target::try_from(path)
.unwrap_err()
.to_string()
.contains("relative to its declared root")
);
}
}
#[cfg(windows)]
#[test]
fn a_pin_with_a_win32_alias_is_not_returned_as_an_ordinary_path() {
use crate::scope::{open_scoped, scoped_path};
let root = crate::test_os::tempdir();
let root = crate::test_os::trailing_dot_alias(root.path());
assert!(open_scoped(&root, "literal.").is_ok());
assert!(
scoped_path(&root, std::path::Path::new("literal."))
.unwrap_err()
.to_string()
.contains("ordinary Windows path")
);
}
#[cfg(windows)]
#[test]
fn native_separators_are_rendered_as_slashes() {
assert_eq!(
path_text(std::path::Path::new(r"C:\input\name")),
"C:/input/name"
);
}
#[cfg(windows)]
#[test]
fn verbatim_paths_render_without_the_native_prefix() {
assert_eq!(
path_text(std::path::Path::new(r"\\?\C:\input\name")),
"C:/input/name"
);
assert_eq!(
path_text(std::path::Path::new(r"\\?\UNC\server\share\input")),
"//server/share/input"
);
}
}