bynk_project/
workspace.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Workspace {
29 pub root: PathBuf,
31 pub config: WorkspaceConfig,
32 pub members: Vec<PathBuf>,
35}
36
37pub 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
47pub 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 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#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct ImplicitWorkspace {
88 pub workspace: Workspace,
91 pub skipped: Vec<PathBuf>,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ImplicitWorkspaceError {
99 RootSources,
102 NoProjects { deeper: Vec<PathBuf> },
106}
107
108pub 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
151pub 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
164fn 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
189fn 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
234fn 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
249fn 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 ¤t {
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
277fn 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
286fn 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
311fn 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}