girt 0.13.1

An incremental, idiomatic Rust implementation of Git
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
525
526
527
528
529
530
use std::sync::Arc;

use super::pattern::Pattern;

/// The filesystem kind of a queried ignore path.
///
/// ```
/// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
///
/// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
/// rules.add(Source::Info, b"cache/\n")?;
/// assert!(
///     rules
///         .check(b"cache", InputKind::Directory)?
///         .unwrap()
///         .ignored
/// );
/// assert!(rules.check(b"cache", InputKind::File)?.is_none());
/// // Classify a symlink as File, including a symlink whose target is a directory.
/// # Ok::<(), girt::ignore::Error>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum InputKind {
    /// A file, symlink or other non-directory path.
    File,
    /// A directory; directory-only patterns apply.
    Directory,
}

/// Explicit byte comparison policy, independent of the host filesystem.
///
/// ```
/// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
///
/// let mut rules = Ignore::new(Case::AsciiInsensitive, Limits::default());
/// rules.add(Source::Directory(b"Src"), b"*.LOG\n")?;
/// assert!(
///     rules
///         .check(b"src/build.log", InputKind::File)?
///         .unwrap()
///         .ignored
/// );
/// // This policy is explicit and does not inspect filesystem case sensitivity.
/// # Ok::<(), girt::ignore::Error>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Case {
    /// Compare bytes exactly (the policy used by jj's ignore consumer).
    Sensitive,
    /// Fold ASCII letters, including directory-source prefixes. No Unicode folding is performed.
    AsciiInsensitive,
}

/// An ignore source's precedence and repository-relative directory.
///
/// Higher variants override lower variants; deeper directories override shallower ones.
/// Adding another source at the same level appends its rules after existing rules.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Source<'a> {
    /// Caller-resolved `core.excludesFile` content, anchored at the repository root.
    Global,
    /// Common-directory `info/exclude`, anchored at the repository root.
    Info,
    /// `.gitignore` in this slash-separated directory; the empty slice denotes the root.
    Directory(&'a [u8]),
    /// Explicit command rules, anchored at the root and higher than directory files.
    Command,
}

/// Resource budgets for an entire retained set and each independent query.
///
/// Compilation and storage are linear in input bytes with a constant factor for compiled tokens
/// (up to 40 bytes per pattern byte, plus vector/record overhead). Queries use two linear rows,
/// never recursive backtracking. Allocation failure follows Rust's allocator policy; these limits
/// are not a recoverable allocator or an exact RSS bound.
///
/// ```
/// use girt::ignore::{Case, Error, Ignore, InputKind, Limits, Source};
/// let mut rules = Ignore::new(Case::Sensitive, Limits::default().with_patterns(1));
/// rules.add(Source::Info, b"*.log\n")?;
/// assert!(matches!(
///     rules.add(Source::Command, b"*.tmp\n"),
///     Err(Error::Limit(_))
/// ));
/// // Failed addition is atomic: the previous rule set remains usable.
/// assert!(rules.check(b"build.log", InputKind::File)?.unwrap().ignored);
/// assert!(rules.check(b"scratch.tmp", InputKind::File)?.is_none());
/// # Ok::<(), girt::ignore::Error>(())
/// ```
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Limits {
    /// Aggregate source content and directory-prefix bytes; default 8 MiB.
    pub bytes: usize,
    /// Number of added sources, including empty sources; default 4096.
    pub sources: usize,
    /// Retained non-comment, nonempty rules; default 100,000.
    pub patterns: usize,
    /// Maximum line bytes excluding LF and the initial BOM, before trimming; default 4096.
    pub line_bytes: usize,
    /// Maximum query or source-directory path length; default 4096 bytes.
    pub path_bytes: usize,
    /// Aggregate conservative matching work per query; default 100 million units.
    ///
    /// Includes source-prefix comparisons, pattern checks and dynamic-programming cells across
    /// every ancestor. Exhaustion returns an error, never a partial ignore decision.
    pub work: usize,
}

impl Limits {
    /// Sets [`Self::bytes`].
    #[must_use]
    pub fn with_bytes(mut self, bytes: usize) -> Self {
        self.bytes = bytes;
        self
    }

    /// Sets [`Self::sources`].
    #[must_use]
    pub fn with_sources(mut self, sources: usize) -> Self {
        self.sources = sources;
        self
    }

    /// Sets [`Self::patterns`].
    #[must_use]
    pub fn with_patterns(mut self, patterns: usize) -> Self {
        self.patterns = patterns;
        self
    }

