use super::{Cmd, Pipeline};
pub(super) fn cd_target(pipeline: &Pipeline) -> Option<(String, bool)> {
let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
return None;
};
if s.words.first()?.eval() != "cd" {
return None;
}
let mut physical = false;
let mut args = s.words.iter().skip(1).map(super::Word::eval);
let mut target = None;
for arg in &mut args {
if arg == "--" {
target = args.next();
break;
}
if let Some(flags) = arg.strip_prefix('-') {
if flags.is_empty() || !flags.chars().all(|c| matches!(c, 'L' | 'P' | 'e' | '@')) {
return None;
}
for c in flags.chars() {
match c {
'L' => physical = false,
'P' => physical = true,
_ => {}
}
}
continue;
}
target = Some(arg);
break;
}
if args.next().is_some() {
return None;
}
let target = target?;
let prefixed = s.env.iter().any(|(name, _)| name == "CDPATH" || name == "cdpath");
(!searches_cdpath(&target, prefixed || cdpath_in_scope())).then_some((target, physical))
}
fn cdpath_in_scope() -> bool {
crate::pathctx::expand_vars("$CDPATH", false) != "$CDPATH"
|| crate::pathctx::expand_vars("$cdpath", false) != "$cdpath"
|| std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
}
fn searches_cdpath(target: &str, cdpath_set: bool) -> bool {
let anchored =
target.starts_with(['/', '~']) || target == "." || target == ".." || target.starts_with("./") || target.starts_with("../");
cdpath_set && !anchored
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
proptest! {
#[test]
fn cdpath_redirects_only_an_unanchored_name(name in "[a-z][a-z0-9_.-]{0,8}", prefix in prop::sample::select(vec!["", "/", "~/", "./", "../"])) {
let target = format!("{prefix}{name}");
prop_assert!(!searches_cdpath(&target, false), "{target} without CDPATH");
prop_assert_eq!(searches_cdpath(&target, true), prefix.is_empty(), "{}", target);
}
}
#[test]
fn the_dot_directories_never_search_cdpath() {
for target in [".", "..", "./", "../x"] {
assert!(!searches_cdpath(target, true), "{target}");
}
assert!(searches_cdpath("$X", true), "an unexpanded target fails closed");
}
}