use std::{
borrow::Cow,
path::{Component, Path, PathBuf},
};
use crate::errors::{ERROR_PATH_DENIED, PathValidationError};
#[derive(Debug, Clone)]
pub(crate) struct ValidatedToolPath {
anchored: Option<PathBuf>,
pub(crate) components: Vec<String>,
pub(crate) display: String,
}
impl ValidatedToolPath {
pub(super) fn anchors<'a>(
&'a self,
roots: impl IntoIterator<Item = &'a PathBuf>,
) -> Vec<(PathBuf, &'a [String])> {
match self.anchored.as_ref() {
Some(anchor) => vec![(anchor.clone(), self.components.as_slice())],
None => roots
.into_iter()
.map(|root| (root.clone(), self.components.as_slice()))
.collect(),
}
}
#[must_use]
pub(crate) fn denies_symlinks(&self) -> bool {
self.anchored.is_none()
}
#[must_use]
pub(crate) fn relative_spelling(&self) -> Option<&str> {
self.anchored.is_none().then_some(self.display.as_str())
}
}
pub(crate) fn validate_workspace_path_argument(
raw_path: &str,
workspace_root: &Path,
) -> Result<ValidatedToolPath, PathValidationError> {
if raw_path.is_empty() {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must not be empty",
None,
));
}
if raw_path.chars().any(char::is_control) {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must not contain control characters",
None,
));
}
let requested = Path::new(raw_path);
let (anchored, relative_text, clamp) = if requested.is_absolute() {
match strip_workspace_root(requested, workspace_root)? {
Some(stripped) => (None, Cow::Owned(stripped), false),
None => {
let (anchor, remainder) = split_filesystem_root(requested)?;
(Some(anchor), Cow::Owned(remainder), true)
}
}
} else {
(None, Cow::Borrowed(raw_path), false)
};
let reported = |text: &str| -> String {
match anchored.as_ref() {
Some(anchor) => anchor
.join(text)
.to_str()
.map_or_else(|| text.to_owned(), str::to_owned),
None => text.to_owned(),
}
};
let mut components: Vec<String> = Vec::new();
for component in Path::new(relative_text.as_ref()).components() {
match component {
Component::Normal(value) => {
let Some(value) = value.to_str() else {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path component must be UTF-8",
None,
));
};
components.push(value.to_owned());
}
Component::CurDir => {}
Component::ParentDir => match components.last() {
Some(last) if last == ".." => components.push("..".to_owned()),
Some(_) => {
components.pop();
}
None if clamp => {}
None => components.push("..".to_owned()),
},
Component::RootDir | Component::Prefix(_) => {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must be relative to a workspace root or absolute",
None,
));
}
}
}
let display = if components.is_empty() && anchored.is_none() {
".".to_owned()
} else {
reported(&components.join("/"))
};
Ok(ValidatedToolPath {
anchored,
components,
display,
})
}
fn strip_workspace_root(
requested: &Path,
workspace_root: &Path,
) -> Result<Option<String>, PathValidationError> {
let requested = merry_core::host_paths::simplify_verbatim_path(requested);
let workspace_root = merry_core::host_paths::simplify_verbatim_path(workspace_root);
let stripped = if let Ok(stripped) = requested.strip_prefix(&workspace_root) {
Some(stripped.to_path_buf())
} else {
#[cfg(windows)]
{
strip_prefix_case_insensitive(&requested, &workspace_root)
}
#[cfg(not(windows))]
{
None
}
};
let Some(stripped) = stripped else {
return Ok(None);
};
let Some(stripped) = stripped.to_str() else {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must be UTF-8",
None,
));
};
if stripped.is_empty() {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must name a file inside the workspace root, not the root itself",
None,
));
}
Ok(Some(stripped.to_owned()))
}
#[cfg(windows)]
fn strip_prefix_case_insensitive(path: &Path, root: &Path) -> Option<PathBuf> {
let mut path_components = path.components();
for root_component in root.components() {
let candidate = path_components.next()?;
let same = match (candidate, root_component) {
(Component::RootDir, Component::RootDir) => true,
(Component::Prefix(a), Component::Prefix(b)) => a
.as_os_str()
.to_str()
.zip(b.as_os_str().to_str())
.is_some_and(|(lhs, rhs)| lhs.eq_ignore_ascii_case(rhs)),
(Component::Normal(a), Component::Normal(b)) => a
.to_str()
.zip(b.to_str())
.is_some_and(|(lhs, rhs)| lhs.eq_ignore_ascii_case(rhs)),
_ => candidate == root_component,
};
if !same {
return None;
}
}
let mut remainder = PathBuf::new();
for component in path_components {
remainder.push(component.as_os_str());
}
Some(remainder)
}
fn split_filesystem_root(requested: &Path) -> Result<(PathBuf, String), PathValidationError> {
let mut anchor = PathBuf::new();
let mut remainder = Vec::new();
for component in requested.components() {
match component {
Component::Prefix(_) | Component::RootDir => anchor.push(component.as_os_str()),
Component::Normal(value) => {
let Some(value) = value.to_str() else {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path component must be UTF-8",
None,
));
};
remainder.push(value.to_owned());
}
Component::CurDir => {}
Component::ParentDir => {
remainder.pop();
}
}
}
if remainder.is_empty() {
return Err(PathValidationError::new(
ERROR_PATH_DENIED,
"workspace path must name a file, not a filesystem root",
None,
));
}
Ok((anchor, remainder.join("/")))
}