    /// Sets [`Self::line_bytes`].
    #[must_use]
    pub fn with_line_bytes(mut self, line_bytes: usize) -> Self {
        self.line_bytes = line_bytes;
        self
    }

    /// Sets [`Self::path_bytes`].
    #[must_use]
    pub fn with_path_bytes(mut self, path_bytes: usize) -> Self {
        self.path_bytes = path_bytes;
        self
    }

    /// Sets [`Self::work`].
    #[must_use]
    pub fn with_work(mut self, work: usize) -> Self {
        self.work = work;
        self
    }
}
impl Default for Limits {
    fn default() -> Self {
        Self {
            bytes: 8 * 1024 * 1024,
            sources: 4096,
            patterns: 100_000,
            line_bytes: 4096,
            path_bytes: 4096,
            work: 100_000_000,
        }
    }
}

impl Limits {
    /// Returns limits for a repository the caller trusts as Git trusts the user's own.
    ///
    /// Git bounds none of these values. The defaults suit untrusted input; these are large enough
    /// that only available memory bounds the work, while keeping headroom for internal arithmetic.
    pub const fn trusted() -> Self {
        Self {
            bytes: usize::MAX / 4,
            sources: usize::MAX / 4,
            patterns: usize::MAX / 4,
            line_bytes: usize::MAX / 4,
            path_bytes: usize::MAX / 4,
            work: usize::MAX / 4,
        }
    }
}

/// An invalid path or exhausted budget; errors never imply an ignore decision.
///
/// Propagate failure rather than including or excluding the path on an incomplete decision.
/// Retry a limit failure only after choosing a larger budget appropriate to the caller's trust.
///
/// ```
/// use girt::ignore::{Case, Error, Ignore, InputKind, Limits};
/// let rules = Ignore::new(Case::Sensitive, Limits::default());
/// assert_eq!(
///     rules.check(b"../outside", InputKind::File),
///     Err(Error::Path)
/// );
/// ```
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// Paths must be relative and nonempty, without NUL, empty, `.` or `..` components.
    /// The root directory source alone permits an empty path; backslash is an ordinary byte.
    #[error("invalid repository-relative ignore path")]
    Path,
    /// A named input, retained-storage or matching-work limit was exceeded.
    #[error("ignore {0} limit exceeded")]
    Limit(&'static str),
}

/// The decisive rule, including a possible excluded ancestor.
///
/// ```
/// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
/// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
/// let source = rules.add(Source::Info, b"cache/\n")?;
/// let found = rules.check(b"cache/data", InputKind::File)?.unwrap();
/// assert_eq!((found.source, found.line), (source, 1));
/// assert!(found.matched_bytes < b"cache/data".len()); // Decision came from an ancestor.
///
/// # Ok::<(), girt::ignore::Error>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Match {
    /// Whether this rule excludes the path; false identifies an explicit negation.
    pub ignored: bool,
    /// Zero-based successful source-addition index, for caller-owned source labels.
    pub source: usize,
    /// One-based physical source line.
    pub line: usize,
    /// Byte length of the matched path prefix; shorter than the query for an excluded ancestor.
    pub matched_bytes: usize,
}

/// An owned set of compiled Git ignore sources.
///
/// Matching accepts arbitrary non-NUL bytes and does not normalize Unicode, separators or case
/// beyond the chosen [`Case`]. Content recognizes LF, CRLF, an initial UTF-8 BOM, escaped trailing
/// spaces, comments and negation. A NUL truncates its physical line, matching Git's file reader.
/// Invalid glob syntax (including a terminal escape or unclosed class) is retained as a rule that
/// never matches. No source files are opened, and directory flags are supplied by the caller.
///
/// ```
/// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
/// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
/// rules.add(Source::Global, b"*.log\n")?;
/// rules.add(Source::Directory(b""), b"!important.log\n")?;
/// assert!(rules.check(b"debug.log", InputKind::File)?.unwrap().ignored);
/// assert!(
///     !rules
///         .check(b"important.log", InputKind::File)?
///         .unwrap()
///         .ignored
/// );
/// assert!(rules.check(b"source.rs", InputKind::File)?.is_none());
/// # Ok::<(), girt::ignore::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct Ignore {
    case: Case,
    limits: Limits,
    // Shared so that a copy extended by one more directory costs only reference counts.
    sources: Vec<Arc<Rules>>,
    bytes: usize,
    patterns: usize,
}
/// Counts from [`Ignore::usage`].
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[derive(Clone, Copy)]
pub(crate) struct Usage {
    pub(crate) sources: usize,
    pub(crate) patterns: usize,
}

