use std::path::{Component, Path, PathBuf};
use crate::config::Config;
use super::process::calling_process;
pub fn absolute_path(relative_path: &str, config: &Config) -> Option<PathBuf> {
match (
&config.cwd_of_delta_process,
&config.cwd_of_user_shell_process,
calling_process().paths_in_input_are_relative_to_cwd() || config.relative_paths,
) {
(Some(cwd_of_delta_process), _, false) => Some(cwd_of_delta_process.join(relative_path)),
(_, Some(cwd_of_user_shell_process), true) => {
Some(cwd_of_user_shell_process.join(relative_path))
}
(Some(cwd_of_delta_process), None, true) => {
Some(cwd_of_delta_process.join(relative_path))
}
_ => None,
}
.map(normalize_path)
}
#[allow(clippy::needless_borrows_for_generic_args)] pub fn relativize_path_maybe(path: &mut String, config: &Config) {
let mut inner_relativize = || -> Option<()> {
let base = config.cwd_relative_to_repo_root.as_deref()?;
let relative_path = pathdiff::diff_paths(&path, base)?;
if relative_path.is_relative() {
#[cfg(target_os = "windows")]
if relative_path.starts_with(Path::new(r"\")) {
return None;
}
*path = relative_path.to_string_lossy().into_owned();
}
Some(())
};
if config.relative_paths && !calling_process().paths_in_input_are_relative_to_cwd() {
let _ = inner_relativize();
}
}
pub fn cwd_of_user_shell_process(
cwd_of_delta_process: Option<&PathBuf>,
cwd_relative_to_repo_root: Option<&str>,
) -> Option<PathBuf> {
match (cwd_of_delta_process, cwd_relative_to_repo_root) {
(Some(cwd), None) => {
Some(PathBuf::from(cwd))
}
(Some(repo_root), Some(cwd_relative_to_repo_root)) => {
Some(PathBuf::from(repo_root).join(cwd_relative_to_repo_root))
}
(None, _) => {
None
}
}
}
fn normalize_path<P>(path: P) -> PathBuf
where
P: AsRef<Path>,
{
let mut components = path.as_ref().components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
#[cfg(test)]
pub fn fake_delta_cwd_for_tests() -> PathBuf {
#[cfg(not(target_os = "windows"))]
{
PathBuf::from("/fake/delta/cwd")
}
#[cfg(target_os = "windows")]
{
PathBuf::from(r"C:\fake\delta\cwd")
}
}