changesette 6.0.0

A version and changelog manager using the changesets file format
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::iter::Peekable;
use std::path::{Component, Path};
use std::str::CharIndices;

use anyhow::{Result, bail};

#[derive(Debug, PartialEq)]
pub(crate) enum Seg {
    Literal(String),
    /// A single-segment glob, matched with `fast_glob`.
    Wildcard(String),
    Globstar,
}

/// A workspace pattern compiled to `/`-separated segments; the last segment
/// is always `Literal("package.json")`, so the pattern matches manifest file
/// paths.
#[derive(Debug)]
pub(crate) struct Pattern {
    segs: Vec<Seg>,
}

/// Compiles one workspace pattern into its polarity (`true` for a `!`
/// negation) and matcher; the errors name only the offense, and the caller
/// attaches the manifest path and the original pattern. The body is read as
/// one fast-glob glob and split at its top-level separators.
pub(crate) fn compile(original: &str) -> Result<(bool, Pattern)> {
    // Every leading `!` flips the polarity, as npm counts them; leaving one
    // in the body would hand it to the glob matcher.
    let mut negated = false;
    let mut body = original;
    while let Some(rest) = body.strip_prefix('!') {
        negated = !negated;
        body = rest;
    }
    // An absolute path and a `..` segment are the patterns the upstream
    // tools silently break on or resolve outside the root, so they are loud
    // errors rather than a silent no-match.
    if body.starts_with('/') || body.starts_with("\\/") {
        bail!("absolute patterns are not supported")
    }
    let parts = split(body)?;
    // An empty pattern is a plain mistake — npm matches nothing and pnpm
    // errors — and reading it as `.` would silently opt the root into
    // versioning. An intentional root reference has a `.` segment.
    if parts.iter().all(|part| part.is_empty()) {
        bail!("empty patterns are not supported")
    }
    let mut segs = Vec::new();
    for (index, part) in parts.into_iter().enumerate() {
        if part.is_empty() || part == "." {
            continue;
        }
        if part == ".." {
            bail!("`..` segments are not supported")
        }
        let seg = classify(part)?;
        // A leading Windows drive prefix (`C:/x`, or the drive-relative
        // `C:x`) addresses a location outside the root like an absolute
        // path, so it is the same loud error; on Unix nothing parses as a
        // prefix and `C:` stays an ordinary name.
        if index == 0
            && let Seg::Literal(name) = &seg
            && !is_plain_component(name)
        {
            bail!("drive-prefixed patterns are not supported")
        }
        segs.push(seg);
    }
    // Appending the manifest name gives the pnpm-style idioms for free: the
    // zero-width `**` makes `x/**` cover `x` itself and `!x/**` exclude it.
    segs.push(Seg::Literal("package.json".to_owned()));
    Ok((negated, Pattern { segs }))
}

fn split(body: &str) -> Result<Vec<&str>> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut brace_depth: usize = 0;
    let mut chars = body.char_indices().peekable();
    while let Some((index, c)) = chars.next() {
        match c {
            '\\' => {
                // A separator cannot be escaped: fast-glob unescapes `\/`
                // right back into one, so `\/` splits like a bare `/` (with
                // the `\` dropped) rather than diverging from the matcher.
                if let Some(&(slash_index, '/')) = chars.peek() {
                    if brace_depth > 0 {
                        bail!("`/` inside braces is not supported")
                    }
                    chars.next();
                    parts.push(&body[start..index]);
                    start = slash_index + 1;
                } else {
                    // An escaped character, or a trailing `\` that the
                    // per-segment validation rejects.
                    chars.next();
                }
            }
            '/' => {
                // Braces spanning segments are deliberately unsupported
                // (zero occurrences in the wild): an intended error now,
                // where the shattered halves used to fail the glob
                // validation by accident.
                if brace_depth > 0 {
                    bail!("`/` inside braces is not supported")
                }
                parts.push(&body[start..index]);
                start = index + 1;
            }
            '{' => brace_depth += 1,
            // A `}` without a matching `{` is an ordinary character.
            '}' => brace_depth = brace_depth.saturating_sub(1),
            '[' => skip_class(&mut chars)?,
            _ => {}
        }
    }
    parts.push(&body[start..]);
    Ok(parts)
}