#[derive(Clone, Debug)]
struct Rules {
    base: Vec<u8>,
    rank: (u8, usize, usize),
    patterns: Vec<(usize, Pattern)>,
}
impl Ignore {
    /// Creates an empty set with explicit comparison and resource policies.
    pub fn new(case: Case, limits: Limits) -> Self {
        Self {
            case,
            limits,
            sources: Vec::new(),
            bytes: 0,
            patterns: 0,
        }
    }

    /// The comparison policy chosen at construction.
    #[must_use]
    pub fn case(&self) -> Case {
        self.case
    }

    /// The budgets every addition and query is checked against.
    #[must_use]
    pub fn limits(&self) -> Limits {
        self.limits
    }

    /// Sources and patterns added so far, counted against [`Limits::sources`] and
    /// [`Limits::patterns`].
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub(crate) fn usage(&self) -> Usage {
        Usage {
            sources: self.sources.len(),
            patterns: self.patterns,
        }
    }

    /// Source bytes that can still be added before [`Limits::bytes`] is reached.
    pub(crate) fn remaining_bytes(&self) -> usize {
        self.limits.bytes.saturating_sub(self.bytes)
    }

    /// Compiles a source and returns its stable insertion index.
    ///
    /// Source order need not follow hierarchy; precedence is determined by [`Source`]. All
    /// previously added sources remain unchanged on error, including their provenance indices.
    /// Duplicate directory additions are concatenated in addition order, not replacements.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Path`] for invalid directory prefixes and [`Error::Limit`] before retaining
    /// input beyond the configured budgets. A rejected addition leaves the set unchanged.
    ///
    /// ```
    /// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
    /// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
    /// let source = rules.add(Source::Directory(b"src"), b"# generated\n*.tmp\n")?;
    /// let found = rules.check(b"src/parser.tmp", InputKind::File)?.unwrap();
    /// assert_eq!((found.source, found.line), (source, 2));
    /// assert!(rules.check(b"parser.tmp", InputKind::File)?.is_none());
    /// # Ok::<(), girt::ignore::Error>(())
    /// ```
    pub fn add(&mut self, source: Source<'_>, content: &[u8]) -> Result<usize, Error> {
        let (level, base) = match source {
            Source::Global => (0, &b""[..]),
            Source::Info => (1, &b""[..]),
            Source::Directory(base) => (2, base),
            Source::Command => (3, &b""[..]),
        };
        validate_path(base, true, self.limits.path_bytes)?;
        let bytes = self
            .bytes
            .saturating_add(content.len())
            .saturating_add(base.len());
        if bytes > self.limits.bytes {
            return Err(Error::Limit("source bytes"));
        }
        if self.sources.len() >= self.limits.sources {
            return Err(Error::Limit("source count"));
        }
        let content = content.strip_prefix(b"\xef\xbb\xbf").unwrap_or(content);
        let mut patterns = Vec::new();
        for (line, raw) in content.split(|b| *b == b'\n').enumerate() {
            if raw.len() > self.limits.line_bytes {
                return Err(Error::Limit("line bytes"));
            }
            if let Some(pattern) = Pattern::parse(raw, self.case) {
                if self.patterns.saturating_add(patterns.len()) >= self.limits.patterns {
                    return Err(Error::Limit("pattern count"));
                }
                patterns.push((line + 1, pattern));
            }
        }
        let index = self.sources.len();
        let depth = if base.is_empty() {
            0
        } else {
            base.split(|b| *b == b'/').count()
        };
        self.patterns += patterns.len();
        self.bytes = bytes;
        self.sources.push(Arc::new(Rules {
            base: base.to_vec(),
            rank: (level, depth, index),
            patterns,
        }));
        self.sources.sort_by_key(|s| s.rank);
        Ok(index)
    }

