Skip to main content

nativeview_view_syntax/workspace/
mod.rs

1//! Single-sourced Cargo workspace & crate-root discovery and canonical path normalization
2//! shared between `nativeview-view-macros` and `nativeview-cli` (`hot_diff` / `view_diff`) so
3//! `AnchorKey` hashes never drift across crates, standalone examples, or OSes.
4
5mod toml_min;
6
7use std::path::{Path, PathBuf};
8
9use crate::anchor::{normalize_rel_file, workspace_rel_file};
10use toml_min::{parse_cargo_manifest_info, CargoManifestInfo};
11
12/// Canonicalizes `path`, absolutizing relative paths and falling back to canonicalizing the
13/// nearest existing ancestor when `path` does not exist yet (e.g. deleted files or macOS `/var`
14/// vs `/private/var` symlinks).
15pub fn canonicalize_preserving_missing(path: &Path) -> PathBuf {
16    if let Ok(c) = std::fs::canonicalize(path) {
17        return c;
18    }
19    let abs = if path.is_absolute() {
20        path.to_path_buf()
21    } else if let Ok(cwd) = std::env::current_dir() {
22        cwd.join(path)
23    } else {
24        path.to_path_buf()
25    };
26    if let Ok(c) = std::fs::canonicalize(&abs) {
27        return c;
28    }
29    let mut tail = Vec::new();
30    let mut cur = abs.as_path();
31    while let Some(name) = cur.file_name() {
32        tail.push(name.to_os_string());
33        let Some(parent) = cur.parent() else {
34            break;
35        };
36        cur = parent;
37        if let Ok(mut base) = std::fs::canonicalize(cur) {
38            for part in tail.into_iter().rev() {
39                base.push(part);
40            }
41            return base;
42        }
43    }
44    abs
45}
46
47/// Resolves `path` to a canonical workspace-relative (or standalone crate-relative) POSIX path
48/// using `/` separators with `\\?\` verbatim prefixes stripped.
49///
50/// Resolution order:
51/// 1. If `explicit_root` is provided and `path` lies inside it, returns `path` relative to
52///    `explicit_root`.
53/// 2. Enclosing Cargo `[workspace]` root whose `members` includes this crate (and `exclude` does
54///    not exclude it), honoring `[package] workspace = "..."` when present.
55/// 3. Nearest enclosing crate `Cargo.toml` directory (for standalone or excluded crates).
56/// 4. Normalized canonical absolute path if no enclosing `Cargo.toml` exists.
57pub fn resolve_workspace_rel_file(path: &Path, explicit_root: Option<&Path>) -> String {
58    let canon = canonicalize_preserving_missing(path);
59    let canon_str = canon.to_string_lossy();
60    let normalized_abs = workspace_rel_file(&canon_str, "");
61
62    if let Some(root) = explicit_root {
63        let canon_root = canonicalize_preserving_missing(root);
64        let rel = workspace_rel_file(&canon_str, &canon_root.to_string_lossy());
65        if rel != normalized_abs {
66            return rel;
67        }
68    }
69
70    let root = find_workspace_root(&canon).or_else(|| find_crate_root(&canon));
71    if let Some(root) = root {
72        workspace_rel_file(&canon_str, &root.to_string_lossy())
73    } else {
74        normalized_abs
75    }
76}
77
78/// Finds the enclosing Cargo workspace root for canonicalized `path`, returning `None` for
79/// standalone or excluded crates.
80pub fn find_workspace_root(path: &Path) -> Option<PathBuf> {
81    let crate_root = find_crate_root(path)?;
82    if let Some(crate_manifest) = read_manifest_info(&crate_root) {
83        if crate_manifest.has_workspace {
84            return Some(crate_root);
85        }
86        if let Some(explicit_ws) = crate_manifest.package_workspace {
87            let ws_dir = canonicalize_preserving_missing(&crate_root.join(explicit_ws));
88            if read_manifest_info(&ws_dir).is_some_and(|m| m.has_workspace) {
89                return Some(ws_dir);
90            }
91        }
92    }
93
94    let mut cur = crate_root.parent();
95    while let Some(dir) = cur {
96        if let Some(manifest) = read_manifest_info(dir)
97            && manifest.has_workspace
98        {
99            let rel_crate = workspace_rel_file(
100                &crate_root.to_string_lossy(),
101                &dir.to_string_lossy(),
102            );
103            if workspace_excludes(&manifest.exclude, &rel_crate) {
104                return None;
105            }
106            if workspace_includes(&manifest.members, &rel_crate) {
107                return Some(dir.to_path_buf());
108            }
109            // Enclosing `[workspace]` does not list this crate as a member -> standalone crate.
110            return None;
111        }
112        cur = dir.parent();
113    }
114    None
115}
116
117/// Finds the nearest enclosing directory containing a `Cargo.toml` file.
118pub fn find_crate_root(path: &Path) -> Option<PathBuf> {
119    let mut cur = path.parent();
120    while let Some(dir) = cur {
121        if dir.join("Cargo.toml").is_file() {
122            return Some(dir.to_path_buf());
123        }
124        cur = dir.parent();
125    }
126    None
127}
128
129fn read_manifest_info(dir: &Path) -> Option<CargoManifestInfo> {
130    let manifest = dir.join("Cargo.toml");
131    if !manifest.is_file() {
132        return None;
133    }
134    let text = std::fs::read_to_string(&manifest).ok()?;
135    Some(parse_cargo_manifest_info(&text))
136}
137
138fn workspace_excludes(excludes: &[String], rel_crate: &str) -> bool {
139    excludes.iter().any(|pat| {
140        let norm_pat = normalize_pattern(pat);
141        matches_path_or_ancestor(&norm_pat, rel_crate)
142    })
143}
144
145fn workspace_includes(members: &[String], rel_crate: &str) -> bool {
146    members.iter().any(|pat| {
147        let norm_pat = normalize_pattern(pat);
148        glob_path_matches(&norm_pat, rel_crate)
149    })
150}
151
152fn normalize_pattern(raw: &str) -> String {
153    normalize_rel_file(raw).trim_end_matches('/').to_owned()
154}
155
156fn matches_path_or_ancestor(pattern: &str, rel_path: &str) -> bool {
157    if glob_path_matches(pattern, rel_path) {
158        return true;
159    }
160    let mut cur = rel_path;
161    while let Some((parent, _)) = cur.rsplit_once('/') {
162        if glob_path_matches(pattern, parent) {
163            return true;
164        }
165        cur = parent;
166    }
167    false
168}
169
170fn glob_path_matches(pattern: &str, path: &str) -> bool {
171    let pat_segs: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
172    let path_segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
173    glob_segs_match(&pat_segs, &path_segs)
174}
175
176fn glob_segs_match(pat: &[&str], path: &[&str]) -> bool {
177    match (pat.first(), path.first()) {
178        (None, None) => true,
179        (Some(&"**"), _) => {
180            glob_segs_match(&pat[1..], path)
181                || (!path.is_empty() && glob_segs_match(pat, &path[1..]))
182        }
183        (Some(p), Some(s)) => {
184            wildcard_seg_match(p.as_bytes(), s.as_bytes())
185                && glob_segs_match(&pat[1..], &path[1..])
186        }
187        _ => false,
188    }
189}
190
191fn wildcard_seg_match(pat: &[u8], text: &[u8]) -> bool {
192    let (mut pi, mut ti) = (0usize, 0usize);
193    let mut star_pi: Option<usize> = None;
194    let mut star_ti = 0usize;
195    while ti < text.len() {
196        if pi < pat.len() && (pat[pi] == b'?' || pat[pi] == text[ti]) {
197            pi += 1;
198            ti += 1;
199        } else if pi < pat.len() && pat[pi] == b'*' {
200            star_pi = Some(pi);
201            pi += 1;
202            star_ti = ti;
203        } else if let Some(sp) = star_pi {
204            pi = sp + 1;
205            star_ti += 1;
206            ti = star_ti;
207        } else {
208            return false;
209        }
210    }
211    while pi < pat.len() && pat[pi] == b'*' {
212        pi += 1;
213    }
214    pi == pat.len()
215}