xbp 10.38.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
Documentation
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Project-local ignore rules for XBP discovery, versioning, and worktree-watch.
//!
//! Sources (merged, later sources override earlier for the same pattern text):
//! 1. Built-in skip directories used by service discovery
//! 2. `.xbpignore` at the project root (optional)
//! 3. `.xbp/.xbpignore` (canonical project file)
//! 4. Extra patterns passed by the caller from `.xbp/xbp.yaml`:
//!    - service discovery / version targets → `ignore_paths`
//!      (aliases: `ignored_paths`, `xbpignore`)
//!    - worktree-watch only → `watch_ignore_paths` (alias: `watch_ignore`)
//!
//! `ignore_paths` never silences worktree-watch; use `watch_ignore_paths` for that.
//!
//! Pattern syntax is a practical gitignore subset:
//! - blank lines and `#` comments are ignored
//! - `!pattern` negates a previous match
//! - trailing `/` matches directories only
//! - leading `/` anchors to the project root
//! - `*` matches within a path segment; `**` matches across segments
//! - unanchored patterns match as a path suffix or any path segment (e.g. `node_modules`)

use std::fs;
use std::path::{Path, PathBuf};

use super::strip_utf8_bom;

/// Default directory names skipped during service discovery walks.
pub const DEFAULT_DISCOVERY_SKIP_DIRS: &[&str] = &[
    ".git",
    ".github",
    ".next",
    ".nx",
    ".open-next",
    ".turbo",
    ".venv",
    ".vercel",
    ".xbp",
    "build",
    "coverage",
    "dist",
    "node_modules",
    "out",
    "target",
    "tmp",
    "vendor",
    "venv",
];

#[derive(Debug, Clone, PartialEq, Eq)]
struct IgnorePattern {
    raw: String,
    negated: bool,
    dir_only: bool,
    /// Pattern body after stripping `!` and trailing `/`, normalized to `/`.
    body: String,
    anchored: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct XbpIgnoreSet {
    patterns: Vec<IgnorePattern>,
}

impl XbpIgnoreSet {
    pub fn empty() -> Self {
        Self {
            patterns: Vec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.patterns.is_empty()
    }

    pub fn patterns(&self) -> impl Iterator<Item = &str> {
        self.patterns.iter().map(|pattern| pattern.raw.as_str())
    }

    pub fn from_patterns<I, S>(patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut set = Self::empty();
        set.extend_patterns(patterns);
        set
    }

    pub fn from_file_content(content: &str) -> Self {
        let mut set = Self::empty();
        set.extend_file_content(content);
        set
    }

    pub fn extend_patterns<I, S>(&mut self, patterns: I)
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for pattern in patterns {
            if let Some(parsed) = parse_ignore_pattern(pattern.as_ref()) {
                self.patterns.push(parsed);
            }
        }
    }

    pub fn extend_file_content(&mut self, content: &str) {
        let stripped = strip_utf8_bom(content);
        for line in stripped.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if let Some(parsed) = parse_ignore_pattern(trimmed) {
                self.patterns.push(parsed);
            }
        }
    }

    pub fn merge(&mut self, other: &XbpIgnoreSet) {
        self.patterns.extend(other.patterns.iter().cloned());
    }

    /// True when the relative path should be ignored.
    ///
    /// `is_dir` should be true when the path is known to be a directory (walk
    /// filtering, service roots). When unknown, pass `false` so file-oriented
    /// patterns still apply and directory-only patterns only match if the path
    /// looks like a directory prefix match via children is not required.
    pub fn is_ignored_relative(&self, relative: &str, is_dir: bool) -> bool {
        let normalized = normalize_relative_path(relative);
        if normalized.is_empty() || normalized == "." {
            return false;
        }

        let mut ignored = false;
        for pattern in &self.patterns {
            if pattern_matches(pattern, &normalized, is_dir) {
                ignored = !pattern.negated;
            }
        }
        ignored
    }