fn skip_class(chars: &mut Peekable<CharIndices<'_>>) -> Result<()> {
    // Mirrors fast-glob's class parsing: an optional `^`/`!` prefix, then
    // the first character is a literal member (so a leading `]` does not
    // close the class), and `\` escapes the next character. An unclosed
    // class swallows the rest of the body and is left for the per-segment
    // validation to reject.
    if matches!(chars.peek(), Some((_, '^' | '!'))) {
        chars.next();
    }
    let mut first = true;
    while let Some((_, c)) = chars.next() {
        match c {
            ']' if !first => return Ok(()),
            '/' => bail!("`/` inside character classes is not supported"),
            '\\' => {
                if matches!(chars.peek(), Some((_, '/'))) {
                    bail!("`/` inside character classes is not supported")
                }
                chars.next();
            }
            _ => {}
        }
        first = false;
    }
    Ok(())
}

/// Whether `name` parses as exactly one normal path component. Meant for
/// `Literal` segments, which are free of `\` and glob syntax, so the std
/// parser reads them unambiguously; only a Windows prefix like `C:` fails.
pub(crate) fn is_plain_component(name: &str) -> bool {
    let mut components = Path::new(name).components();
    matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
}

fn classify(part: &str) -> Result<Seg> {
    if part == "**" {
        return Ok(Seg::Globstar);
    }
    if part.contains(['*', '?', '[', ']', '{', '}', '\\']) {
        fast_glob::validate(part)?;
        // fast_glob reads every leading `!` of the string it is handed as a
        // negation, while in the whole pattern this `!` sits mid-glob and is
        // literal — escape it so the matcher reads it that way too.
        if part.starts_with('!') {
            return Ok(Seg::Wildcard(format!("\\{part}")));
        }
        return Ok(Seg::Wildcard(part.to_owned()));
    }
    Ok(Seg::Literal(part.to_owned()))
}

impl Pattern {
    pub(crate) fn segs(&self) -> &[Seg] {
        &self.segs
    }

    /// Whether every segment is a `Literal`, making the pattern a plain path
    /// the walker can skip in favor of an existence check.
    pub(crate) fn is_literal(&self) -> bool {
        self.segs.iter().all(|seg| matches!(seg, Seg::Literal(_)))
    }

    /// Matches a root-relative `/`-separated manifest path in full; a
    /// negation passes `dot_permissive` so its wildcards cover dot segments.
    pub(crate) fn matches(&self, rel_manifest: &str, dot_permissive: bool) -> bool {
        let names: Vec<&str> = rel_manifest.split('/').collect();
        matches_from(&self.segs, &names, dot_permissive)
    }
}

fn matches_from(segs: &[Seg], names: &[&str], dot_permissive: bool) -> bool {
    let Some((seg, segs_rest)) = segs.split_first() else {
        return names.is_empty();
    };
    if let Seg::Globstar = seg {
        // A globstar consumes zero or more segments.
        if matches_from(segs_rest, names, dot_permissive) {
            return true;
        }
        return match names.split_first() {
            Some((name, names_rest)) if seg_matches(seg, name, dot_permissive) => {
                matches_from(segs, names_rest, dot_permissive)
            }
            _ => false,
        };
    }
    match names.split_first() {
        Some((name, names_rest)) => {
            seg_matches(seg, name, dot_permissive)
                && matches_from(segs_rest, names_rest, dot_permissive)
        }
        None => false,
    }
}

