Skip to main content

raf_source/
root.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! Workspace-root lookup over the bounded tree and membership model.
5
6use crate::error::{LoadError, LoadErrorKind, Origin};
7use crate::manifest::{self, Manifest};
8use crate::members::members;
9use crate::meter::Meter;
10use crate::modtree::tidy;
11use crate::{DEFAULT_MAX_FILE_BYTES, EntryKind, LoadOptions, RelPath, Tree};
12
13fn finding(path: &RelPath, message: impl Into<String>) -> LoadError {
14    LoadError::new(
15        path,
16        None,
17        LoadErrorKind::Manifest {
18            message: message.into(),
19            source: None,
20        },
21    )
22}
23
24fn read(tree: &dyn Tree, dir: &RelPath) -> Result<Option<Manifest>, LoadError> {
25    let path = dir.join("Cargo.toml").expect("a literal child");
26    if tree
27        .entry(&path)
28        .map_err(|error| LoadError::tree(&path, None, &Origin::Discovery, error))?
29        .is_none()
30    {
31        return Ok(None);
32    }
33    let text = tree
34        .read(&path, DEFAULT_MAX_FILE_BYTES)
35        .map_err(|error| LoadError::tree(&path, None, &Origin::Discovery, error))?;
36    manifest::parse(&text).map(Some).map_err(|error| {
37        let origin = error
38            .key
39            .map_or(Origin::Discovery, |key| Origin::ManifestKey { key });
40        LoadError::new(
41            &path,
42            None,
43            LoadErrorKind::Manifest {
44                message: error.message,
45                source: error.source,
46            },
47        )
48        .reached_by(&origin)
49    })
50}
51
52fn owns(
53    tree: &dyn Tree,
54    root: &RelPath,
55    parsed: &Manifest,
56    package: &RelPath,
57) -> Result<bool, LoadError> {
58    let path = root.join("Cargo.toml").expect("a literal child");
59    let found = members(
60        tree,
61        &Meter::new(&LoadOptions::default()),
62        root,
63        &path,
64        parsed,
65    )?;
66    if found.contains(package) {
67        return Ok(true);
68    }
69    for member in found {
70        if directory(tree, &member)? == *package {
71            return Ok(true);
72        }
73    }
74    Ok(false)
75}
76
77pub(crate) fn directory(tree: &dyn Tree, path: &RelPath) -> Result<RelPath, LoadError> {
78    let path =
79        tidy(tree, path).map_err(|error| LoadError::tree(path, None, &Origin::Discovery, error))?;
80    let mut prefix = path.clone();
81    loop {
82        if prefix.segments().any(|segment| segment == "..")
83            || tree
84                .entry(&prefix)
85                .map_err(|error| LoadError::tree(&prefix, None, &Origin::Discovery, error))?
86                != Some(EntryKind::Dir)
87        {
88            return Err(finding(
89                &prefix,
90                "root discovery requires real directories without directory symlinks; canonicalize the starting directory first",
91            ));
92        }
93        let Some(parent) = prefix.parent() else {
94            break;
95        };
96        prefix = parent;
97    }
98    Ok(path)
99}
100
101/// Find the workspace root containing `start`, relative to the supplied tree.
102///
103/// The nearest `[workspace]` wins. A package belongs to it only when the
104/// bounded member walk includes it (including transitive path dependencies).
105/// An excluded package or a package without an ancestor workspace is its own
106/// root. An unlisted package is refused rather than assigned to an unrelated
107/// workspace. `package.workspace` selects an explicit workspace inside the
108/// tree, whose membership must agree. No source files or processes are needed.
109///
110/// # Errors
111///
112/// Returns a [`LoadError`] for an invalid starting directory, missing manifest,
113/// malformed or oversized manifest, inaccessible tree, conflicting workspace
114/// declarations, unlisted package, or membership walk exceeding its bounds.
115/// Discovery never walks above the caller's tree boundary.
116/// Directory symlinks are refused because their lexical ancestors need not be
117/// the ancestors of the directory they reach.
118pub fn discover_root(tree: &dyn Tree, start: &RelPath) -> Result<RelPath, LoadError> {
119    let start = directory(tree, start)?;
120    let mut current = Some(start.clone());
121    let mut package = None;
122    while let Some(dir) = current {
123        if let Some(parsed) = read(tree, &dir)? {
124            if package.is_none() && parsed.package.is_some() {
125                if let Some(target) = &parsed.package_workspace {
126                    if parsed.has_workspace {
127                        return Err(finding(
128                            &dir,
129                            "package.workspace conflicts with [workspace]",
130                        ));
131                    }
132                    let joined = dir
133                        .join(target)
134                        .map_err(|error| finding(&dir, error.to_string()))?;
135                    let root = directory(tree, &joined)?;
136                    let workspace = read(tree, &root)?
137                        .ok_or_else(|| finding(&root, "package.workspace has no Cargo.toml"))?;
138                    if !workspace.has_workspace || !owns(tree, &root, &workspace, &dir)? {
139                        return Err(finding(
140                            &dir,
141                            "package.workspace must name a workspace that includes this package",
142                        ));
143                    }
144                    return Ok(root);
145                }
146                package = Some(dir.clone());
147            }
148            if parsed.has_workspace {
149                let Some(package) = &package else {
150                    return Ok(dir);
151                };
152                if owns(tree, &dir, &parsed, package)? {
153                    return Ok(dir);
154                }
155                let parts: Vec<Vec<char>> = package
156                    .segments()
157                    .skip(dir.segments().count())
158                    .map(|part| part.chars().collect())
159                    .collect();
160                for text in &parsed.exclude {
161                    let pattern =
162                        crate::glob::Pattern::parse(text).map_err(|error| finding(&dir, error))?;
163                    if pattern.matches_prefix(&parts) {
164                        return Ok(package.clone());
165                    }
166                }
167                return Err(finding(
168                    package,
169                    "package is below a workspace but is not a member; add it to workspace.members, exclude it, or give it its own [workspace]",
170                ));
171            }
172        }
173        current = dir.parent();
174    }
175    package.ok_or_else(|| {
176        finding(
177            &start,
178            "no Cargo.toml package or workspace found in this directory or its ancestors",
179        )
180    })
181}