1use std::path::{Path, PathBuf};
19
20use super::shell_allowlist::Separator;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SegmentCwd {
25 pub segment: String,
26 pub cwd: Option<PathBuf>,
29}
30
31pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
36 track(command, base).0
37}
38
39pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
41 track(command, base).1
42}
43
44struct Pending {
49 moved: Option<PathBuf>,
50 old: Option<PathBuf>,
52 skippable: bool,
54 fallback: bool,
57}
58
59impl Pending {
60 fn either(self) -> Option<PathBuf> {
61 merge(self.moved, self.old.as_deref())
62 }
63}
64
65fn track(command: &str, base: Option<&Path>) -> (Vec<SegmentCwd>, Option<PathBuf>) {
66 let segments = super::shell_allowlist::segments_with_separators(command);
67 let cdpath = std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
69 || segments.iter().any(|(s, _)| s.contains("CDPATH"));
70
71 let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
73 let mut list_base = cwd.clone();
76 let mut pending: Option<Pending> = None;
77 let mut prev: Option<Separator> = None;
78 let mut out = Vec::with_capacity(segments.len());
79
80 for (segment, sep) in segments {
81 let here = cwd.clone();
84 let mut own = here.clone();
85
86 if let Some(p) = pending.take_if(|p| p.fallback) {
87 cwd = if exits(&segment) && !p.skippable {
91 p.moved
92 } else if cd_target(&segment).is_some() || moves_opaquely(&segment) {
93 None
94 } else {
95 p.either()
96 };
97 } else if let Some(target) = cd_target(&segment) {
98 let moved = if cdpath && is_cdpath_candidate(target) {
99 None
100 } else {
101 resolve_cd(here.as_deref(), target)
102 };
103 let old = match pending.take() {
106 Some(p) => merge(here.clone(), p.old.as_deref()),
107 None => here.clone(),
108 };
109 let runs_unconditionally = matches!(
110 prev,
111 None | Some(Separator::Sequence | Separator::Background)
112 );
113 if prev == Some(Separator::Pipe) || sep == Some(Separator::Pipe) {
114 cwd = merge(moved, old.as_deref());
117 } else if runs_unconditionally && moved.as_deref().is_some_and(Path::is_dir) {
118 cwd = moved;
120 } else {
121 let skippable = prev == Some(Separator::Or);
122 let p = Pending {
123 moved,
124 old,
125 skippable,
126 fallback: sep == Some(Separator::Or),
127 };
128 cwd = match sep {
129 Some(Separator::Or) => p.old.clone(),
130 Some(Separator::Sequence) => merge(p.moved.clone(), p.old.as_deref()),
131 _ if skippable => merge(p.moved.clone(), p.old.as_deref()),
132 _ => p.moved.clone(),
133 };
134 if matches!(sep, Some(Separator::Or | Separator::And) | None) {
135 pending = Some(p);
136 }
137 }
138 } else {
139 if moves_opaquely(&segment) {
140 own = None;
141 if !segment.starts_with('(') {
144 cwd = None;
145 pending = None;
146 }
147 }
148 if let Some(p) = pending.take() {
151 match sep {
152 Some(Separator::And | Separator::Pipe) | None => pending = Some(p),
153 Some(Separator::Or | Separator::Sequence | Separator::Background) => {
154 cwd = p.either();
155 }
156 }
157 }
158 }
159
160 out.push(SegmentCwd { segment, cwd: own });
161 match sep {
162 Some(Separator::Background) => {
163 cwd.clone_from(&list_base);
164 pending = None;
165 }
166 Some(Separator::Sequence) => list_base.clone_from(&cwd),
167 _ => {}
168 }
169 prev = sep;
170 }
171 (out, cwd)
172}
173
174fn merge(a: Option<PathBuf>, b: Option<&Path>) -> Option<PathBuf> {
176 if a.as_deref() == b { a } else { None }
177}
178
179fn exits(segment: &str) -> bool {
181 matches!(segment.split_whitespace().next(), Some("exit" | "return"))
182}
183
184fn is_cdpath_candidate(target: &str) -> bool {
186 let t = target.trim_matches(['"', '\'']);
187 !(t.starts_with('/')
188 || t.starts_with('~')
189 || t.starts_with("./")
190 || t.starts_with("../")
191 || t == "."
192 || t == ".."
193 || Path::new(t).is_absolute())
194}
195
196fn moves_opaquely(segment: &str) -> bool {
201 segment
202 .split(|c: char| c.is_whitespace() || "(){};&|`".contains(c))
203 .any(|word| matches!(word, "cd" | "pushd" | "popd" | "chdir"))
204}
205
206fn cd_target(segment: &str) -> Option<&str> {
208 let mut words = segment.split_whitespace();
209 if words.next()? != "cd" {
210 return None;
211 }
212 let target = words.next()?;
213 if words.next().is_some() {
214 return None;
216 }
217 Some(target)
218}
219
220fn resolve_cd(from: Option<&Path>, target: &str) -> Option<PathBuf> {
226 let unquoted = target.trim_matches(['"', '\'']);
227 if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
228 return None;
229 }
230 if let Some(rest) = unquoted.strip_prefix('~') {
232 let home = std::env::var_os("HOME").map(PathBuf::from)?;
233 return Some(join_in(&home, rest.trim_start_matches('/')));
234 }
235 if unquoted.starts_with('/') {
242 return Some(PathBuf::from(normalize_posix(unquoted)));
243 }
244 let path = Path::new(unquoted);
245 if path.is_absolute() {
246 return Some(normalize(path));
247 }
248 Some(join_in(from?, unquoted))
249}
250
251pub fn join_in(base: &Path, rel: &str) -> PathBuf {
256 let base_str = base.to_string_lossy();
257 if base_str.starts_with('/') {
258 return PathBuf::from(normalize_posix(&format!(
259 "{}/{rel}",
260 base_str.trim_end_matches('/')
261 )));
262 }
263 normalize(&base.join(rel))
264}
265
266fn normalize_posix(path: &str) -> String {
268 let mut out: Vec<&str> = Vec::new();
269 for part in path.split('/') {
270 match part {
271 "" | "." => {}
272 ".." => {
273 out.pop();
274 }
275 other => out.push(other),
276 }
277 }
278 format!("/{}", out.join("/"))
279}
280
281fn normalize(path: &Path) -> PathBuf {
284 use std::path::Component;
285 let mut out = PathBuf::new();
286 for component in path.components() {
287 match component {
288 Component::CurDir => {}
289 Component::ParentDir => {
290 out.pop();
291 }
292 other => out.push(other),
293 }
294 }
295 out
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn a_leading_cd_moves_the_following_segments() {
304 let segs = segments_with_cwd(
305 "cd /tmp/work && curl -o x.png http://e/x",
306 Some(Path::new("/proj")),
307 );
308 assert_eq!(
309 segs.last().unwrap().cwd.as_deref(),
310 Some(Path::new("/tmp/work"))
311 );
312 }
313
314 #[test]
315 fn without_a_cd_every_segment_keeps_the_call_directory() {
316 let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
317 assert!(
318 segs.iter()
319 .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
320 );
321 }
322
323 #[test]
324 fn a_relative_cd_is_joined_onto_the_call_directory() {
325 assert_eq!(
326 final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
327 Some(PathBuf::from("/proj/sub/dir"))
328 );
329 assert_eq!(
330 final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
331 Some(PathBuf::from("/proj/side"))
332 );
333 }
334
335 #[test]
339 fn an_unresolvable_cd_makes_the_directory_unknown() {
340 assert_eq!(
341 final_cwd("cd \"$TMPDIR\" && ls", Some(Path::new("/proj"))),
342 None
343 );
344 assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
345 }
346
347 #[test]
351 fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
352 assert_eq!(
353 final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
354 Some(PathBuf::from("/tmp"))
355 );
356 assert_eq!(
357 final_cwd("cd /private/tmp/session/../session && ls", None),
358 Some(PathBuf::from("/private/tmp/session"))
359 );
360 assert_eq!(
361 join_in(Path::new("/tmp/work"), "sub/shot.png"),
362 PathBuf::from("/tmp/work/sub/shot.png"),
363 "and joins with a forward slash, which the scratch prefixes match on"
364 );
365 }
366
367 #[test]
368 fn no_base_and_no_cd_is_unknown() {
369 assert_eq!(final_cwd("ls -la", None), None);
370 }
371
372 fn cwds(command: &str) -> Vec<Option<PathBuf>> {
373 segments_with_cwd(command, Some(Path::new("/proj")))
374 .into_iter()
375 .map(|s| s.cwd)
376 .collect()
377 }
378
379 const MISSING: &str = "/lean-ctx-1850-does-not-exist";
380
381 #[test]
383 fn a_cd_segment_runs_in_the_directory_before_it() {
384 assert_eq!(cwds("cd /tmp && ls")[0], Some(PathBuf::from("/proj")));
385 }
386
387 #[test]
390 fn a_cd_that_may_fail_does_not_carry_past_a_sequence() {
391 let got = cwds(&format!("cd {MISSING} && true; echo x"));
392 assert_eq!(got[1], Some(PathBuf::from(MISSING)), "reached only via &&");
393 assert_eq!(got[2], None);
394 }
395
396 #[test]
397 fn a_cd_that_may_be_skipped_leaves_the_directory_unknown() {
398 assert_eq!(cwds("false && cd /tmp; echo x")[2], None);
399 assert_eq!(cwds("true || cd /tmp && echo x")[2], None);
400 assert_eq!(cwds("cd /tmp | cat; echo x")[2], None, "a pipeline element");
401 }
402
403 #[test]
406 fn a_second_cd_does_not_make_a_failed_first_one_certain() {
407 assert_eq!(cwds(&format!("cd {MISSING} && cd . ; echo x"))[2], None);
408 }
409
410 #[test]
411 fn cd_or_exit_leaves_only_the_moved_directory() {
412 let got = cwds(&format!("cd {MISSING} || exit 1; echo x"));
413 assert_eq!(got[1], Some(PathBuf::from("/proj")), "the fallback");
414 assert_eq!(got[2], Some(PathBuf::from(MISSING)));
415 }
416
417 #[test]
419 fn a_backgrounded_list_does_not_move_what_follows() {
420 assert_eq!(
421 cwds("cd /tmp && echo a & echo b")[2],
422 Some(PathBuf::from("/proj"))
423 );
424 }
425
426 #[test]
427 fn opaque_movers_make_the_directory_unknown() {
428 for command in [
429 "pushd /tmp && echo x",
430 "builtin cd /tmp && echo x",
431 "{ cd /tmp; } && echo x",
432 ] {
433 assert_eq!(cwds(command).last(), Some(&None), "{command}");
434 }
435 let subshell = cwds("(cd /tmp) && echo x");
436 assert_eq!(subshell[0], None, "its own directory is not followed");
437 assert_eq!(
438 subshell[1],
439 Some(PathBuf::from("/proj")),
440 "but it cannot move the parent shell"
441 );
442 }
443
444 #[test]
445 fn cdpath_makes_a_relative_cd_unknown() {
446 assert_eq!(cwds("CDPATH=/elsewhere; cd sub && ls")[2], None);
447 assert_eq!(
448 cwds("CDPATH=/elsewhere; cd ./sub && ls")[2],
449 Some(PathBuf::from("/proj/sub")),
450 "`./` bypasses CDPATH"
451 );
452 }
453}