    pub fn is_ignored_path(&self, project_root: &Path, path: &Path) -> bool {
        let relative = match path.strip_prefix(project_root) {
            Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
            Err(_) => path.to_string_lossy().replace('\\', "/"),
        };
        let is_dir = path.is_dir();
        self.is_ignored_relative(&relative, is_dir)
    }

    /// True when a directory entry should not be descended into during discovery.
    pub fn skips_dir_name(&self, dir_name: &str) -> bool {
        let name = dir_name.trim().trim_matches(|ch| ch == '/' || ch == '\\');
        if name.is_empty() || name == "." || name == ".." {
            return false;
        }
        // Bare folder names in patterns (and built-ins expressed as such).
        self.is_ignored_relative(name, true)
    }

    /// True when a service root directory (project-relative) is ignored.
    pub fn ignores_service_root(&self, root_directory: &str) -> bool {
        let normalized = normalize_relative_path(root_directory);
        if normalized.is_empty() || normalized == "." {
            return false;
        }
        self.is_ignored_relative(&normalized, true)
    }

    /// True when a version target path should be excluded from versioning.
    pub fn ignores_version_target(&self, target: &str) -> bool {
        let normalized = normalize_relative_path(target);
        if normalized.is_empty() {
            return false;
        }
        // Version manifests are files; also ignore when a parent directory is banned.
        if self.is_ignored_relative(&normalized, false) {
            return true;
        }
        // Parent path segments: packages/icons/package.json → packages/icons
        if let Some(parent) = Path::new(&normalized).parent() {
            let parent_rel = parent.to_string_lossy().replace('\\', "/");
            if !parent_rel.is_empty() && parent_rel != "." {
                return self.is_ignored_relative(&parent_rel, true);
            }
        }
        false
    }
}

/// Load ignore rules for a project root.
///
/// Order: optional extra patterns (e.g. from yaml) are applied after files so
/// config can refine file rules. Built-in discovery skip dirs are always first.
pub fn load_project_xbp_ignore(project_root: &Path, extra_patterns: &[String]) -> XbpIgnoreSet {
    let mut set = XbpIgnoreSet::from_patterns(
        DEFAULT_DISCOVERY_SKIP_DIRS
            .iter()
            .map(|name| (*name).to_string()),
    );

    for candidate in xbp_ignore_file_candidates(project_root) {
        if let Ok(content) = fs::read_to_string(&candidate) {
            set.extend_file_content(&content);
        }
    }

    if !extra_patterns.is_empty() {
        set.extend_patterns(extra_patterns.iter().map(String::as_str));
    }

    set
}

/// Canonical ignore file paths for a project (existence not required).
pub fn xbp_ignore_file_candidates(project_root: &Path) -> Vec<PathBuf> {
    vec![
        project_root.join(".xbpignore"),
        project_root.join(".xbp").join(".xbpignore"),
    ]
}

pub fn default_xbp_ignore_path(project_root: &Path) -> PathBuf {
    project_root.join(".xbp").join(".xbpignore")
}

fn parse_ignore_pattern(raw: &str) -> Option<IgnorePattern> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed.starts_with('#') {
        return None;
    }

    let (negated, rest) = if let Some(rest) = trimmed.strip_prefix('!') {
        (true, rest.trim())
    } else {
        (false, trimmed)
    };
    if rest.is_empty() {
        return None;
    }

    let dir_only = rest.ends_with('/');
    let without_slash = rest.trim_end_matches(|ch| ch == '/' || ch == '\\');
    let normalized = without_slash.replace('\\', "/");
    let anchored = normalized.starts_with('/');
    let body = normalized
        .trim_start_matches('/')
        .trim_start_matches("./")
        .trim_matches('/')
        .to_string();
    if body.is_empty() {
        return None;
    }

    Some(IgnorePattern {
        raw: trimmed.to_string(),
        negated,
        dir_only,
        body,
        anchored,
    })
}

