use std::path::{Path, PathBuf};
use super::command_vars::{KnownVars, expand_leading_variable, literal_assignments_before_each};
use super::shell_allowlist::Separator;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SegmentCwd {
pub segment: String,
pub cwd: Option<PathBuf>,
}
pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
track(command, base).0
}
pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
track(command, base).1
}
struct Pending {
moved: Option<PathBuf>,
old: Option<PathBuf>,
skippable: bool,
fallback: bool,
}
impl Pending {
fn either(self) -> Option<PathBuf> {
merge(self.moved, self.old.as_deref())
}
}
fn track(command: &str, base: Option<&Path>) -> (Vec<SegmentCwd>, Option<PathBuf>) {
let segments = super::shell_allowlist::segments_with_separators(command);
let vars = literal_assignments_before_each(&segments);
let cdpath = std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
|| segments.iter().any(|(s, _)| s.contains("CDPATH"));
let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
let mut list_base = cwd.clone();
let mut pending: Option<Pending> = None;
let mut prev: Option<Separator> = None;
let mut out = Vec::with_capacity(segments.len());
for ((segment, sep), vars) in segments.into_iter().zip(vars) {
let here = cwd.clone();
let mut own = here.clone();
if let Some(p) = pending.take_if(|p| p.fallback) {
cwd = if exits(&segment) && !p.skippable {
p.moved
} else if cd_target(&segment).is_some() || moves_opaquely(&segment) {
None
} else {
p.either()
};
} else if let Some(target) = cd_target(&segment) {
let moved = if cdpath && is_cdpath_candidate(target) {
None
} else {
resolve_cd(here.as_deref(), target, &vars)
};
let old = match pending.take() {
Some(p) => merge(here.clone(), p.old.as_deref()),
None => here.clone(),
};
let runs_unconditionally = matches!(
prev,
None | Some(Separator::Sequence | Separator::Background)
);
if prev == Some(Separator::Pipe) || sep == Some(Separator::Pipe) {
cwd = merge(moved, old.as_deref());
} else if runs_unconditionally && moved.as_deref().is_some_and(Path::is_dir) {
cwd = moved;
} else {
let skippable = prev == Some(Separator::Or);
let p = Pending {
moved,
old,
skippable,
fallback: sep == Some(Separator::Or),
};
cwd = match sep {
Some(Separator::Or) => p.old.clone(),
Some(Separator::Sequence) => merge(p.moved.clone(), p.old.as_deref()),
_ if skippable => merge(p.moved.clone(), p.old.as_deref()),
_ => p.moved.clone(),
};
if matches!(sep, Some(Separator::Or | Separator::And) | None) {
pending = Some(p);
}
}
} else {
if moves_opaquely(&segment) {
own = None;
if !segment.starts_with('(') {
cwd = None;
pending = None;
}
}
if let Some(p) = pending.take() {
match sep {
Some(Separator::And | Separator::Pipe) | None => pending = Some(p),
Some(Separator::Or | Separator::Sequence | Separator::Background) => {
cwd = p.either();
}
}
}
}
out.push(SegmentCwd { segment, cwd: own });
match sep {
Some(Separator::Background) => {
cwd.clone_from(&list_base);
pending = None;
}
Some(Separator::Sequence) => list_base.clone_from(&cwd),
_ => {}
}
prev = sep;
}
(out, cwd)
}
fn merge(a: Option<PathBuf>, b: Option<&Path>) -> Option<PathBuf> {
if a.as_deref() == b { a } else { None }
}
fn exits(segment: &str) -> bool {
matches!(segment.split_whitespace().next(), Some("exit" | "return"))
}
fn is_cdpath_candidate(target: &str) -> bool {
let t = target.trim_matches(['"', '\'']);
!(t.starts_with('/')
|| t.starts_with('~')
|| t.starts_with("./")
|| t.starts_with("../")
|| t == "."
|| t == ".."
|| Path::new(t).is_absolute())
}
fn moves_opaquely(segment: &str) -> bool {
const MOVERS: [&str; 4] = ["cd", "pushd", "popd", "chdir"];
let split_words = |text: &str| -> Vec<String> {
text.split(|c: char| c.is_whitespace() || OPERATORS.contains(c))
.map(str::to_string)
.collect()
};
let mut words = split_words(&blank_quoted(segment));
words.extend(
super::shell_allowlist::shell_tokenize(segment)
.iter()
.flat_map(|token| token.split(|c: char| OPERATORS.contains(c)))
.map(str::to_string),
);
words
.iter()
.any(|w| w == "eval" || MOVERS.contains(&w.as_str()))
}
const OPERATORS: &str = "(){};&|`";
fn blank_quoted(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
let mut chars = segment.chars();
let mut single = false;
let mut double = false;
while let Some(c) = chars.next() {
match c {
'\\' if !single => {
let next = chars.next();
if double {
out.push(' ');
if next.is_some() {
out.push(' ');
}
} else {
out.push(c);
out.extend(next);
}
}
'\'' if !double => {
single = !single;
out.push(' ');
}
'"' if !single => {
double = !double;
out.push(' ');
}
_ if single || double => out.push(' '),
_ => out.push(c),
}
}
out
}
fn cd_target(segment: &str) -> Option<&str> {
let mut words = segment.split_whitespace();
if words.next()? != "cd" {
return None;
}
let target = words.next()?;
if words.next().is_some() {
return None;
}
Some(target)
}
fn resolve_cd(from: Option<&Path>, target: &str, vars: &KnownVars) -> Option<PathBuf> {
let unquoted = target.trim_matches(['"', '\'']);
let expanded;
let unquoted = if unquoted.starts_with('$') && !target.starts_with('\'') {
expanded = expand_leading_variable(unquoted, vars)?;
expanded.as_str()
} else {
unquoted
};
if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
return None;
}
if let Some(rest) = unquoted.strip_prefix('~') {
let home = std::env::var_os("HOME").map(PathBuf::from)?;
return Some(join_in(&home, rest.trim_start_matches('/')));
}
if unquoted.starts_with('/') {
return Some(PathBuf::from(normalize_posix(unquoted)));
}
let path = Path::new(unquoted);
if path.is_absolute() {
return Some(normalize(path));
}
Some(join_in(from?, unquoted))
}
pub fn join_in(base: &Path, rel: &str) -> PathBuf {
let base_str = base.to_string_lossy();
if base_str.starts_with('/') {
return PathBuf::from(normalize_posix(&format!(
"{}/{rel}",
base_str.trim_end_matches('/')
)));
}
normalize(&base.join(rel))
}
fn normalize_posix(path: &str) -> String {
let mut out: Vec<&str> = Vec::new();
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
out.pop();
}
other => out.push(other),
}
}
format!("/{}", out.join("/"))
}
fn normalize(path: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_leading_cd_moves_the_following_segments() {
let segs = segments_with_cwd(
"cd /tmp/work && curl -o x.png http://e/x",
Some(Path::new("/proj")),
);
assert_eq!(
segs.last().unwrap().cwd.as_deref(),
Some(Path::new("/tmp/work"))
);
}
#[test]
fn without_a_cd_every_segment_keeps_the_call_directory() {
let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
assert!(
segs.iter()
.all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
);
}
#[test]
fn a_relative_cd_is_joined_onto_the_call_directory() {
assert_eq!(
final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
Some(PathBuf::from("/proj/sub/dir"))
);
assert_eq!(
final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
Some(PathBuf::from("/proj/side"))
);
}
#[test]
fn an_unresolvable_cd_makes_the_directory_unknown() {
assert_eq!(
final_cwd(
"cd \"$LEAN_CTX_2079_NEVER_SET\" && ls",
Some(Path::new("/proj"))
),
None
);
assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
}
#[test]
fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
assert_eq!(
final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
Some(PathBuf::from("/tmp"))
);
assert_eq!(
final_cwd("cd /private/tmp/session/../session && ls", None),
Some(PathBuf::from("/private/tmp/session"))
);
assert_eq!(
join_in(Path::new("/tmp/work"), "sub/shot.png"),
PathBuf::from("/tmp/work/sub/shot.png"),
"and joins with a forward slash, which the scratch prefixes match on"
);
}
#[test]
fn no_base_and_no_cd_is_unknown() {
assert_eq!(final_cwd("ls -la", None), None);
}
fn cwds(command: &str) -> Vec<Option<PathBuf>> {
segments_with_cwd(command, Some(Path::new("/proj")))
.into_iter()
.map(|s| s.cwd)
.collect()
}
const MISSING: &str = "/lean-ctx-1850-does-not-exist";
#[test]
fn a_cd_segment_runs_in_the_directory_before_it() {
assert_eq!(cwds("cd /tmp && ls")[0], Some(PathBuf::from("/proj")));
}
#[test]
fn a_cd_that_may_fail_does_not_carry_past_a_sequence() {
let got = cwds(&format!("cd {MISSING} && true; echo x"));
assert_eq!(got[1], Some(PathBuf::from(MISSING)), "reached only via &&");
assert_eq!(got[2], None);
}
#[test]
fn a_cd_that_may_be_skipped_leaves_the_directory_unknown() {
assert_eq!(cwds("false && cd /tmp; echo x")[2], None);
assert_eq!(cwds("true || cd /tmp && echo x")[2], None);
assert_eq!(cwds("cd /tmp | cat; echo x")[2], None, "a pipeline element");
}
#[test]
fn a_second_cd_does_not_make_a_failed_first_one_certain() {
assert_eq!(cwds(&format!("cd {MISSING} && cd . ; echo x"))[2], None);
}
#[test]
fn cd_or_exit_leaves_only_the_moved_directory() {
let got = cwds(&format!("cd {MISSING} || exit 1; echo x"));
assert_eq!(got[1], Some(PathBuf::from("/proj")), "the fallback");
assert_eq!(got[2], Some(PathBuf::from(MISSING)));
}
#[test]
fn a_backgrounded_list_does_not_move_what_follows() {
assert_eq!(
cwds("cd /tmp && echo a & echo b")[2],
Some(PathBuf::from("/proj"))
);
}
#[test]
fn opaque_movers_make_the_directory_unknown() {
for command in [
"pushd /tmp && echo x",
"builtin cd /tmp && echo x",
"{ cd /tmp; } && echo x",
] {
assert_eq!(cwds(command).last(), Some(&None), "{command}");
}
let subshell = cwds("(cd /tmp) && echo x");
assert_eq!(subshell[0], None, "its own directory is not followed");
assert_eq!(
subshell[1],
Some(PathBuf::from("/proj")),
"but it cannot move the parent shell"
);
}
#[test]
fn cdpath_makes_a_relative_cd_unknown() {
assert_eq!(cwds("CDPATH=/elsewhere; cd sub && ls")[2], None);
assert_eq!(
cwds("CDPATH=/elsewhere; cd ./sub && ls")[2],
Some(PathBuf::from("/proj/sub")),
"`./` bypasses CDPATH"
);
}
#[test]
fn a_cd_inside_a_quoted_argument_does_not_move_anything() {
for command in [
"printf '%s\\n' 'note: cd /tmp mention' > f.txt",
"cd /proj && printf '| %s | (cd $TMPDIR not followed) |\\n' x >> f.txt",
"echo \"pushd here, popd there, then cd back\" > f.txt",
"echo \"$(cd /tmp; pwd)\" > f.txt",
"echo 'it'\\''s cd' > f.txt",
] {
assert_eq!(
cwds(command).last(),
Some(&Some(PathBuf::from("/proj"))),
"{command}"
);
}
}
#[test]
fn a_quoted_command_name_or_eval_still_moves_the_shell() {
for command in [
"\"cd\" /tmp && echo x",
"c'd' /tmp && echo x",
"\\cd /tmp && echo x",
"builtin 'cd' /tmp && echo x",
"eval 'cd /tmp' && echo x",
"'eval' \"c\"\"d /tmp\" && echo x",
"echo ${ cd /tmp; } && echo x",
] {
assert_eq!(cwds(command).last(), Some(&None), "{command}");
}
}
#[test]
fn a_cd_through_a_known_variable_is_followed() {
assert_eq!(
cwds("D=/tmp && cd $D && echo x").last(),
Some(&Some(PathBuf::from("/tmp")))
);
assert_eq!(
cwds("D=/tmp; cd \"${D}/sub\" && echo x").last(),
Some(&Some(PathBuf::from("/tmp/sub")))
);
assert_eq!(
cwds("D=sub; cd $D && echo x").last(),
Some(&Some(PathBuf::from("/proj/sub"))),
"a relative value is joined like a relative literal"
);
let expected = std::env::var("TMPDIR")
.ok()
.filter(|t| !t.is_empty() && !t.contains(['$', '`']))
.map(|t| resolve_cd(None, &t, &KnownVars::default()));
assert_eq!(
final_cwd("cd $TMPDIR && ls", Some(Path::new("/proj"))),
expected.flatten(),
"$TMPDIR resolves exactly as its value spelled out"
);
}
#[test]
fn a_cd_through_an_unknown_variable_stays_unknown() {
for command in [
"cd $D && echo x",
"true && D=/tmp; cd $D && echo x",
"D=/tmp; read D; cd $D && echo x",
"TMPDIR=$PWD; cd $TMPDIR && echo x",
"unset TMPDIR; cd $TMPDIR && echo x",
"D=/tmp; cd '$D' && echo x",
"D=/tmp; cd $Dx && echo x",
] {
assert_eq!(cwds(command).last(), Some(&None), "{command}");
}
}
}