    /// Resolves a file or directory, including all parent exclusions.
    ///
    /// Supply a nonempty repository-relative path without a trailing slash. Intermediate
    /// components are treated as directories. A symlink itself is not a directory; callers must
    /// not traverse through symlinks. `None` means no rule matched the final path. A negation
    /// returns `Some` with `ignored == false`; an excluded ancestor returns its own provenance.
    /// This method does not consult the index: apply tracked-file policy before using its result.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Path`] for invalid paths and [`Error::Limit`] for path/work exhaustion.
    /// There are no side effects or partial decisions. Each call receives a fresh work budget.
    ///
    /// ```
    /// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
    /// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
    /// rules.add(Source::Directory(b""), b"build/\n!build/keep.txt\n")?;
    /// let found = rules.check(b"build/keep.txt", InputKind::File)?.unwrap();
    /// assert!(found.ignored); // The excluded parent prevents re-inclusion.
    /// assert_eq!(found.matched_bytes, b"build".len());
    /// # Ok::<(), girt::ignore::Error>(())
    /// ```
    #[expect(
        clippy::indexing_slicing,
        reason = "each end is the position of a `/` in path"
    )]
    pub fn check(&self, path: &[u8], kind: InputKind) -> Result<Option<Match>, Error> {
        validate_path(path, false, self.limits.path_bytes)?;
        let mut work = self.limits.work;
        for end in path
            .iter()
            .enumerate()
            .filter_map(|(i, b)| (*b == b'/').then_some(i))
        {
            let found = self.direct(&path[..end], true, &mut work)?;
            if found.is_some_and(|m| m.ignored) {
                return Ok(found);
            }
        }
        self.direct(path, kind == InputKind::Directory, &mut work)
    }

    /// Resolves rules for this path without checking excluded ancestors.
    ///
    /// Use this when the caller traverses directories and has already decided whether each
    /// ancestor may be entered. [`Ignore::check`] is the usual whole-path query. A match here
    /// does not establish that an untracked child of an excluded directory can be included.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Path`] for invalid paths and [`Error::Limit`] for path or matching-work
    /// exhaustion. No partial decision is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::ignore::{Case, Ignore, InputKind, Limits, Source};
    ///
    /// let mut rules = Ignore::new(Case::Sensitive, Limits::default());
    /// rules.add(Source::Info, b"build/\n!build/keep\n")?;
    /// assert!(
    ///     !rules
    ///         .check_direct(b"build/keep", InputKind::File)?
    ///         .unwrap()
    ///         .ignored
    /// );
    /// assert!(
    ///     rules
    ///         .check(b"build/keep", InputKind::File)?
    ///         .unwrap()
    ///         .ignored
    /// );
    /// // Direct queries explain leaf rules; full queries enforce excluded-parent behavior.
    /// # Ok::<(), girt::ignore::Error>(())
    /// ```
    pub fn check_direct(&self, path: &[u8], kind: InputKind) -> Result<Option<Match>, Error> {
        validate_path(path, false, self.limits.path_bytes)?;
        let mut work = self.limits.work;
        self.direct(path, kind == InputKind::Directory, &mut work)
    }

    fn direct(
        &self,
        path: &[u8],
        directory: bool,
        work: &mut usize,
    ) -> Result<Option<Match>, Error> {
        for source in self.sources.iter().rev() {
            charge(work, source.base.len().saturating_add(1))?;
            let Some(relative) = relative(path, &source.base, self.case) else {
                continue;
            };
            for (line, pattern) in source.patterns.iter().rev() {
                charge(work, 1)?;
                if pattern.matches(relative, directory, work)? {
                    return Ok(Some(Match {
                        ignored: !pattern.negative,
                        source: source.rank.2,
                        line: *line,
                        matched_bytes: path.len(),
                    }));
                }
            }
        }
        Ok(None)
    }
}

pub(super) fn charge(work: &mut usize, cost: usize) -> Result<(), Error> {
    *work = work
        .checked_sub(cost)
        .ok_or(Error::Limit("matching work"))?;
    Ok(())
}
fn validate_path(path: &[u8], root: bool, limit: usize) -> Result<(), Error> {
    if path.len() > limit {
        return Err(Error::Limit("path bytes"));
    }
    if path.is_empty() && root {
        return Ok(());
    }
    if path.contains(&0)
        || path
            .split(|b| *b == b'/')
            .any(|p| p.is_empty() || p == b"." || p == b"..")
    {
        return Err(Error::Path);
    }
    Ok(())
}
fn relative<'a>(path: &'a [u8], base: &[u8], case: Case) -> Option<&'a [u8]> {
    if base.is_empty() {
        return Some(path);
    }
    let prefix = path.get(..base.len())?;
    let equal = match case {
        Case::Sensitive => prefix == base,
        Case::AsciiInsensitive => prefix.eq_ignore_ascii_case(base),
    };
    #[expect(clippy::indexing_slicing, reason = "path has a `/` at base.len()")]
    (equal && path.get(base.len()) == Some(&b'/')).then(|| &path[base.len() + 1..])
}