use std::{
ffi::OsStr,
path::{Component, Path, PathBuf},
};
use bstr::{BStr, BString, ByteSlice};
use gix_error::{ErrorExt, ExnMessageResult, validation};
use crate::Stack;
pub trait ToNormalPathComponents {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>>;
}
impl ToNormalPathComponents for &Path {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>> {
self.components().map(|c| component_to_os_str(c, self.display()))
}
}
impl ToNormalPathComponents for PathBuf {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>> {
self.components().map(|c| component_to_os_str(c, self.display()))
}
}
fn component_to_os_str(
component: Component<'_>,
path_with_component: impl std::fmt::Display,
) -> ExnMessageResult<&OsStr> {
match component {
Component::Normal(os_str) => Ok(os_str),
_ => Err(validation(format!(
"Input path \"{path_with_component}\" contains relative or absolute components"
))
.raise()),
}
}
impl ToNormalPathComponents for &BStr {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>> {
self.split(|b| *b == b'/')
.filter_map(|c| bytes_component_to_os_str(c, self))
}
}
impl ToNormalPathComponents for &str {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>> {
self.split('/')
.filter_map(|c| bytes_component_to_os_str(c.as_bytes(), (*self).into()))
}
}
impl ToNormalPathComponents for &BString {
fn to_normal_path_components(&self) -> impl Iterator<Item = ExnMessageResult<&OsStr>> {
self.split(|b| *b == b'/')
.filter_map(|c| bytes_component_to_os_str(c, self.as_bstr()))
}
}
fn bytes_component_to_os_str<'a>(component: &'a [u8], path: &BStr) -> Option<ExnMessageResult<&'a OsStr>> {
if component.is_empty() {
return None;
}
let component = match gix_path::try_from_byte_slice(component.as_bstr()) {
Ok(c) => c,
Err(err) => return Some(Err(err)),
};
let component = component.components().next()?;
Some(component_to_os_str(component, path))
}
impl Stack {
pub fn root(&self) -> &Path {
&self.root
}
pub fn current(&self) -> &Path {
&self.current
}
pub fn current_relative(&self) -> &Path {
&self.current_relative
}
}
pub trait Delegate {
fn push_directory(&mut self, stack: &Stack) -> std::io::Result<()>;
fn push(&mut self, is_last_component: bool, stack: &Stack) -> std::io::Result<()>;
fn pop_directory(&mut self);
}
impl Stack {
pub fn new(root: PathBuf) -> Self {
Stack {
current: root.clone(),
current_relative: PathBuf::with_capacity(128),
valid_components: 0,
root,
current_is_directory: true,
}
}
pub fn make_relative_path_current(
&mut self,
relative: impl ToNormalPathComponents,
delegate: &mut dyn Delegate,
) -> std::io::Result<()> {
let mut components = relative.to_normal_path_components().peekable();
if self.valid_components != 0 && components.peek().is_none() {
return Err(std::io::Error::other("empty inputs are not allowed"));
}
if self.valid_components == 0 {
delegate.push_directory(self)?;
}
let mut existing_components = self.current_relative.components();
let mut matching_components = 0;
while let (Some(existing_comp), Some(new_comp)) = (existing_components.next(), components.peek()) {
match new_comp {
Ok(new_comp) => {
if existing_comp.as_os_str() == *new_comp {
components.next();
matching_components += 1;
} else {
break;
}
}
Err(_) => {
let err = components.next().expect("just peeked").expect_err("peeked an error");
return Err(std::io::Error::other(err.into_error()));
}
}
}
for _ in 0..self.valid_components - matching_components {
self.current.pop();
self.current_relative.pop();
if self.current_is_directory {
delegate.pop_directory();
}
self.current_is_directory = true;
}
self.valid_components = matching_components;
if matching_components != 0 && components.peek().is_none() {
if self.current_is_directory {
delegate.pop_directory();
self.current_is_directory = false;
}
return delegate.push(true, self);
}
if !self.current_is_directory && components.peek().is_some() {
delegate.push(false, self)?;
self.current_is_directory = true;
if let Err(err) = delegate.push_directory(self) {
self.current_is_directory = false;
return Err(err);
}
}
while let Some(comp) = components.next() {
let comp = comp.map_err(|err| std::io::Error::other(err.into_error()))?;
let is_last_component = components.peek().is_none();
let parent_is_directory = self.current_is_directory;
self.current_is_directory = !is_last_component;
self.current.push(comp);
self.current_relative.push(comp);
self.valid_components += 1;
let res = delegate.push(is_last_component, self);
if let Err(err) = res {
self.current.pop();
self.current_relative.pop();
self.valid_components -= 1;
self.current_is_directory = parent_is_directory;
return Err(err);
}
if self.current_is_directory
&& let Err(err) = delegate.push_directory(self)
{
self.current.pop();
self.current_relative.pop();
self.valid_components -= 1;
self.current_is_directory = parent_is_directory;
return Err(err);
}
}
Ok(())
}
}