fn normalize_relative_path(raw: &str) -> String {
    raw.trim()
        .replace('\\', "/")
        .trim_start_matches("./")
        .trim_matches('/')
        .to_string()
}

fn pattern_matches(pattern: &IgnorePattern, path: &str, is_dir: bool) -> bool {
    if pattern.dir_only && !is_dir {
        // Directory-only patterns still match when the path is under that directory.
        // Example: `docs/` ignores `docs/readme.md`.
        let prefix = &pattern.body;
        if path == *prefix || path.starts_with(&format!("{prefix}/")) {
            // file under ignored dir → ignored
            return path != *prefix || is_dir;
        }
        // For exact file path that equals a dir pattern name without being a dir,
        // treat as no match unless path is under it.
        if path == *prefix {
            return false;
        }
        // Unanchored dir pattern: match if any ancestor segment path matches.
        return path_has_directory_match(path, pattern);
    }

    if pattern.anchored {
        return path_glob_match(&pattern.body, path)
            || (!pattern.dir_only && path_is_under_glob(&pattern.body, path));
    }

    // Unanchored: match full path, any suffix path, or a single path component.
    if path_glob_match(&pattern.body, path) {
        return true;
    }
    if path_is_under_glob(&pattern.body, path) {
        return true;
    }

    // Single-segment patterns match any path component (gitignore behavior).
    if !pattern.body.contains('/') && !pattern.body.contains("**") {
        return path
            .split('/')
            .any(|component| path_glob_match(&pattern.body, component));
    }

    // Multi-segment unanchored: match if any suffix matches the pattern.
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for start in 0..segments.len() {
        let suffix = segments[start..].join("/");
        if path_glob_match(&pattern.body, &suffix)
            || path_is_under_glob(&pattern.body, &suffix)
        {
            return true;
        }
    }

    false
}

fn path_has_directory_match(path: &str, pattern: &IgnorePattern) -> bool {
    if pattern.anchored {
        return path == pattern.body || path.starts_with(&format!("{}/", pattern.body));
    }
    if !pattern.body.contains('/') && !pattern.body.contains('*') {
        return path
            .split('/')
            .any(|component| component.eq_ignore_ascii_case(&pattern.body));
    }
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for start in 0..segments.len() {
        let suffix = segments[start..].join("/");
        if path_glob_match(&pattern.body, &suffix)
            || suffix.starts_with(&format!("{}/", pattern.body))
            || path_is_under_glob(&pattern.body, &suffix)
        {
            return true;
        }
    }
    false
}

fn path_is_under_glob(pattern: &str, path: &str) -> bool {
    // If pattern matches a parent of path, path is ignored.
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for end in 1..segments.len() {
        let parent = segments[..end].join("/");
        if path_glob_match(pattern, &parent) {
            return true;
        }
    }
    false
}

/// Glob match with `*` (segment-local) and `**` (cross-segment).
fn path_glob_match(pattern: &str, path: &str) -> bool {
    let pattern = pattern.trim_matches('/');
    let path = path.trim_matches('/');
    if pattern == "**" {
        return true;
    }
    glob_match_segments(
        &split_glob_segments(pattern),
        &path.split('/').filter(|s| !s.is_empty()).collect::<Vec<_>>(),
    )
}

fn split_glob_segments(pattern: &str) -> Vec<&str> {
    pattern.split('/').filter(|s| !s.is_empty()).collect()
}

fn glob_match_segments(pattern: &[&str], path: &[&str]) -> bool {
    fn rec(p: &[&str], s: &[&str]) -> bool {
        match (p.first().copied(), s.first().copied()) {
            (None, None) => true,
            (Some("**"), _) => {
                // `**` matches zero or more segments, then the rest of the pattern.
                if rec(&p[1..], s) {
                    return true;
                }
                // Consume one path segment and keep `**`.
                if s.is_empty() {
                    return false;
                }
                rec(p, &s[1..])
            }
            (Some(pat), Some(seg)) => {
                if segment_glob_match(pat, seg) {
                    rec(&p[1..], &s[1..])
                } else {
                    false
                }
            }
            (Some(_), None) | (None, Some(_)) => false,
        }
    }
    rec(pattern, path)
}

