1use std::borrow::Cow;
17use std::cell::RefCell;
18
19pub mod anchor;
20pub mod folder;
21pub(crate) use folder::judging;
22mod home;
23pub mod item_shape;
24mod lexical;
25mod physical;
26mod placing;
27mod vars;
28pub use item_shape::{Binding, Facts, ItemShape, ItemShapeGuard, binding, enter_loop_shape, enter_stdin_shape, loop_shape, stdin_shape};
29use lexical::{expand_home, lexical_join, names_no_known_directory};
30pub(crate) use placing::on_the_link;
31use placing::resolve_placed;
32pub use vars::{LoopGuard, VarGuard, enter_loop_var, enter_var, expand_vars, names_a_loop_var};
33
34#[derive(Clone, Default)]
38pub struct PathCtx {
39 pub cwd: Option<String>,
40 pub root: Option<String>,
41 pub session_id: Option<String>,
44}
45
46thread_local! {
47 static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
48 static REPORTED: RefCell<Option<String>> = const { RefCell::new(None) };
49}
50
51#[must_use]
54pub fn enter(ctx: PathCtx) -> Guard {
55 let reported = REPORTED.with(|r| r.replace(ctx.cwd.clone()));
56 Guard(CURRENT.with(|c| c.replace(ctx)), Some(reported))
57}
58
59pub struct Guard(PathCtx, Option<Option<String>>);
61
62impl Drop for Guard {
63 fn drop(&mut self) {
64 CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
65 if let Some(reported) = self.1.take() {
66 REPORTED.with(|r| *r.borrow_mut() = reported);
67 }
68 }
69}
70
71#[must_use]
74pub fn enter_cwd(cwd: Option<String>) -> Guard {
75 Guard(
76 CURRENT.with(|c| {
77 let mut b = c.borrow_mut();
78 PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
81 }),
82 None,
83 )
84}
85
86pub(crate) fn moved_by_cd() -> bool {
89 REPORTED.with(|r| *r.borrow() != cwd())
90}
91
92pub fn cwd() -> Option<String> {
94 CURRENT.with(|c| c.borrow().cwd.clone())
95}
96
97pub fn root() -> Option<String> {
100 CURRENT.with(|c| {
101 let b = c.borrow();
102 b.root.clone().or_else(|| b.cwd.clone())
103 })
104}
105
106pub(crate) fn placed_in_root(abs: &str) -> bool {
109 root()
110 .filter(|root| root.starts_with('/'))
111 .is_some_and(|root| crate::engine::resolve::regions::lies_in_root(abs, &physical::root(&root)))
112}
113
114pub fn in_session_scratchpad(path: &str) -> bool {
135 let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
136 return false;
137 };
138 if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
141 return false;
142 }
143 if !under_temp_root(path) {
144 return false;
145 }
146 path.split('/').any(|seg| seg == id)
147}
148
149const TEMP_ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
150const TEMP_ROOTS_ANY_CASE: &[&str] =
151 &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/", "/var/folders/", "/private/var/folders/"];
152
153pub fn under_temp_root(path: &str) -> bool {
160 if TEMP_ROOTS.iter().any(|r| path.starts_with(r)) {
161 return true;
162 }
163 std::env::var("TMPDIR").ok().is_some_and(|t| {
164 let t = t.trim_end_matches('/');
165 !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
166 })
167}
168
169pub fn under_temp(path: &str) -> bool {
174 let folded = strip_data_volume(path).to_ascii_lowercase();
175 let dir = if folded.ends_with('/') { folded } else { format!("{folded}/") };
176 TEMP_ROOTS_ANY_CASE.iter().any(|root| dir.starts_with(root)) || tmpdir_spellings().iter().any(|root| dir.starts_with(root))
177}
178
179fn strip_data_volume(path: &str) -> String {
180 let mut rest = path;
181 const PREFIX: &str = "/system/volumes/data";
182 while rest.get(..PREFIX.len()).is_some_and(|head| head.eq_ignore_ascii_case(PREFIX)) {
184 let after = &rest[PREFIX.len()..];
185 if after.is_empty() || after.starts_with('/') {
186 rest = after;
187 continue;
188 }
189 break;
190 }
191 rest.to_string()
192}
193
194fn tmpdir_spellings() -> Vec<String> {
195 let Ok(raw) = std::env::var("TMPDIR") else { return Vec::new() };
196 let dir = raw.trim_end_matches('/').to_ascii_lowercase();
197 if dir.len() <= 1 || !dir.starts_with('/') {
198 return Vec::new();
199 }
200 let mut out = vec![format!("{dir}/")];
201 if let Some(rest) = dir.strip_prefix("/private/") {
202 out.push(format!("/{rest}/"));
203 } else if dir == "/tmp" || dir.starts_with("/tmp/") || dir == "/var" || dir.starts_with("/var/") {
204 out.push(format!("/private{dir}/"));
205 }
206 out
207}
208
209pub(crate) fn physical_directory(path: &str) -> String {
211 if !path.starts_with('/') {
212 return path.to_string();
213 }
214 physical::resolve(path, true).unwrap_or_else(|| path.to_string())
215}
216
217thread_local! {
218 static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
219}
220
221#[must_use]
226pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
227 STDIN_REPR.with(|v| v.borrow_mut().push(repr));
228 StdinReprGuard
229}
230
231pub fn stdin_item_repr() -> Option<String> {
234 STDIN_REPR.with(|v| v.borrow().last().cloned())
235}
236
237pub struct StdinReprGuard;
238
239impl Drop for StdinReprGuard {
240 fn drop(&mut self) {
241 STDIN_REPR.with(|v| {
242 v.borrow_mut().pop();
243 });
244 }
245}
246
247thread_local! {
248 static RIPGREP_CONFIG: RefCell<Vec<bool>> = const { RefCell::new(Vec::new()) };
249}
250
251pub(crate) const RIPGREP_CONFIG_PATH: &str = "RIPGREP_CONFIG_PATH";
252
253#[must_use]
254pub(crate) fn bind_ripgrep_config(follows: Option<bool>) -> RipgrepConfigGuard {
255 if let Some(follows) = follows {
256 RIPGREP_CONFIG.with(|v| v.borrow_mut().push(follows));
257 }
258 RipgrepConfigGuard { pushed: follows.is_some() }
259}
260
261pub(crate) fn ripgrep_config_follows() -> bool {
264 RIPGREP_CONFIG
265 .with(|v| v.borrow().last().copied())
266 .unwrap_or_else(|| config_file_follows(std::env::var_os(RIPGREP_CONFIG_PATH), cwd().as_deref()))
267}
268
269fn config_file_follows(path: Option<std::ffi::OsString>, cwd: Option<&str>) -> bool {
271 let Some(path) = path.filter(|path| !path.is_empty()).map(std::path::PathBuf::from) else {
272 return false;
273 };
274 let path = match cwd {
275 _ if path.is_absolute() => path,
276 Some(cwd) => std::path::Path::new(cwd).join(path),
277 None => return true,
278 };
279 std::fs::read_to_string(path).map_or(true, |text| {
280 text.lines()
281 .map(str::trim)
282 .any(|line| line.starts_with("--follow") || (line.starts_with('-') && !line.starts_with("--") && line.contains('L')))
283 })
284}
285
286pub(crate) struct RipgrepConfigGuard {
287 pushed: bool,
288}
289
290impl Drop for RipgrepConfigGuard {
291 fn drop(&mut self) {
292 if self.pushed {
293 RIPGREP_CONFIG.with(|v| {
294 v.borrow_mut().pop();
295 });
296 }
297 }
298}
299
300pub fn resolve(path: &str) -> Cow<'_, str> {
312 resolve_placed(path, None)
313}
314
315pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
318 if use_.mutates() {
319 folder::note_named_write();
320 }
321 resolve_placed(path, Some(use_))
322}
323
324pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
327
328pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
343 join_cwd_mode(cur, target, false)
344}
345
346pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
347 let expanded = match expand_home(target) {
348 Some(t) => t,
349 None => return Some(UNRESOLVED_CWD.to_string()), };
351 if names_no_known_directory(&expanded) {
359 return Some(UNRESOLVED_CWD.to_string());
360 }
361 let raw = if let Some(landed) = declared_substitution_directory(cur, &expanded) {
362 landed
363 } else if expanded.starts_with('/') {
364 expanded.into_owned()
365 } else {
366 let c = cur.filter(|c| c.starts_with('/'))?;
367 format!("{c}/{expanded}")
368 };
369 Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
370}
371
372fn declared_substitution_directory(cur: Option<&str>, expanded: &str) -> Option<String> {
374 use crate::engine::facet::{FacetTerm, LocalLocus};
375 let after = expanded.strip_prefix(crate::cst::eval::TAGGED_PREFIX)?;
376 let (term, tail) = after.split_once("__").unwrap_or(("", ""));
377 let Some(tag) = LocalLocus::from_term(&term.to_lowercase().replace('_', "-")) else {
378 return Some(UNRESOLVED_CWD.to_string());
379 };
380 let Some(cur) = cur.filter(|c| c.starts_with('/') && *c != UNRESOLVED_CWD) else {
381 return Some(UNRESOLVED_CWD.to_string());
382 };
383 let here = crate::engine::resolve::locus::read_locus(cur);
384 if here == tag {
385 let rel = tail.trim_start_matches('/');
386 return Some(if rel.is_empty() { cur.to_string() } else { lexical::lexical_join(cur, rel) });
387 }
388 let in_band = |locus: LocalLocus| locus >= LocalLocus::SandboxScope && locus <= LocalLocus::WorktreeTrusted;
389 if in_band(tag) && !in_band(here) {
390 return Some(UNRESOLVED_CWD.to_string());
391 }
392 let base = match tag {
393 LocalLocus::Temp => "/tmp",
394 _ => return Some(UNRESOLVED_CWD.to_string()),
395 };
396 let rel = tail.trim_start_matches('/');
397 Some(if rel.is_empty() { base.to_string() } else { lexical::lexical_join(base, rel) })
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn an_inherited_ripgrep_config_follows_when_it_says_so_or_cannot_be_read() {
406 let dir = tempfile::tempdir().expect("scratch");
407 let cwd = dir.path().to_str().expect("utf-8");
408 for (name, text) in [
409 ("long", "--follow\n"),
410 ("short", " -iL\n"),
411 ("plain", "--smart-case\n--max-columns=10\n"),
412 ("glob", "--glob=*L*\n--type-add=L:*.l\n"),
413 ] {
414 std::fs::write(dir.path().join(name), text).expect("config");
415 }
416 let follows = |path: Option<&str>, cwd: Option<&str>| config_file_follows(path.map(Into::into), cwd);
417 assert!(follows(Some("long"), Some(cwd)));
418 assert!(follows(Some("short"), Some(cwd)));
419 assert!(follows(Some("missing"), Some(cwd)));
420 assert!(follows(Some("plain"), None));
421 assert!(!follows(Some("plain"), Some(cwd)));
422 assert!(!follows(Some("glob"), Some(cwd)));
423 assert!(!follows(Some(dir.path().join("plain").to_str().expect("utf-8")), None));
424 assert!(!follows(Some(""), Some(cwd)));
425 assert!(!follows(None, Some(cwd)));
426 }
427
428 const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
429
430 fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
431 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
432 f()
433 }
434
435 #[test]
440 fn only_this_sessions_scratchpad_is_recognized() {
441 let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
442 let matching: &[String] = &[
443 format!("{scratch}/build.sh"),
444 format!("{scratch}/nested/deep/gen.py"),
445 scratch.clone(),
446 format!("/tmp/{SID}/x.sh"),
448 format!("/tmp/some-other-harness/{SID}/work/x.sh"),
449 format!("/var/tmp/{SID}/x.sh"),
450 ];
451 let rejected: &[String] = &[
452 "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
454 format!("/tmp/{SID}-evil/x.sh"),
456 format!("/tmp/evil-{SID}/x.sh"),
457 format!("/tmp/a{SID}/x.sh"),
458 format!("/home/u/{SID}/x.sh"),
460 format!("~/.ssh/{SID}/id_rsa"),
461 format!("/etc/{SID}/passwd"),
462 "/tmp/evil.sh".into(),
464 "/private/tmp/downloaded.sh".into(),
465 format!("/TMP/{SID}/x.sh"),
468 format!("/System/Volumes/Data/tmp/{SID}/x.sh"),
469 format!("/private/var/folders/xx/yy/T/{SID}/x.sh"),
470 ];
471 with_session(Some(SID), || {
472 for p in matching {
473 assert!(in_session_scratchpad(p), "should be recognized: {p}");
474 }
475 for p in rejected {
476 assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
477 }
478 });
479 }
480
481 #[test]
484 fn a_missing_or_unusable_session_id_recognizes_nothing() {
485 let path = format!("/tmp/{SID}/x.sh");
486 with_session(None, || {
487 assert!(!in_session_scratchpad(&path), "no session id → no recognition");
488 });
489 for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
490 with_session(Some(weak), || {
491 assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
492 });
493 }
494 }
495
496 #[test]
497 fn under_temp_never_slices_inside_a_multibyte_character() {
498 let prefix = "/system/volumes/data";
499 for filler in ["\u{fffd}", "\u{e9}", "\u{1f600}"] {
500 for cut in 0..=prefix.len() {
501 let path = format!("{}{filler}{}", &prefix[..cut], &prefix[cut..]);
502 assert!(!under_temp(&path), "{path}");
503 }
504 }
505 assert!(under_temp("/System/Volumes/Data/tmp/x"));
506 }
507
508 #[test]
509 fn under_temp_folds_case_firmlinks_and_var_folders_without_admitting_them() {
510 for path in [
511 "/TMP/y", "/Tmp/y", "/PRIVATE/TMP/y", "/private/TMP/y", "/System/Volumes/Data/tmp/y", "/System/Volumes/Data/private/tmp/y",
512 "/private/var/folders/xx/yy/T/y", "/var/folders/xx/yy/T/y", "/VAR/folders/xx/yy/T/y", "/Var/Folders/xx/yy/T/y",
513 ] {
514 assert!(under_temp(path), "{path}");
515 assert!(crate::engine::resolve::locus::under_temp(path), "locus: {path}");
516 assert!(!under_temp_root(path), "exact prefix must stay strict: {path}");
517 }
518 assert!(under_temp("/tmp/y"));
519 assert!(under_temp_root("/tmp/y"));
520 assert!(!under_temp("/etc/y"));
521 assert!(!under_temp("/tmpfile/y"));
522 }
523
524 #[test]
525 fn no_context_leaves_paths_unchanged() {
526 assert_eq!(resolve("./x"), "./x");
527 assert_eq!(resolve("config"), "config");
528 assert_eq!(resolve("/etc/x"), "/etc/x");
529 }
530
531 #[test]
532 fn relative_inside_the_project_stays_worktree_relative() {
533 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
534 assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
535 assert_eq!(resolve("./y"), "sub/y");
536 assert_eq!(resolve("../z"), "z", ".. that stays inside root");
537 }
538
539 #[test]
540 fn relative_outside_the_project_becomes_absolute() {
541 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
542 assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
543 assert_eq!(resolve("passwd"), "/etc/passwd");
544 assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
545 }
546
547 #[test]
548 fn dotdot_escaping_the_project_becomes_absolute() {
549 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
550 assert_eq!(resolve("../../../etc/x"), "/etc/x");
551 }
552
553 #[test]
554 fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
555 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
556 assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
558 assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
559 assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
560 assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
561 assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
563 assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
564 assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
565 assert_eq!(
566 resolve("/home/u/proj-evil/secret"),
567 "/home/u/proj-evil/secret",
568 "a sibling dir is not confused for inside by bare string prefix",
569 );
570 assert_eq!(resolve("$HOME/x"), "$HOME/x");
572 assert_eq!(resolve("~/x"), "~/x");
573 }
574
575 #[test]
576 fn a_home_spelled_path_inside_root_becomes_root_relative() {
577 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
578 return;
579 };
580 let root = format!("{home}/projects/app");
581 let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
582 assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
583 assert_eq!(resolve("~/projects/app"), ".");
584 assert_eq!(resolve("~/projects/app/"), ".");
585 let under = |rest: &str| format!("~/projects/{rest}");
586 assert_eq!(resolve(&under("app/a/../b")), "b");
587 assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
588 for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
589 assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
590 }
591 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
592 assert_eq!(resolve("~"), "~");
593 assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
594 }
595
596 #[test]
597 fn a_home_spelled_path_needs_an_absolute_root() {
598 let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
599 assert_eq!(resolve("~/x"), "~/x");
600 drop(_none);
601 let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
602 assert_eq!(resolve("~/x"), "~/x");
603 }
604
605 #[test]
606 fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
607 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
608 return;
609 };
610 let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
611 assert_eq!(resolve("~"), "~");
612 assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
613 assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
614 assert_eq!(resolve("."), home);
615 }
616
617 #[test]
618 fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
619 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
620 return;
621 };
622 let root = format!("{home}/projects/app");
623 let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
624 assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
625 drop(outside);
626 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
627 for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
628 assert_eq!(resolve(&glob), glob);
629 }
630 }
631
632 #[test]
633 fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
634 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
635 return;
636 };
637 let root = format!("{home}/.ssh");
638 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
639 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
640 }
641
642 #[test]
643 fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
644 let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
645 assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
646 assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
647 assert_eq!(resolve("etc"), "/etc");
648 assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
649 assert_eq!(resolve("."), "/");
650 drop(_g);
651 let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
652 assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
653 assert_eq!(resolve("sudoers"), "/etc/sudoers");
654 assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
655 drop(_etc);
656 let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
657 assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
658 }
659
660 #[test]
661 fn loop_var_expands_to_its_representative_per_face() {
662 let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
663 assert_eq!(expand_vars("$f", false), "read_item");
664 assert_eq!(expand_vars("$f", true), "write_item");
665 assert_eq!(expand_vars("${f}", false), "read_item");
666 assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
667 assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
668 assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
669 assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
670 assert_eq!(expand_vars("plain", false), "plain");
671 }
672
673 #[test]
674 fn loop_var_binding_is_scoped_and_nests() {
675 assert_eq!(expand_vars("$f", false), "$f", "no binding");
676 {
677 let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
678 {
679 let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
680 assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
681 }
682 assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
683 }
684 assert_eq!(expand_vars("$f", false), "$f", "all popped");
685 }
686
687 #[test]
688 fn the_guard_restores_on_drop() {
689 {
690 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
691 assert_eq!(resolve("x"), "/etc/x");
692 }
693 assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
694 }
695
696 const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
697
698 fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
699 let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
700 .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
701 .env("TMPDIR", tmpdir)
702 .env(PROBE_VAR, path)
703 .output()
704 .expect("spawn probe");
705 let stdout = String::from_utf8_lossy(&out.stdout);
706 assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
707 match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
708 (true, false) => true,
709 (false, true) => false,
710 _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
711 }
712 }
713
714 #[test]
715 fn tmpdir_probe() {
716 let Ok(path) = std::env::var(PROBE_VAR) else {
717 return;
718 };
719 println!("PROBE_VERDICT={}", under_temp_root(&path));
720 }
721
722 #[test]
723 fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
724 for (tmpdir, path, expected) in [
725 ("/work/scratch", "/work/scratch/x.sh", true),
726 ("/work/scratch/", "/work/scratch/x.sh", true),
727 ("/work/scratch//", "/work/scratch/nested/x.sh", true),
728 ("/work/scratch", "/work/scratch", false),
729 ("/work/scratch", "/work/scratchy/x.sh", false),
730 ("/work/scratch", "/work/other/x.sh", false),
731 ("/work/scratch", "work/scratch/x.sh", false),
732 ("", "/x.sh", false),
733 ("", "/", false),
734 ("/", "/x.sh", false),
735 ("//", "/x.sh", false),
736 ("scratch", "scratch/x.sh", false),
737 ("scratch/", "scratch/x.sh", false),
738 ("./scratch", "./scratch/x.sh", false),
739 ("$SCRATCH", "$SCRATCH/x.sh", false),
740 ("relative/dir", "relative/dir/x.sh", false),
741 ] {
742 assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
743 }
744 }
745
746 #[test]
747 fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
748 for tmpdir in ["", "scratch", "/work/scratch"] {
749 for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
750 assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
751 }
752 assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
753 }
754 }
755}