Skip to main content

safe_chains/pathctx/
root.rs

1//! The project root a command is judged against.
2
3use super::{CURRENT, UNRESOLVED_CWD, folder};
4
5/// The project root a command is judged against.
6///
7/// An unknown root is a value, not an absence, so no consumer can read it as "no boundary": each
8/// has to match on [`Root::Unknown`] and say what it does then, and every place that grants
9/// something on the strength of the root fails closed there. The ratchet test
10/// `root_consumers_tests` lists every consumer.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum Root {
13    Known(String),
14    Unknown,
15}
16
17/// The workspace ROOT (project dir), falling back to `cwd` (the hook defaults root to cwd), or
18/// [`Root::Unknown`] when the context names a folder that is not a usable one: the unknown-folder
19/// sentinel, or a `cd` that could not be resolved.
20///
21/// An evaluation that was handed no context at all (a library caller, not a harness) has no
22/// workspace boundary to be wrong about, so its root is the empty `Known("")`: not an absolute
23/// path, so nothing is placed in it, and not unknown, so relative paths keep classifying as they
24/// always did without one. A harness always enters a context.
25pub fn root() -> Root {
26    CURRENT.with(|c| {
27        let b = c.borrow();
28        if b.cwd.is_none() && b.root.is_none() {
29            return Root::Known(String::new());
30        }
31        match b.root.as_ref().or(b.cwd.as_ref()).filter(|r| !folder::is_unknown(r) && *r != UNRESOLVED_CWD) {
32            Some(root) => Root::Known(root.clone()),
33            None => Root::Unknown,
34        }
35    })
36}
37
38/// The folder the command runs in on disk: the working directory, or, in the unknown folder, the
39/// one the harness reported with any `cd` below it applied. `None` when neither names a real place.
40pub(crate) fn folder_on_disk() -> Option<String> {
41    let cwd = super::cwd()?;
42    let Some(below) = cwd.strip_prefix(crate::targets::UNKNOWN_WORKDIR) else {
43        return (cwd != UNRESOLVED_CWD).then_some(cwd);
44    };
45    if !(below.is_empty() || below.starts_with('/')) {
46        return None;
47    }
48    super::place::folder_below(&cwd)
49}