Skip to main content

bynk_project/
workspace.rs

1//! Packaging slice 1 (#2207, decision C): workspaces.
2//!
3//! A workspace root is a directory whose `bynk.toml` holds `[workspace]` (and
4//! may hold `[registries]`) and nothing else: it is never a project itself, the
5//! Cargo "virtual manifest". Its members are the directories `members` matches,
6//! minus those `exclude` matches, each holding its own `bynk.toml`.
7//!
8//! A pattern is a relative path whose components may use `*` (any run of
9//! characters) and `?` (one character); each `*` matches within one directory
10//! level. A hidden directory is matched only by a component that itself starts
11//! with `.`.
12//!
13//! A project finds the workspace it belongs to by walking up for a `[workspace]`
14//! whose members include it ([`find_parent_workspace`]). A parent `bynk.toml`
15//! that doesn't parse, has an unknown table, or doesn't list the project counts
16//! as absent, so one broken unrelated manifest can't break every project nested
17//! under it.
18
19use std::collections::{BTreeSet, HashMap};
20use std::fs;
21use std::path::{Component, Path, PathBuf};
22
23use crate::manifest::{WorkspaceConfig, workspace_config_from};
24use crate::paths::{ProjectPathsError, check_manifest_str};
25
26/// A loaded workspace root and its members.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Workspace {
29    /// The root directory, as the caller named it.
30    pub root: PathBuf,
31    pub config: WorkspaceConfig,
32    /// Each member's directory relative to `root`, sorted, so every command
33    /// runs over them in the same order.
34    pub members: Vec<PathBuf>,
35}
36
37/// Whether `dir`'s `bynk.toml` parses and holds a `[workspace]` table. A
38/// manifest that doesn't parse isn't a workspace root: the command that reads
39/// it next reports it as malformed.
40pub fn is_workspace_root(dir: &Path) -> bool {
41    fs::read_to_string(dir.join("bynk.toml"))
42        .ok()
43        .and_then(|text| text.parse::<toml::Table>().ok())
44        .is_some_and(|doc| doc.contains_key("workspace"))
45}
46
47/// Load the workspace rooted at `root`: check its manifest, refuse sources at
48/// the root, and resolve its members. A workspace whose patterns match no
49/// member is an error, as an unknown table is (#1665).
50pub fn load_workspace(root: &Path) -> Result<Workspace, ProjectPathsError> {
51    let manifest = root.join("bynk.toml");
52    let text = fs::read_to_string(&manifest).map_err(|_| ProjectPathsError::Malformed)?;
53    // Path-aware, so a member of an enclosing workspace that declares its own
54    // `[workspace]` is refused as that, before anything else.
55    crate::paths::check_manifest(root, &HashMap::from([(manifest, text.clone())]))?;
56    let doc = text
57        .parse::<toml::Table>()
58        .map_err(|_| ProjectPathsError::Malformed)?;
59    let Some(table) = doc.get("workspace").and_then(|v| v.as_table()) else {
60        return Err(ProjectPathsError::BadWorkspace {
61            reason: "is missing".to_string(),
62        });
63    };
64    let config = workspace_config_from(table)?;
65    if root.join("src").is_dir() || has_bynk_file(root) {
66        return Err(ProjectPathsError::WorkspaceRootSources);
67    }
68    let members = expand_members(root, &config)?;
69    if members.is_empty() {
70        return Err(ProjectPathsError::BadWorkspace {
71            reason: format!(
72                "matches no member: no directory under the root matches {}",
73                quoted_list(&config.members)
74            ),
75        });
76    }
77    Ok(Workspace {
78        root: root.to_path_buf(),
79        config,
80        members,
81    })
82}
83
84/// #3274: the workspace a manifest-less directory of projects stands for under
85/// `--each`, with what it set aside.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct ImplicitWorkspace {
88    /// Exactly what `[workspace] members = ["*"]` at `root` would give, so every
89    /// command runs it down the same path as a real workspace.
90    pub workspace: Workspace,
91    /// Immediate subdirectories that hold `.bynk` files but no `bynk.toml`:
92    /// not projects, so not members, but named so nothing is ignored silently.
93    pub skipped: Vec<PathBuf>,
94}
95
96/// Why a directory is not an implicit workspace.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ImplicitWorkspaceError {
99    /// `.bynk` files sit directly in the directory, which no member would read,
100    /// as at a workspace root ([`ProjectPathsError::WorkspaceRootSources`]).
101    RootSources,
102    /// No immediate subdirectory holds a `bynk.toml`. `deeper` lists the
103    /// outermost projects further down, if any; an implicit workspace never
104    /// reaches past one level.
105    NoProjects { deeper: Vec<PathBuf> },
106}
107
108/// #3274: the implicit workspace at `root`, a directory with no `bynk.toml`
109/// of its own. Its members are the immediate subdirectories that hold a
110/// `bynk.toml`, in name order: `members = ["*"]` as a real workspace reads it,
111/// except that a subdirectory without a manifest is set aside rather than an
112/// error (a repository of examples keeps a `docs/` beside them). Directories
113/// that discovery skips (hidden, `out`, `node_modules`) are never members.
114pub fn implicit_workspace(root: &Path) -> Result<ImplicitWorkspace, ImplicitWorkspaceError> {
115    if has_bynk_file(root) {
116        return Err(ImplicitWorkspaceError::RootSources);
117    }
118    let mut members = BTreeSet::new();
119    let mut skipped = BTreeSet::new();
120    let entries = fs::read_dir(root).map(|rd| rd.flatten().collect::<Vec<_>>());
121    for entry in entries.unwrap_or_default() {
122        let path = entry.path();
123        if !path.is_dir() || crate::discovery::is_skipped_dir(&path, &[]) {
124            continue;
125        }
126        let rel = PathBuf::from(entry.file_name());
127        if crate::discovery::is_project_boundary(&path) {
128            members.insert(rel);
129        } else if crate::discovery::holds_bynk_source(&path) {
130            skipped.insert(rel);
131        }
132    }
133    if members.is_empty() {
134        return Err(ImplicitWorkspaceError::NoProjects {
135            deeper: crate::discovery::nested_projects(root, &[]),
136        });
137    }
138    Ok(ImplicitWorkspace {
139        workspace: Workspace {
140            root: root.to_path_buf(),
141            config: WorkspaceConfig {
142                members: vec!["*".to_string()],
143                exclude: Vec::new(),
144            },
145            members: members.into_iter().collect(),
146        },
147        skipped: skipped.into_iter().collect(),
148    })
149}
150
151/// The workspace root above `project_root` whose members include it, if any.
152pub fn find_parent_workspace(project_root: &Path) -> Option<PathBuf> {
153    let me = project_root.canonicalize().ok()?;
154    let mut dir = me.parent();
155    while let Some(candidate) = dir {
156        if lists(candidate, &me) {
157            return Some(candidate.to_path_buf());
158        }
159        dir = candidate.parent();
160    }
161    None
162}
163
164/// Whether `root`'s manifest is a well-formed workspace that lists `member`
165/// (canonical). Anything short of that is "not listed".
166fn lists(root: &Path, member: &Path) -> bool {
167    let Ok(text) = fs::read_to_string(root.join("bynk.toml")) else {
168        return false;
169    };
170    if check_manifest_str(&text).is_err() {
171        return false;
172    }
173    let Some(config) = text
174        .parse::<toml::Table>()
175        .ok()
176        .and_then(|doc| doc.get("workspace")?.as_table().cloned())
177        .and_then(|t| workspace_config_from(&t).ok())
178    else {
179        return false;
180    };
181    let Ok(members) = expand_members(root, &config) else {
182        return false;
183    };
184    members
185        .iter()
186        .any(|m| root.join(m).canonicalize().is_ok_and(|c| c == member))
187}
188
189/// The members `config` resolves to under `root`: every directory a `members`
190/// pattern matches that no `exclude` pattern matches, relative and sorted. A
191/// literal entry that doesn't exist, or a member without a `bynk.toml`, is an
192/// error; a wildcard entry that matches nothing contributes nothing.
193fn expand_members(
194    root: &Path,
195    config: &WorkspaceConfig,
196) -> Result<Vec<PathBuf>, ProjectPathsError> {
197    let bad = |reason: String| ProjectPathsError::BadWorkspace { reason };
198    let mut found: BTreeSet<PathBuf> = BTreeSet::new();
199    for pattern in &config.members {
200        let parts = components(pattern);
201        let matches = matching_dirs(root, &parts);
202        if matches.is_empty() && !parts.iter().any(|p| is_wildcard(p)) {
203            return Err(bad(format!(
204                "`members` lists `{pattern}`, which isn't a directory under the workspace root"
205            )));
206        }
207        found.extend(matches);
208    }
209    let mut members = Vec::new();
210    for rel in found {
211        let excluded = config
212            .exclude
213            .iter()
214            .any(|ex| excludes(&components(ex), &rel));
215        if excluded {
216            continue;
217        }
218        let shown = rel.to_string_lossy().replace('\\', "/");
219        if rel.as_os_str().is_empty() {
220            return Err(bad(
221                "`members` matches the workspace root itself, which is never a member".to_string(),
222            ));
223        }
224        if !root.join(&rel).join("bynk.toml").is_file() {
225            return Err(bad(format!(
226                "member `{shown}` has no `bynk.toml` — add one, or `exclude` it"
227            )));
228        }
229        members.push(rel);
230    }
231    Ok(members)
232}
233
234/// A pattern's normal components (`./` and empty segments dropped).
235fn components(pattern: &str) -> Vec<String> {
236    Path::new(pattern)
237        .components()
238        .filter_map(|c| match c {
239            Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
240            _ => None,
241        })
242        .collect()
243}
244
245fn is_wildcard(part: &str) -> bool {
246    part.contains(['*', '?'])
247}
248
249/// The directories under `root` that `parts` match, relative to `root`.
250fn matching_dirs(root: &Path, parts: &[String]) -> Vec<PathBuf> {
251    let mut current = vec![PathBuf::new()];
252    for part in parts {
253        let mut next = Vec::new();
254        for base in &current {
255            if is_wildcard(part) {
256                let Ok(entries) = fs::read_dir(root.join(base)) else {
257                    continue;
258                };
259                let mut names: Vec<String> = entries
260                    .filter_map(Result::ok)
261                    .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
262                    .map(|e| e.file_name().to_string_lossy().into_owned())
263                    .filter(|n| part.starts_with('.') || !n.starts_with('.'))
264                    .filter(|n| wildcard_match(part, n))
265                    .collect();
266                names.sort();
267                next.extend(names.into_iter().map(|n| base.join(n)));
268            } else if root.join(base).join(part).is_dir() {
269                next.push(base.join(part));
270            }
271        }
272        current = next;
273    }
274    current
275}
276
277/// Whether the exclude pattern `parts` matches `member` or a directory above it.
278fn excludes(parts: &[String], member: &Path) -> bool {
279    let names: Vec<String> = member
280        .components()
281        .map(|c| c.as_os_str().to_string_lossy().into_owned())
282        .collect();
283    parts.len() <= names.len() && parts.iter().zip(&names).all(|(p, n)| wildcard_match(p, n))
284}
285
286/// `*` and `?` matching over one path component.
287fn wildcard_match(pattern: &str, name: &str) -> bool {
288    let p: Vec<char> = pattern.chars().collect();
289    let n: Vec<char> = name.chars().collect();
290    let (mut pi, mut ni) = (0, 0);
291    let (mut star, mut mark) = (None, 0);
292    while ni < n.len() {
293        if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
294            pi += 1;
295            ni += 1;
296        } else if pi < p.len() && p[pi] == '*' {
297            star = Some(pi);
298            mark = ni;
299            pi += 1;
300        } else if let Some(s) = star {
301            pi = s + 1;
302            mark += 1;
303            ni = mark;
304        } else {
305            return false;
306        }
307    }
308    p[pi..].iter().all(|c| *c == '*')
309}
310
311/// Whether `dir` holds a `.bynk` file directly.
312fn has_bynk_file(dir: &Path) -> bool {
313    fs::read_dir(dir).is_ok_and(|entries| {
314        entries
315            .filter_map(Result::ok)
316            .any(|e| e.path().extension().is_some_and(|x| x == "bynk") && e.path().is_file())
317    })
318}
319
320fn quoted_list(items: &[String]) -> String {
321    if items.is_empty() {
322        return "nothing (`members` is empty)".to_string();
323    }
324    items
325        .iter()
326        .map(|i| format!("`{i}`"))
327        .collect::<Vec<_>>()
328        .join(", ")
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn wildcards_match_within_a_component() {
337        assert!(wildcard_match("*", "money"));
338        assert!(wildcard_match("m*y", "money"));
339        assert!(wildcard_match("mon?y", "money"));
340        assert!(!wildcard_match("m*x", "money"));
341        assert!(wildcard_match("money", "money"));
342        assert!(!wildcard_match("mone", "money"));
343    }
344
345    #[test]
346    fn an_exclude_covers_a_member_and_everything_under_it() {
347        let ex = components("packages/scratch");
348        assert!(excludes(&ex, Path::new("packages/scratch")));
349        assert!(excludes(&ex, Path::new("packages/scratch/inner")));
350        assert!(!excludes(&ex, Path::new("packages/money")));
351        assert!(excludes(
352            &components("packages/s*"),
353            Path::new("packages/scratch")
354        ));
355    }
356}