1use std::path::{Path, PathBuf};
27
28use super::command_vars::{KnownVars, expand_leading_variable, literal_assignments_before_each};
29use super::shell_allowlist::Separator;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SegmentCwd {
34 pub segment: String,
35 pub cwd: Option<PathBuf>,
38}
39
40pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
45 track(command, base).0
46}
47
48pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
50 track(command, base).1
51}
52
53struct Pending {
58 moved: Option<PathBuf>,
59 old: Option<PathBuf>,
61 skippable: bool,
63 fallback: bool,
66}
67
68impl Pending {
69 fn either(self) -> Option<PathBuf> {
70 merge(self.moved, self.old.as_deref())
71 }
72}
73
74fn track(command: &str, base: Option<&Path>) -> (Vec<SegmentCwd>, Option<PathBuf>) {
75 let segments = super::shell_allowlist::segments_with_separators(command);
76 let vars = literal_assignments_before_each(&segments);
77 let cdpath = std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
79 || segments.iter().any(|(s, _)| s.contains("CDPATH"));
80
81 let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
83 let mut list_base = cwd.clone();
86 let mut pending: Option<Pending> = None;
87 let mut prev: Option<Separator> = None;
88 let mut out = Vec::with_capacity(segments.len());
89
90 for ((segment, sep), vars) in segments.into_iter().zip(vars) {
91 let here = cwd.clone();
94 let mut own = here.clone();
95
96 if let Some(p) = pending.take_if(|p| p.fallback) {
97 cwd = if exits(&segment) && !p.skippable {
101 p.moved
102 } else if cd_target(&segment).is_some() || moves_opaquely(&segment) {
103 None
104 } else {
105 p.either()
106 };
107 } else if let Some(target) = cd_target(&segment) {
108 let moved = if cdpath && is_cdpath_candidate(target) {
109 None
110 } else {
111 resolve_cd(here.as_deref(), target, &vars)
112 };
113 let old = match pending.take() {
116 Some(p) => merge(here.clone(), p.old.as_deref()),
117 None => here.clone(),
118 };
119 let runs_unconditionally = matches!(
120 prev,
121 None | Some(Separator::Sequence | Separator::Background)
122 );
123 if prev == Some(Separator::Pipe) || sep == Some(Separator::Pipe) {
124 cwd = merge(moved, old.as_deref());
127 } else if runs_unconditionally && moved.as_deref().is_some_and(Path::is_dir) {
128 cwd = moved;
130 } else {
131 let skippable = prev == Some(Separator::Or);
132 let p = Pending {
133 moved,
134 old,
135 skippable,
136 fallback: sep == Some(Separator::Or),
137 };
138 cwd = match sep {
139 Some(Separator::Or) => p.old.clone(),
140 Some(Separator::Sequence) => merge(p.moved.clone(), p.old.as_deref()),
141 _ if skippable => merge(p.moved.clone(), p.old.as_deref()),
142 _ => p.moved.clone(),
143 };
144 if matches!(sep, Some(Separator::Or | Separator::And) | None) {
145 pending = Some(p);
146 }
147 }
148 } else {
149 if moves_opaquely(&segment) {
150 own = None;
151 if !segment.starts_with('(') {
154 cwd = None;
155 pending = None;
156 }
157 }
158 if let Some(p) = pending.take() {
161 match sep {
162 Some(Separator::And | Separator::Pipe) | None => pending = Some(p),
163 Some(Separator::Or | Separator::Sequence | Separator::Background) => {
164 cwd = p.either();
165 }
166 }
167 }
168 }
169
170 out.push(SegmentCwd { segment, cwd: own });
171 match sep {
172 Some(Separator::Background) => {
173 cwd.clone_from(&list_base);
174 pending = None;
175 }
176 Some(Separator::Sequence) => list_base.clone_from(&cwd),
177 _ => {}
178 }
179 prev = sep;
180 }
181 (out, cwd)
182}
183
184fn merge(a: Option<PathBuf>, b: Option<&Path>) -> Option<PathBuf> {
186 if a.as_deref() == b { a } else { None }
187}
188
189fn exits(segment: &str) -> bool {
191 matches!(segment.split_whitespace().next(), Some("exit" | "return"))
192}
193
194fn is_cdpath_candidate(target: &str) -> bool {
196 let t = target.trim_matches(['"', '\'']);
197 !(t.starts_with('/')
198 || t.starts_with('~')
199 || t.starts_with("./")
200 || t.starts_with("../")
201 || t == "."
202 || t == ".."
203 || Path::new(t).is_absolute())
204}
205
206fn moves_opaquely(segment: &str) -> bool {
223 const MOVERS: [&str; 4] = ["cd", "pushd", "popd", "chdir"];
224 let split_words = |text: &str| -> Vec<String> {
225 text.split(|c: char| c.is_whitespace() || OPERATORS.contains(c))
226 .map(str::to_string)
227 .collect()
228 };
229 let mut words = split_words(&blank_quoted(segment));
230 words.extend(
231 super::shell_allowlist::shell_tokenize(segment)
232 .iter()
233 .flat_map(|token| token.split(|c: char| OPERATORS.contains(c)))
234 .map(str::to_string),
235 );
236 words
237 .iter()
238 .any(|w| w == "eval" || MOVERS.contains(&w.as_str()))
239}
240
241const OPERATORS: &str = "(){};&|`";
243
244fn blank_quoted(segment: &str) -> String {
248 let mut out = String::with_capacity(segment.len());
249 let mut chars = segment.chars();
250 let mut single = false;
251 let mut double = false;
252 while let Some(c) = chars.next() {
253 match c {
254 '\\' if !single => {
255 let next = chars.next();
257 if double {
258 out.push(' ');
259 if next.is_some() {
260 out.push(' ');
261 }
262 } else {
263 out.push(c);
264 out.extend(next);
265 }
266 }
267 '\'' if !double => {
268 single = !single;
269 out.push(' ');
270 }
271 '"' if !single => {
272 double = !double;
273 out.push(' ');
274 }
275 _ if single || double => out.push(' '),
276 _ => out.push(c),
277 }
278 }
279 out
280}
281
282fn cd_target(segment: &str) -> Option<&str> {
284 let mut words = segment.split_whitespace();
285 if words.next()? != "cd" {
286 return None;
287 }
288 let target = words.next()?;
289 if words.next().is_some() {
290 return None;
292 }
293 Some(target)
294}
295
296fn resolve_cd(from: Option<&Path>, target: &str, vars: &KnownVars) -> Option<PathBuf> {
306 let unquoted = target.trim_matches(['"', '\'']);
307 let expanded;
308 let unquoted = if unquoted.starts_with('$') && !target.starts_with('\'') {
309 expanded = expand_leading_variable(unquoted, vars)?;
310 expanded.as_str()
311 } else {
312 unquoted
313 };
314 if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
315 return None;
316 }
317 if let Some(rest) = unquoted.strip_prefix('~') {
319 let home = std::env::var_os("HOME").map(PathBuf::from)?;
320 return Some(join_in(&home, rest.trim_start_matches('/')));
321 }
322 if unquoted.starts_with('/') {
329 return Some(PathBuf::from(normalize_posix(unquoted)));
330 }
331 let path = Path::new(unquoted);
332 if path.is_absolute() {
333 return Some(normalize(path));
334 }
335 Some(join_in(from?, unquoted))
336}
337
338pub fn join_in(base: &Path, rel: &str) -> PathBuf {
343 let base_str = base.to_string_lossy();
344 if base_str.starts_with('/') {
345 return PathBuf::from(normalize_posix(&format!(
346 "{}/{rel}",
347 base_str.trim_end_matches('/')
348 )));
349 }
350 normalize(&base.join(rel))
351}
352
353fn normalize_posix(path: &str) -> String {
355 let mut out: Vec<&str> = Vec::new();
356 for part in path.split('/') {
357 match part {
358 "" | "." => {}
359 ".." => {
360 out.pop();
361 }
362 other => out.push(other),
363 }
364 }
365 format!("/{}", out.join("/"))
366}
367
368fn normalize(path: &Path) -> PathBuf {
371 use std::path::Component;
372 let mut out = PathBuf::new();
373 for component in path.components() {
374 match component {
375 Component::CurDir => {}
376 Component::ParentDir => {
377 out.pop();
378 }
379 other => out.push(other),
380 }
381 }
382 out
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 #[test]
390 fn a_leading_cd_moves_the_following_segments() {
391 let segs = segments_with_cwd(
392 "cd /tmp/work && curl -o x.png http://e/x",
393 Some(Path::new("/proj")),
394 );
395 assert_eq!(
396 segs.last().unwrap().cwd.as_deref(),
397 Some(Path::new("/tmp/work"))
398 );
399 }
400
401 #[test]
402 fn without_a_cd_every_segment_keeps_the_call_directory() {
403 let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
404 assert!(
405 segs.iter()
406 .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
407 );
408 }
409
410 #[test]
411 fn a_relative_cd_is_joined_onto_the_call_directory() {
412 assert_eq!(
413 final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
414 Some(PathBuf::from("/proj/sub/dir"))
415 );
416 assert_eq!(
417 final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
418 Some(PathBuf::from("/proj/side"))
419 );
420 }
421
422 #[test]
426 fn an_unresolvable_cd_makes_the_directory_unknown() {
427 assert_eq!(
428 final_cwd(
429 "cd \"$LEAN_CTX_2079_NEVER_SET\" && ls",
430 Some(Path::new("/proj"))
431 ),
432 None
433 );
434 assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
435 }
436
437 #[test]
441 fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
442 assert_eq!(
443 final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
444 Some(PathBuf::from("/tmp"))
445 );
446 assert_eq!(
447 final_cwd("cd /private/tmp/session/../session && ls", None),
448 Some(PathBuf::from("/private/tmp/session"))
449 );
450 assert_eq!(
451 join_in(Path::new("/tmp/work"), "sub/shot.png"),
452 PathBuf::from("/tmp/work/sub/shot.png"),
453 "and joins with a forward slash, which the scratch prefixes match on"
454 );
455 }
456
457 #[test]
458 fn no_base_and_no_cd_is_unknown() {
459 assert_eq!(final_cwd("ls -la", None), None);
460 }
461
462 fn cwds(command: &str) -> Vec<Option<PathBuf>> {
463 segments_with_cwd(command, Some(Path::new("/proj")))
464 .into_iter()
465 .map(|s| s.cwd)
466 .collect()
467 }
468
469 const MISSING: &str = "/lean-ctx-1850-does-not-exist";
470
471 #[test]
473 fn a_cd_segment_runs_in_the_directory_before_it() {
474 assert_eq!(cwds("cd /tmp && ls")[0], Some(PathBuf::from("/proj")));
475 }
476
477 #[test]
480 fn a_cd_that_may_fail_does_not_carry_past_a_sequence() {
481 let got = cwds(&format!("cd {MISSING} && true; echo x"));
482 assert_eq!(got[1], Some(PathBuf::from(MISSING)), "reached only via &&");
483 assert_eq!(got[2], None);
484 }
485
486 #[test]
487 fn a_cd_that_may_be_skipped_leaves_the_directory_unknown() {
488 assert_eq!(cwds("false && cd /tmp; echo x")[2], None);
489 assert_eq!(cwds("true || cd /tmp && echo x")[2], None);
490 assert_eq!(cwds("cd /tmp | cat; echo x")[2], None, "a pipeline element");
491 }
492
493 #[test]
496 fn a_second_cd_does_not_make_a_failed_first_one_certain() {
497 assert_eq!(cwds(&format!("cd {MISSING} && cd . ; echo x"))[2], None);
498 }
499
500 #[test]
501 fn cd_or_exit_leaves_only_the_moved_directory() {
502 let got = cwds(&format!("cd {MISSING} || exit 1; echo x"));
503 assert_eq!(got[1], Some(PathBuf::from("/proj")), "the fallback");
504 assert_eq!(got[2], Some(PathBuf::from(MISSING)));
505 }
506
507 #[test]
509 fn a_backgrounded_list_does_not_move_what_follows() {
510 assert_eq!(
511 cwds("cd /tmp && echo a & echo b")[2],
512 Some(PathBuf::from("/proj"))
513 );
514 }
515
516 #[test]
517 fn opaque_movers_make_the_directory_unknown() {
518 for command in [
519 "pushd /tmp && echo x",
520 "builtin cd /tmp && echo x",
521 "{ cd /tmp; } && echo x",
522 ] {
523 assert_eq!(cwds(command).last(), Some(&None), "{command}");
524 }
525 let subshell = cwds("(cd /tmp) && echo x");
526 assert_eq!(subshell[0], None, "its own directory is not followed");
527 assert_eq!(
528 subshell[1],
529 Some(PathBuf::from("/proj")),
530 "but it cannot move the parent shell"
531 );
532 }
533
534 #[test]
535 fn cdpath_makes_a_relative_cd_unknown() {
536 assert_eq!(cwds("CDPATH=/elsewhere; cd sub && ls")[2], None);
537 assert_eq!(
538 cwds("CDPATH=/elsewhere; cd ./sub && ls")[2],
539 Some(PathBuf::from("/proj/sub")),
540 "`./` bypasses CDPATH"
541 );
542 }
543
544 #[test]
547 fn a_cd_inside_a_quoted_argument_does_not_move_anything() {
548 for command in [
549 "printf '%s\\n' 'note: cd /tmp mention' > f.txt",
550 "cd /proj && printf '| %s | (cd $TMPDIR not followed) |\\n' x >> f.txt",
551 "echo \"pushd here, popd there, then cd back\" > f.txt",
552 "echo \"$(cd /tmp; pwd)\" > f.txt",
553 "echo 'it'\\''s cd' > f.txt",
554 ] {
555 assert_eq!(
556 cwds(command).last(),
557 Some(&Some(PathBuf::from("/proj"))),
558 "{command}"
559 );
560 }
561 }
562
563 #[test]
566 fn a_quoted_command_name_or_eval_still_moves_the_shell() {
567 for command in [
568 "\"cd\" /tmp && echo x",
569 "c'd' /tmp && echo x",
570 "\\cd /tmp && echo x",
571 "builtin 'cd' /tmp && echo x",
572 "eval 'cd /tmp' && echo x",
573 "'eval' \"c\"\"d /tmp\" && echo x",
574 "echo ${ cd /tmp; } && echo x",
575 ] {
576 assert_eq!(cwds(command).last(), Some(&None), "{command}");
577 }
578 }
579
580 #[test]
583 fn a_cd_through_a_known_variable_is_followed() {
584 assert_eq!(
585 cwds("D=/tmp && cd $D && echo x").last(),
586 Some(&Some(PathBuf::from("/tmp")))
587 );
588 assert_eq!(
589 cwds("D=/tmp; cd \"${D}/sub\" && echo x").last(),
590 Some(&Some(PathBuf::from("/tmp/sub")))
591 );
592 assert_eq!(
593 cwds("D=sub; cd $D && echo x").last(),
594 Some(&Some(PathBuf::from("/proj/sub"))),
595 "a relative value is joined like a relative literal"
596 );
597 let expected = std::env::var("TMPDIR")
598 .ok()
599 .filter(|t| !t.is_empty() && !t.contains(['$', '`']))
600 .map(|t| resolve_cd(None, &t, &KnownVars::default()));
601 assert_eq!(
602 final_cwd("cd $TMPDIR && ls", Some(Path::new("/proj"))),
603 expected.flatten(),
604 "$TMPDIR resolves exactly as its value spelled out"
605 );
606 }
607
608 #[test]
610 fn a_cd_through_an_unknown_variable_stays_unknown() {
611 for command in [
612 "cd $D && echo x",
613 "true && D=/tmp; cd $D && echo x",
614 "D=/tmp; read D; cd $D && echo x",
615 "TMPDIR=$PWD; cd $TMPDIR && echo x",
616 "unset TMPDIR; cd $TMPDIR && echo x",
617 "D=/tmp; cd '$D' && echo x",
619 "D=/tmp; cd $Dx && echo x",
620 ] {
621 assert_eq!(cwds(command).last(), Some(&None), "{command}");
622 }
623 }
624}