fn segment_glob_match(pattern: &str, segment: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if !pattern.contains('*') {
        return pattern == segment;
    }

    // Simple `*` wildcards within a single segment.
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        return pattern == segment;
    }

    let mut rest = segment;
    for (index, part) in parts.iter().enumerate() {
        if part.is_empty() {
            continue;
        }
        if index == 0 {
            if !rest.starts_with(part) {
                return false;
            }
            rest = &rest[part.len()..];
            continue;
        }
        if index == parts.len() - 1 {
            return rest.ends_with(part);
        }
        if let Some(pos) = rest.find(part) {
            rest = &rest[pos + part.len()..];
        } else {
            return false;
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_root(name: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let path = std::env::temp_dir().join(format!("xbp-ignore-{name}-{nanos}"));
        let _ = fs::remove_dir_all(&path);
        fs::create_dir_all(path.join(".xbp")).expect("mkdir");
        path
    }

    #[test]
    fn matches_unanchored_folder_anywhere() {
        let set = XbpIgnoreSet::from_patterns(["node_modules"]);
        assert!(set.is_ignored_relative("node_modules", true));
        assert!(set.is_ignored_relative("apps/web/node_modules", true));
        assert!(set.is_ignored_relative("apps/web/node_modules/pkg/index.js", false));
        assert!(!set.is_ignored_relative("apps/web/src/main.ts", false));
    }

    #[test]
    fn matches_anchored_and_directory_only_patterns() {
        let set = XbpIgnoreSet::from_patterns(["/docs/", "packages/icons"]);
        assert!(set.is_ignored_relative("docs", true));
        assert!(set.is_ignored_relative("docs/guide.md", false));
        assert!(!set.is_ignored_relative("apps/docs/guide.md", false));
        assert!(set.is_ignored_relative("packages/icons", true));
        assert!(set.is_ignored_relative("packages/icons/package.json", false));
        assert!(!set.is_ignored_relative("packages/web/package.json", false));
    }

    #[test]
    fn supports_negation() {
        let set = XbpIgnoreSet::from_patterns(["secrets/", "!secrets/public.env"]);
        assert!(set.is_ignored_relative("secrets/private.key", false));
        assert!(!set.is_ignored_relative("secrets/public.env", false));
    }

    #[test]
    fn loads_dot_xbp_ignore_and_yaml_patterns() {
        let root = temp_root("load");
        fs::write(
            root.join(".xbp").join(".xbpignore"),
            "# project ignores\npackages/icons/\n*.snap\n",
        )
        .expect("write ignore");
        fs::write(root.join(".xbpignore"), "legacy-root-ignore/\n").expect("write root ignore");

        let set = load_project_xbp_ignore(
            &root,
            &["e2e/".to_string(), "packages/icons/README.md".to_string()],
        );

        assert!(set.ignores_service_root("packages/icons"));
        assert!(set.ignores_version_target("packages/icons/package.json"));
        assert!(set.is_ignored_relative("legacy-root-ignore/foo", false));
        assert!(set.is_ignored_relative("e2e/test.spec.ts", false));
        assert!(set.is_ignored_relative("apps/web/__snapshots__/a.snap", false));
        // built-in
        assert!(set.skips_dir_name("node_modules"));
        assert!(set.skips_dir_name("target"));

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn glob_double_star_and_star_segment() {
        let set = XbpIgnoreSet::from_patterns(["**/dist", "apps/*/tmp"]);
        assert!(set.is_ignored_relative("packages/foo/dist/index.js", false));
        assert!(set.is_ignored_relative("dist", true));
        assert!(set.is_ignored_relative("apps/web/tmp", true));
        assert!(set.is_ignored_relative("apps/web/tmp/cache", false));
        assert!(!set.is_ignored_relative("apps/web/src/tmp-file.ts", false));
    }
}