Repository navigation
Expand file tree
/
Copy pathpath_scope.rs
More file actions
312 lines (284 loc) · 11.6 KB
/
Copy pathpath_scope.rs
File metadata and controls
312 lines (284 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! Path-glob scoping shared by agent-mode (and report-only) `scan` and
//! `rollback`. (Hosted/vendored scan PATHS are project directories instead;
//! see `run_project_dirs`.)
//!
//! A [`PathScope`] holds the user's positional PATH patterns and answers
//! "is this installed-package directory in scope?". Matching rules
//! (documented in CLI_CONTRACT.md):
//!
//! * Patterns use Unix-shell glob syntax (`*`, `?`, `[...]`, `**`) with
//! `require_literal_separator` — `*` never crosses a `/`, `**` spans
//! directories.
//! * Relative patterns match the package path relative to `--cwd`;
//! absolute patterns match the absolute path (the only way to scope
//! packages outside the project tree, e.g. `--global` stores).
//! * A pattern that matches any ANCESTOR directory of the package path
//! also matches, so `scan --mode agent packages/foo` scopes the whole subtree
//! without needing an explicit `packages/foo/**`.
//! * Matching is purely textual on `/`-normalized paths — no filesystem
//! access, no symlink resolution.
//!
//! Scoping is PURL-level at the call sites: a package is in scope when
//! any of its discovered copies matches, and scoped operations then act
//! on every copy of the selected package.
use glob::{MatchOptions, Pattern};
use std::path::{Path, PathBuf};
/// `*` and `?` stay within one path component; `**` is the only way to
/// cross directories. Case-sensitive on Unix; case-insensitive on Windows,
/// whose filesystems are case-insensitive (a drive-letter case mismatch
/// must not silently empty a scope).
const MATCH_OPTIONS: MatchOptions = MatchOptions {
case_sensitive: cfg!(not(windows)),
require_literal_separator: true,
require_literal_leading_dot: false,
};
/// Parsed positional PATH patterns.
#[derive(Debug)]
pub struct PathScope {
patterns: Vec<(Pattern, bool)>, // (compiled, is_absolute)
raw: Vec<String>,
}
/// Normalize a pattern for matching: strip a leading `./`, trailing `/`s,
/// and convert `\` to `/` so Windows-style input still compiles to the
/// separator the match side uses.
fn normalize_pattern(raw: &str) -> String {
let mut p = raw.replace('\\', "/");
while let Some(stripped) = p.strip_prefix("./") {
p = stripped.to_string();
}
while p.len() > 1 && p.ends_with('/') {
p.pop();
}
p
}
/// `/`-normalized string form of a path for textual glob matching.
fn slashed(path: &Path) -> String {
let s = path.to_string_lossy();
if std::path::MAIN_SEPARATOR == '/' {
s.into_owned()
} else {
s.replace(std::path::MAIN_SEPARATOR, "/")
}
}
impl PathScope {
/// Compile the user's patterns. An unparseable glob is a usage error —
/// the caller maps `Err` to exit 2 like any other invalid argument.
pub fn parse(raw_patterns: &[String]) -> Result<Self, String> {
let mut patterns = Vec::with_capacity(raw_patterns.len());
let mut raw = Vec::with_capacity(raw_patterns.len());
for r in raw_patterns {
let normalized = normalize_pattern(r);
if normalized.is_empty() {
return Err(format!("invalid path pattern {r:?}: empty pattern"));
}
let compiled = Pattern::new(&normalized)
.map_err(|e| format!("invalid path pattern {r:?}: {e}"))?;
// `has_root` rather than `is_absolute`: identical on Unix, but a
// Windows drive-RELATIVE rooted pattern (`/global/store`, no
// drive letter) is not `is_absolute` — and a rooted pattern can
// never be cwd-relative, so it must match against the absolute
// candidate path either way.
let is_absolute = Path::new(&normalized).has_root();
patterns.push((compiled, is_absolute));
raw.push(r.clone());
}
Ok(Self { patterns, raw })
}
/// No patterns given — scoping is inactive and every path matches.
pub fn is_empty(&self) -> bool {
self.patterns.is_empty()
}
/// The patterns exactly as the user typed them (for envelopes/errors).
pub fn raw(&self) -> &[String] {
&self.raw
}
/// Bind the scope to one `--cwd`, absolutizing it ONCE (for the default
/// relative `.` that is a `getcwd` syscall plus an allocation) so a
/// caller filtering a whole crawl asks [`BoundScope::matches`] per
/// package without repeating it.
pub fn bind(&self, cwd: &Path) -> BoundScope<'_> {
BoundScope {
scope: self,
cwd: cwd.to_path_buf(),
abs_cwd: std::path::absolute(cwd).unwrap_or_else(|_| cwd.to_path_buf()),
}
}
/// Is `candidate` (an absolute package directory from a crawler) in
/// scope? An empty scope matches everything. One-off form of
/// [`PathScope::bind`] + [`BoundScope::matches`]; loops should bind.
pub fn matches(&self, cwd: &Path, candidate: &Path) -> bool {
if self.patterns.is_empty() {
return true;
}
self.bind(cwd).matches(candidate)
}
}
/// A [`PathScope`] bound to one `--cwd` (see [`PathScope::bind`]).
#[derive(Debug)]
pub struct BoundScope<'a> {
scope: &'a PathScope,
/// The cwd exactly as given, kept beside its absolutized form: crawler
/// paths are NOT absolutized (the default `--cwd .` yields candidates
/// like `./node_modules/foo`), so the relative form is the prefix that
/// actually strips in the common case.
cwd: PathBuf,
abs_cwd: PathBuf,
}
impl BoundScope<'_> {
/// Is `candidate` in scope? An empty scope matches everything.
pub fn matches(&self, candidate: &Path) -> bool {
if self.scope.patterns.is_empty() {
return true;
}
// Textual prefix-strip against the absolutized cwd; crawler paths
// are already absolute, so this stays a pure string operation.
let abs = slashed(candidate);
let rel = candidate
.strip_prefix(&self.abs_cwd)
.ok()
.or_else(|| candidate.strip_prefix(&self.cwd).ok())
.map(slashed);
self.scope.patterns.iter().any(|(pattern, is_absolute)| {
let target = if *is_absolute {
Some(abs.as_str())
} else {
rel.as_deref()
};
match target {
Some(t) => matches_path_or_ancestor(pattern, t),
// A relative pattern can never match a path outside cwd.
None => false,
}
})
}
}
/// True when `pattern` matches `path` or any of its ancestor prefixes
/// (successively dropping trailing `/`-components), so a plain directory
/// pattern scopes its whole subtree.
fn matches_path_or_ancestor(pattern: &Pattern, path: &str) -> bool {
let mut current = path;
loop {
if pattern.matches_with(current, MATCH_OPTIONS) {
return true;
}
match current.rfind('/') {
// Root ancestor of an absolute path is "/" — test it too, then stop.
Some(0) if current.len() > 1 => current = "/",
Some(idx) => current = ¤t[..idx],
None => return false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn scope(patterns: &[&str]) -> PathScope {
PathScope::parse(&patterns.iter().map(|s| s.to_string()).collect::<Vec<_>>())
.expect("test patterns are valid")
}
fn cwd() -> PathBuf {
PathBuf::from("/proj")
}
#[test]
fn empty_scope_matches_everything() {
let s = scope(&[]);
assert!(s.is_empty());
assert!(s.matches(&cwd(), Path::new("/anywhere/at/all")));
}
#[test]
fn exact_relative_path_matches() {
let s = scope(&["node_modules/lodash"]);
assert!(s.matches(&cwd(), Path::new("/proj/node_modules/lodash")));
assert!(!s.matches(&cwd(), Path::new("/proj/node_modules/left-pad")));
}
#[test]
fn directory_pattern_scopes_its_subtree() {
// No `/**` needed: matching an ancestor is enough.
let s = scope(&["packages/foo"]);
assert!(s.matches(&cwd(), Path::new("/proj/packages/foo/node_modules/lodash")));
assert!(!s.matches(&cwd(), Path::new("/proj/packages/bar/node_modules/lodash")));
}
#[test]
fn star_does_not_cross_separators() {
let s = scope(&["packages/*"]);
// `packages/*` matches the ancestor `packages/foo`, scoping its tree…
assert!(s.matches(&cwd(), Path::new("/proj/packages/foo/node_modules/lodash")));
// …but `nested/*` must not match a deeper path component-wise.
let s2 = scope(&["*"]);
assert!(s2.matches(&cwd(), Path::new("/proj/anything")));
let s3 = scope(&["src/*.js"]);
assert!(!s3.matches(&cwd(), Path::new("/proj/src/deep/file.js")));
}
#[test]
fn double_star_spans_directories() {
let s = scope(&["packages/**/lodash"]);
assert!(s.matches(&cwd(), Path::new("/proj/packages/foo/node_modules/lodash")));
assert!(!s.matches(&cwd(), Path::new("/proj/apps/foo/node_modules/lodash")));
}
#[test]
fn absolute_pattern_matches_paths_outside_cwd() {
let s = scope(&["/global/store"]);
assert!(s.matches(&cwd(), Path::new("/global/store/lib/node_modules/x")));
assert!(!s.matches(&cwd(), Path::new("/other/store/lib")));
}
#[test]
fn relative_pattern_never_matches_outside_cwd() {
let s = scope(&["store"]);
assert!(!s.matches(&cwd(), Path::new("/global/store")));
}
#[test]
fn leading_dot_slash_and_trailing_slash_are_normalized() {
let s = scope(&["./packages/foo/"]);
assert!(s.matches(&cwd(), Path::new("/proj/packages/foo/nested")));
}
#[test]
fn invalid_pattern_is_a_parse_error() {
let err = PathScope::parse(&["packages/[".to_string()]).unwrap_err();
assert!(
err.starts_with("invalid path pattern \"packages/[\": "),
"{err}"
);
let err = PathScope::parse(&["".to_string()]).unwrap_err();
assert!(err.contains("empty pattern"), "{err}");
}
#[test]
fn case_sensitivity_follows_the_platform() {
// Sensitive on Unix; insensitive on Windows (whose filesystems
// are case-insensitive — a drive-letter case mismatch must not
// silently empty a scope). Mirrors MATCH_OPTIONS.
let s = scope(&["Packages/foo"]);
let matches = s.matches(&cwd(), Path::new("/proj/packages/foo/x"));
assert_eq!(matches, cfg!(windows));
}
/// `bind` absolutizes the cwd once and answers exactly like the
/// per-call form for every candidate, relative and absolute patterns
/// alike.
#[test]
fn bound_scope_matches_like_the_per_call_form() {
let s = scope(&["packages/foo", "/global/store"]);
let bound = s.bind(&cwd());
for candidate in [
"/proj/packages/foo/node_modules/lodash",
"/proj/packages/bar/node_modules/lodash",
"/global/store/lib/node_modules/x",
"/other/store/lib",
] {
let candidate = Path::new(candidate);
assert_eq!(
bound.matches(candidate),
s.matches(&cwd(), candidate),
"{candidate:?}"
);
}
assert!(bound.matches(Path::new("/proj/packages/foo/x")));
assert!(!bound.matches(Path::new("/proj/packages/bar/x")));
assert!(scope(&[]).bind(&cwd()).matches(Path::new("/anywhere")));
}
#[test]
fn matching_is_purely_textual() {
// Paths that do not exist on disk still match — no fs access.
let s = scope(&["no/such/dir"]);
assert!(s.matches(&cwd(), Path::new("/proj/no/such/dir/pkg")));
}
}