/// Matches one pattern segment against one path segment, applying the dot
/// rule unless `dot_permissive`: a `.`-leading name matches only a pattern
/// segment that literally starts with `.`.
pub(crate) fn seg_matches(seg: &Seg, name: &str, dot_permissive: bool) -> bool {
    if !dot_permissive && name.starts_with('.') {
        let dot_ok = match seg {
            Seg::Literal(text) | Seg::Wildcard(text) => text.starts_with('.'),
            Seg::Globstar => false,
        };
        if !dot_ok {
            return false;
        }
    }
    match seg {
        Seg::Literal(text) => text == name,
        Seg::Wildcard(glob) => fast_glob::glob_match(glob, name),
        Seg::Globstar => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lit(text: &str) -> Seg {
        Seg::Literal(text.to_owned())
    }

    fn wild(text: &str) -> Seg {
        Seg::Wildcard(text.to_owned())
    }

    fn positive(pattern: &str) -> Pattern {
        let (negated, compiled) = compile(pattern).unwrap();
        assert!(!negated, "{pattern}");
        compiled
    }

    fn negation(pattern: &str) -> Pattern {
        let (negated, compiled) = compile(pattern).unwrap();
        assert!(negated, "{pattern}");
        compiled
    }

    fn error(pattern: &str) -> String {
        format!("{:#}", compile(pattern).unwrap_err())
    }

    #[test]
    fn normalizes_dot_and_slash_noise() {
        for pattern in ["./x", "x/", "x", "./x/"] {
            assert_eq!(
                positive(pattern).segs(),
                [lit("x"), lit("package.json")],
                "{pattern}"
            );
        }
        assert_eq!(
            positive("x//y").segs(),
            [lit("x"), lit("y"), lit("package.json")]
        );
        for pattern in [".", "./"] {
            assert_eq!(positive(pattern).segs(), [lit("package.json")], "{pattern}");
        }
    }

    #[test]
    fn rejects_an_empty_pattern() {
        for pattern in ["", "!", "!!"] {
            assert!(error(pattern).contains("empty"), "{pattern}");
        }
    }

    #[test]
    fn leading_bangs_toggle_the_polarity_by_parity() {
        assert_eq!(positive("!!x").segs(), [lit("x"), lit("package.json")]);
        assert_eq!(negation("!!!x").segs(), [lit("x"), lit("package.json")]);
    }

    #[test]
    fn rejects_an_absolute_pattern() {
        for pattern in ["/abs", "!/abs", "/"] {
            assert!(error(pattern).contains("absolute"), "{pattern}");
        }
    }

    #[cfg(windows)]
    #[test]
    fn rejects_a_leading_drive_prefix() {
        for pattern in ["C:/packages/*", "C:x", "c:/x", "C:", "!C:/x"] {
            assert!(error(pattern).contains("drive"), "{pattern}");
        }
        assert!(!is_plain_component("C:"));
        assert!(!is_plain_component("C:x"));
        assert!(is_plain_component("x"));
    }

    #[cfg(windows)]
    #[test]
    fn a_drive_prefix_after_the_first_raw_segment_compiles() {
        assert_eq!(
            positive("packages/C:/x").segs(),
            [lit("packages"), lit("C:"), lit("x"), lit("package.json")]
        );
        assert_eq!(
            positive("./C:/x").segs(),
            [lit("C:"), lit("x"), lit("package.json")]
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_drive_like_segment_is_an_ordinary_name_on_unix() {
        assert_eq!(
            positive("C:/x").segs(),
            [lit("C:"), lit("x"), lit("package.json")]
        );
        assert_eq!(positive("C:x").segs(), [lit("C:x"), lit("package.json")]);
        assert!(is_plain_component("C:"));
    }

    #[test]
    fn rejects_a_parent_segment() {
        for pattern in ["../x", "!../x", "a/../b", ".."] {
            assert!(error(pattern).contains("`..`"), "{pattern}");
        }
    }

    #[test]
    fn classifies_segments() {
        assert_eq!(
            positive("packages/**").segs(),
            [lit("packages"), Seg::Globstar, lit("package.json")]
        );
        assert_eq!(positive("f**").segs(), [wild("f**"), lit("package.json")]);
        assert_eq!(
            positive("+(a|b)").segs(),
            [lit("+(a|b)"), lit("package.json")]
        );
        assert_eq!(
            positive("a?c/[xy]").segs(),
            [wild("a?c"), wild("[xy]"), lit("package.json")]
        );
    }

    #[test]
    fn rejects_invalid_glob_syntax() {
        assert!(compile("packages/[").is_err());
        assert!(compile("src/{a,b").is_err());
        assert!(compile("x\\").is_err());
    }

    #[test]
    fn a_bang_after_the_leading_run_is_literal() {
        let pattern = positive("packages/!foo*");
        assert_eq!(
            pattern.segs(),
            [lit("packages"), wild("\\!foo*"), lit("package.json")]
        );
        assert!(pattern.matches("packages/!foox/package.json", false));
        assert!(!pattern.matches("packages/foox/package.json", false));
        assert!(!pattern.matches("packages/bar/package.json", false));
        assert_eq!(
            positive("packages/!foo").segs(),
            [lit("packages"), lit("!foo"), lit("package.json")]
        );
        assert_eq!(
            positive("a/\\!b*").segs(),
            [lit("a"), wild("\\!b*"), lit("package.json")]
        );
    }

    #[test]
    fn an_escaped_slash_is_a_separator() {
        assert_eq!(
            positive("a\\/b").segs(),
            [lit("a"), lit("b"), lit("package.json")]
        );
        assert_eq!(positive("a\\/").segs(), [lit("a"), lit("package.json")]);
        assert!(error("\\/").contains("absolute"));
        assert!(error("\\/x").contains("absolute"));
    }

    #[test]
    fn rejects_a_slash_inside_braces() {
        for pattern in ["{a,b/c}", "{a,b\\/c}", "x/{a,b/c}", "{a,{b/c,d}}"] {
            assert!(error(pattern).contains("braces"), "{pattern}");
        }
        assert_eq!(
            positive("x/{a,b}/y").segs(),
            [lit("x"), wild("{a,b}"), lit("y"), lit("package.json")]
        );
        assert_eq!(
            positive("\\{a,b\\}/c").segs(),
            [wild("\\{a,b\\}"), lit("c"), lit("package.json")]
        );
        assert_eq!(
            positive("a}b/c").segs(),
            [wild("a}b"), lit("c"), lit("package.json")]
        );
    }

    #[test]
    fn rejects_a_slash_inside_a_character_class() {
        for pattern in ["[a/b]", "[a\\/b]", "x[/]y", "[!/]", "x/[a/b]"] {
            assert!(error(pattern).contains("character class"), "{pattern}");
        }
        assert_eq!(
            positive("[]]x/y").segs(),
            [wild("[]]x"), lit("y"), lit("package.json")]
        );
        assert_eq!(
            positive("[{]/a").segs(),
            [wild("[{]"), lit("a"), lit("package.json")]
        );
    }

    #[test]
    fn applies_the_dot_rule_per_segment() {
        assert!(!seg_matches(&wild("*"), ".x", false));
        assert!(seg_matches(&wild(".*"), ".x", false));
        assert!(seg_matches(&lit(".github"), ".github", false));
        assert!(!seg_matches(&Seg::Globstar, ".x", false));
        assert!(seg_matches(&wild("*"), ".x", true));
        assert!(seg_matches(&Seg::Globstar, ".x", true));
    }

    #[test]
    fn expands_braces_within_a_segment() {
        assert!(seg_matches(&wild("{a,b}"), "a", false));
        assert!(seg_matches(&wild("{a,b}"), "b", false));
        assert!(!seg_matches(&wild("{a,b}"), "{a,b}", false));
    }

    #[test]
    fn expands_nested_braces() {
        for name in ["a", "b", "c"] {
            assert!(seg_matches(&wild("{a,{b,c}}"), name, false), "{name}");
        }
        assert!(!seg_matches(&wild("{a,{b,c}}"), "d", false));
        assert!(!seg_matches(&wild("{a,{b,c}}"), "{b,c}", false));
    }

    #[test]
    fn a_negated_character_class_excludes_its_members() {
        assert!(seg_matches(&wild("[!b]"), "a", false));
        assert!(!seg_matches(&wild("[!b]"), "b", false));
        assert!(seg_matches(&wild("x[!b]"), "xc", false));
    }

    #[test]
    fn a_double_star_negation_matches_the_base_directory() {
        let pattern = negation("!x/**");
        assert!(pattern.matches("x/package.json", true));
        assert!(pattern.matches("x/y/package.json", true));
        assert!(!pattern.matches("y/package.json", true));
    }

    #[test]
    fn a_negation_matches_dot_segments() {
        let pattern = negation("!**/.vercel/**");
        assert!(pattern.matches(".vercel/package.json", true));
        assert!(pattern.matches("a/.vercel/b/package.json", true));
        assert!(!pattern.matches("a/b/package.json", true));
    }

    #[test]
    fn a_full_match_applies_the_dot_rule_when_not_permissive() {
        let pattern = positive("*");
        assert!(!pattern.matches(".x/package.json", false));
        assert!(pattern.matches(".x/package.json", true));
        assert!(pattern.matches("x/package.json", false));
    }

    #[test]
    fn a_full_match_expands_braces() {
        let pattern = positive("packages/{a,b}");
        assert!(pattern.matches("packages/a/package.json", true));
        assert!(!pattern.matches("packages/c/package.json", true));
        assert!(!pattern.matches("packages/{a,b}/package.json", true));
    }
}