use std::borrow::Cow;
use std::cell::RefCell;
pub mod anchor;
pub mod folder;
pub(crate) use folder::judging;
mod home;
pub mod item_shape;
mod lexical;
mod physical;
mod placing;
mod vars;
pub use item_shape::{Binding, Facts, ItemShape, ItemShapeGuard, binding, enter_loop_shape, enter_stdin_shape, loop_shape, stdin_shape};
use lexical::{expand_home, lexical_join, names_no_known_directory};
pub(crate) use placing::on_the_link;
use placing::resolve_placed;
pub use vars::{LoopGuard, VarGuard, enter_loop_var, enter_var, expand_vars, names_a_loop_var};
#[derive(Clone, Default)]
pub struct PathCtx {
pub cwd: Option<String>,
pub root: Option<String>,
pub session_id: Option<String>,
}
thread_local! {
static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
static REPORTED: RefCell<Option<String>> = const { RefCell::new(None) };
}
#[must_use]
pub fn enter(ctx: PathCtx) -> Guard {
let reported = REPORTED.with(|r| r.replace(ctx.cwd.clone()));
Guard(CURRENT.with(|c| c.replace(ctx)), Some(reported))
}
pub struct Guard(PathCtx, Option<Option<String>>);
impl Drop for Guard {
fn drop(&mut self) {
CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
if let Some(reported) = self.1.take() {
REPORTED.with(|r| *r.borrow_mut() = reported);
}
}
}
#[must_use]
pub fn enter_cwd(cwd: Option<String>) -> Guard {
Guard(
CURRENT.with(|c| {
let mut b = c.borrow_mut();
PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
}),
None,
)
}
pub(crate) fn moved_by_cd() -> bool {
REPORTED.with(|r| *r.borrow() != cwd())
}
pub fn cwd() -> Option<String> {
CURRENT.with(|c| c.borrow().cwd.clone())
}
pub fn root() -> Option<String> {
CURRENT.with(|c| {
let b = c.borrow();
b.root.clone().or_else(|| b.cwd.clone())
})
}
pub(crate) fn placed_in_root(abs: &str) -> bool {
root()
.filter(|root| root.starts_with('/'))
.is_some_and(|root| crate::engine::resolve::regions::lies_in_root(abs, &physical::root(&root)))
}
pub fn in_session_scratchpad(path: &str) -> bool {
let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
return false;
};
if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return false;
}
if !under_temp_root(path) {
return false;
}
path.split('/').any(|seg| seg == id)
}
const TEMP_ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
const TEMP_ROOTS_ANY_CASE: &[&str] =
&["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/", "/var/folders/", "/private/var/folders/"];
pub fn under_temp_root(path: &str) -> bool {
if TEMP_ROOTS.iter().any(|r| path.starts_with(r)) {
return true;
}
std::env::var("TMPDIR").ok().is_some_and(|t| {
let t = t.trim_end_matches('/');
!t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
})
}
pub fn under_temp(path: &str) -> bool {
let folded = strip_data_volume(path).to_ascii_lowercase();
let dir = if folded.ends_with('/') { folded } else { format!("{folded}/") };
TEMP_ROOTS_ANY_CASE.iter().any(|root| dir.starts_with(root)) || tmpdir_spellings().iter().any(|root| dir.starts_with(root))
}
fn strip_data_volume(path: &str) -> String {
let mut rest = path;
const PREFIX: &str = "/system/volumes/data";
while rest.get(..PREFIX.len()).is_some_and(|head| head.eq_ignore_ascii_case(PREFIX)) {
let after = &rest[PREFIX.len()..];
if after.is_empty() || after.starts_with('/') {
rest = after;
continue;
}
break;
}
rest.to_string()
}
fn tmpdir_spellings() -> Vec<String> {
let Ok(raw) = std::env::var("TMPDIR") else { return Vec::new() };
let dir = raw.trim_end_matches('/').to_ascii_lowercase();
if dir.len() <= 1 || !dir.starts_with('/') {
return Vec::new();
}
let mut out = vec![format!("{dir}/")];
if let Some(rest) = dir.strip_prefix("/private/") {
out.push(format!("/{rest}/"));
} else if dir == "/tmp" || dir.starts_with("/tmp/") || dir == "/var" || dir.starts_with("/var/") {
out.push(format!("/private{dir}/"));
}
out
}
pub(crate) fn physical_directory(path: &str) -> String {
if !path.starts_with('/') {
return path.to_string();
}
physical::resolve(path, true).unwrap_or_else(|| path.to_string())
}
thread_local! {
static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
#[must_use]
pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
STDIN_REPR.with(|v| v.borrow_mut().push(repr));
StdinReprGuard
}
pub fn stdin_item_repr() -> Option<String> {
STDIN_REPR.with(|v| v.borrow().last().cloned())
}
pub struct StdinReprGuard;
impl Drop for StdinReprGuard {
fn drop(&mut self) {
STDIN_REPR.with(|v| {
v.borrow_mut().pop();
});
}
}
thread_local! {
static RIPGREP_CONFIG: RefCell<Vec<bool>> = const { RefCell::new(Vec::new()) };
}
pub(crate) const RIPGREP_CONFIG_PATH: &str = "RIPGREP_CONFIG_PATH";
#[must_use]
pub(crate) fn bind_ripgrep_config(follows: Option<bool>) -> RipgrepConfigGuard {
if let Some(follows) = follows {
RIPGREP_CONFIG.with(|v| v.borrow_mut().push(follows));
}
RipgrepConfigGuard { pushed: follows.is_some() }
}
pub(crate) fn ripgrep_config_follows() -> bool {
RIPGREP_CONFIG
.with(|v| v.borrow().last().copied())
.unwrap_or_else(|| config_file_follows(std::env::var_os(RIPGREP_CONFIG_PATH), cwd().as_deref()))
}
fn config_file_follows(path: Option<std::ffi::OsString>, cwd: Option<&str>) -> bool {
let Some(path) = path.filter(|path| !path.is_empty()).map(std::path::PathBuf::from) else {
return false;
};
let path = match cwd {
_ if path.is_absolute() => path,
Some(cwd) => std::path::Path::new(cwd).join(path),
None => return true,
};
std::fs::read_to_string(path).map_or(true, |text| {
text.lines()
.map(str::trim)
.any(|line| line.starts_with("--follow") || (line.starts_with('-') && !line.starts_with("--") && line.contains('L')))
})
}
pub(crate) struct RipgrepConfigGuard {
pushed: bool,
}
impl Drop for RipgrepConfigGuard {
fn drop(&mut self) {
if self.pushed {
RIPGREP_CONFIG.with(|v| {
v.borrow_mut().pop();
});
}
}
}
pub fn resolve(path: &str) -> Cow<'_, str> {
resolve_placed(path, None)
}
pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
if use_.mutates() {
folder::note_named_write();
}
resolve_placed(path, Some(use_))
}
pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
join_cwd_mode(cur, target, false)
}
pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
let expanded = match expand_home(target) {
Some(t) => t,
None => return Some(UNRESOLVED_CWD.to_string()), };
if names_no_known_directory(&expanded) {
return Some(UNRESOLVED_CWD.to_string());
}
let raw = if let Some(landed) = declared_substitution_directory(cur, &expanded) {
landed
} else if expanded.starts_with('/') {
expanded.into_owned()
} else {
let c = cur.filter(|c| c.starts_with('/'))?;
format!("{c}/{expanded}")
};
Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
}
fn declared_substitution_directory(cur: Option<&str>, expanded: &str) -> Option<String> {
use crate::engine::facet::{FacetTerm, LocalLocus};
let after = expanded.strip_prefix(crate::cst::eval::TAGGED_PREFIX)?;
let (term, tail) = after.split_once("__").unwrap_or(("", ""));
let Some(tag) = LocalLocus::from_term(&term.to_lowercase().replace('_', "-")) else {
return Some(UNRESOLVED_CWD.to_string());
};
let Some(cur) = cur.filter(|c| c.starts_with('/') && *c != UNRESOLVED_CWD) else {
return Some(UNRESOLVED_CWD.to_string());
};
let here = crate::engine::resolve::locus::read_locus(cur);
if here == tag {
let rel = tail.trim_start_matches('/');
return Some(if rel.is_empty() { cur.to_string() } else { lexical::lexical_join(cur, rel) });
}
let in_band = |locus: LocalLocus| locus >= LocalLocus::SandboxScope && locus <= LocalLocus::WorktreeTrusted;
if in_band(tag) && !in_band(here) {
return Some(UNRESOLVED_CWD.to_string());
}
let base = match tag {
LocalLocus::Temp => "/tmp",
_ => return Some(UNRESOLVED_CWD.to_string()),
};
let rel = tail.trim_start_matches('/');
Some(if rel.is_empty() { base.to_string() } else { lexical::lexical_join(base, rel) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_inherited_ripgrep_config_follows_when_it_says_so_or_cannot_be_read() {
let dir = tempfile::tempdir().expect("scratch");
let cwd = dir.path().to_str().expect("utf-8");
for (name, text) in [
("long", "--follow\n"),
("short", " -iL\n"),
("plain", "--smart-case\n--max-columns=10\n"),
("glob", "--glob=*L*\n--type-add=L:*.l\n"),
] {
std::fs::write(dir.path().join(name), text).expect("config");
}
let follows = |path: Option<&str>, cwd: Option<&str>| config_file_follows(path.map(Into::into), cwd);
assert!(follows(Some("long"), Some(cwd)));
assert!(follows(Some("short"), Some(cwd)));
assert!(follows(Some("missing"), Some(cwd)));
assert!(follows(Some("plain"), None));
assert!(!follows(Some("plain"), Some(cwd)));
assert!(!follows(Some("glob"), Some(cwd)));
assert!(!follows(Some(dir.path().join("plain").to_str().expect("utf-8")), None));
assert!(!follows(Some(""), Some(cwd)));
assert!(!follows(None, Some(cwd)));
}
const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
f()
}
#[test]
fn only_this_sessions_scratchpad_is_recognized() {
let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
let matching: &[String] = &[
format!("{scratch}/build.sh"),
format!("{scratch}/nested/deep/gen.py"),
scratch.clone(),
format!("/tmp/{SID}/x.sh"),
format!("/tmp/some-other-harness/{SID}/work/x.sh"),
format!("/var/tmp/{SID}/x.sh"),
];
let rejected: &[String] = &[
"/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
format!("/tmp/{SID}-evil/x.sh"),
format!("/tmp/evil-{SID}/x.sh"),
format!("/tmp/a{SID}/x.sh"),
format!("/home/u/{SID}/x.sh"),
format!("~/.ssh/{SID}/id_rsa"),
format!("/etc/{SID}/passwd"),
"/tmp/evil.sh".into(),
"/private/tmp/downloaded.sh".into(),
format!("/TMP/{SID}/x.sh"),
format!("/System/Volumes/Data/tmp/{SID}/x.sh"),
format!("/private/var/folders/xx/yy/T/{SID}/x.sh"),
];
with_session(Some(SID), || {
for p in matching {
assert!(in_session_scratchpad(p), "should be recognized: {p}");
}
for p in rejected {
assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
}
});
}
#[test]
fn a_missing_or_unusable_session_id_recognizes_nothing() {
let path = format!("/tmp/{SID}/x.sh");
with_session(None, || {
assert!(!in_session_scratchpad(&path), "no session id → no recognition");
});
for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
with_session(Some(weak), || {
assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
});
}
}
#[test]
fn under_temp_never_slices_inside_a_multibyte_character() {
let prefix = "/system/volumes/data";
for filler in ["\u{fffd}", "\u{e9}", "\u{1f600}"] {
for cut in 0..=prefix.len() {
let path = format!("{}{filler}{}", &prefix[..cut], &prefix[cut..]);
assert!(!under_temp(&path), "{path}");
}
}
assert!(under_temp("/System/Volumes/Data/tmp/x"));
}
#[test]
fn under_temp_folds_case_firmlinks_and_var_folders_without_admitting_them() {
for path in [
"/TMP/y", "/Tmp/y", "/PRIVATE/TMP/y", "/private/TMP/y", "/System/Volumes/Data/tmp/y", "/System/Volumes/Data/private/tmp/y",
"/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",
] {
assert!(under_temp(path), "{path}");
assert!(crate::engine::resolve::locus::under_temp(path), "locus: {path}");
assert!(!under_temp_root(path), "exact prefix must stay strict: {path}");
}
assert!(under_temp("/tmp/y"));
assert!(under_temp_root("/tmp/y"));
assert!(!under_temp("/etc/y"));
assert!(!under_temp("/tmpfile/y"));
}
#[test]
fn no_context_leaves_paths_unchanged() {
assert_eq!(resolve("./x"), "./x");
assert_eq!(resolve("config"), "config");
assert_eq!(resolve("/etc/x"), "/etc/x");
}
#[test]
fn relative_inside_the_project_stays_worktree_relative() {
let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
assert_eq!(resolve("./y"), "sub/y");
assert_eq!(resolve("../z"), "z", ".. that stays inside root");
}
#[test]
fn relative_outside_the_project_becomes_absolute() {
let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
assert_eq!(resolve("passwd"), "/etc/passwd");
assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
}
#[test]
fn dotdot_escaping_the_project_becomes_absolute() {
let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
assert_eq!(resolve("../../../etc/x"), "/etc/x");
}
#[test]
fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
assert_eq!(
resolve("/home/u/proj-evil/secret"),
"/home/u/proj-evil/secret",
"a sibling dir is not confused for inside by bare string prefix",
);
assert_eq!(resolve("$HOME/x"), "$HOME/x");
assert_eq!(resolve("~/x"), "~/x");
}
#[test]
fn a_home_spelled_path_inside_root_becomes_root_relative() {
let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
return;
};
let root = format!("{home}/projects/app");
let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
assert_eq!(resolve("~/projects/app"), ".");
assert_eq!(resolve("~/projects/app/"), ".");
let under = |rest: &str| format!("~/projects/{rest}");
assert_eq!(resolve(&under("app/a/../b")), "b");
assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
}
assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
assert_eq!(resolve("~"), "~");
assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
}
#[test]
fn a_home_spelled_path_needs_an_absolute_root() {
let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
assert_eq!(resolve("~/x"), "~/x");
drop(_none);
let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
assert_eq!(resolve("~/x"), "~/x");
}
#[test]
fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
return;
};
let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
assert_eq!(resolve("~"), "~");
assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
assert_eq!(resolve("."), home);
}
#[test]
fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
return;
};
let root = format!("{home}/projects/app");
let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
drop(outside);
let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
assert_eq!(resolve(&glob), glob);
}
}
#[test]
fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
return;
};
let root = format!("{home}/.ssh");
let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
}
#[test]
fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
assert_eq!(resolve("etc"), "/etc");
assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
assert_eq!(resolve("."), "/");
drop(_g);
let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
assert_eq!(resolve("sudoers"), "/etc/sudoers");
assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
drop(_etc);
let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
}
#[test]
fn loop_var_expands_to_its_representative_per_face() {
let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
assert_eq!(expand_vars("$f", false), "read_item");
assert_eq!(expand_vars("$f", true), "write_item");
assert_eq!(expand_vars("${f}", false), "read_item");
assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
assert_eq!(expand_vars("plain", false), "plain");
}
#[test]
fn loop_var_binding_is_scoped_and_nests() {
assert_eq!(expand_vars("$f", false), "$f", "no binding");
{
let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
{
let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
}
assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
}
assert_eq!(expand_vars("$f", false), "$f", "all popped");
}
#[test]
fn the_guard_restores_on_drop() {
{
let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
assert_eq!(resolve("x"), "/etc/x");
}
assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
}
const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
.args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
.env("TMPDIR", tmpdir)
.env(PROBE_VAR, path)
.output()
.expect("spawn probe");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
(true, false) => true,
(false, true) => false,
_ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
}
}
#[test]
fn tmpdir_probe() {
let Ok(path) = std::env::var(PROBE_VAR) else {
return;
};
println!("PROBE_VERDICT={}", under_temp_root(&path));
}
#[test]
fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
for (tmpdir, path, expected) in [
("/work/scratch", "/work/scratch/x.sh", true),
("/work/scratch/", "/work/scratch/x.sh", true),
("/work/scratch//", "/work/scratch/nested/x.sh", true),
("/work/scratch", "/work/scratch", false),
("/work/scratch", "/work/scratchy/x.sh", false),
("/work/scratch", "/work/other/x.sh", false),
("/work/scratch", "work/scratch/x.sh", false),
("", "/x.sh", false),
("", "/", false),
("/", "/x.sh", false),
("//", "/x.sh", false),
("scratch", "scratch/x.sh", false),
("scratch/", "scratch/x.sh", false),
("./scratch", "./scratch/x.sh", false),
("$SCRATCH", "$SCRATCH/x.sh", false),
("relative/dir", "relative/dir/x.sh", false),
] {
assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
}
}
#[test]
fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
for tmpdir in ["", "scratch", "/work/scratch"] {
for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
}
assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
}
}
}