grit-lib 0.5.18

Core library for the grit Git implementation
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Git-compatible path component validation (`verify_path` / tree fsck rules).
//!
//! Centralizes NTFS/HFS dot-file checks and tree-entry rules that previously
//! lived in separate internal modules. Embedders use this before writing index entries,
//! checking out paths, or building trees; [`ProtectOptions`] mirrors
//! `core.protectNTFS` and `core.protectHFS`.
//!
//! ```rust
//! use grit_lib::path_validate::{validate_path, EntryMode, ProtectOptions};
//!
//! let opts = ProtectOptions::default();
//! validate_path(b"src/lib.rs", EntryMode::new(0o100644), opts).unwrap();
//! ```

use crate::config::ConfigSet;
use crate::dotfile::{
    is_hfs_dot_gitattributes, is_hfs_dot_gitignore, is_hfs_dot_gitmodules, is_hfs_dot_mailmap,
    is_hfs_dotgit, is_ntfs_dot_gitattributes, is_ntfs_dot_gitignore, is_ntfs_dot_gitmodules,
    is_ntfs_dot_mailmap, is_ntfs_dotgit,
};
use thiserror::Error;

/// Git tree/index file mode for validation (symlink vs blob affects dot-file rules).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EntryMode(u32);

impl EntryMode {
    /// Wrap a raw Git mode octal value (for example `0o100644`).
    #[must_use]
    pub const fn new(mode: u32) -> Self {
        Self(mode)
    }

    /// `true` when this entry is a symbolic link (`0o120000`).
    #[must_use]
    pub fn is_symlink(self) -> bool {
        self.0 == 0o120000
    }
}

/// Which Git path rules to apply ([`validate_component`] / [`validate_path`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum PathValidationKind {
    /// Object fsck: all symlink dot-file rules; NTFS spellings when [`ProtectOptions`] say so.
    Fsck,
    /// Index population, checkout, and staging (Git `verify_path` on this platform).
    #[default]
    Worktree,
}

/// Whether NTFS and HFS+ spelling protections apply (from `core.protectNTFS` / `core.protectHFS`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ProtectOptions {
    /// Reject NTFS `.git` spellings, short names, `\\` segments, and `:` streams.
    pub protect_ntfs: bool,
    /// Reject HFS+ Unicode-ignorable `.git` spellings.
    pub protect_hfs: bool,
}

impl Default for ProtectOptions {
    fn default() -> Self {
        Self {
            protect_ntfs: true,
            protect_hfs: cfg!(target_os = "macos"),
        }
    }
}

impl ProtectOptions {
    /// Load protection flags from a merged [`ConfigSet`] (no environment reads).
    ///
    /// Defaults match Git: `core.protectNTFS` true; `core.protectHFS` true on macOS, false elsewhere.
    #[must_use]
    pub fn from_config(config: &ConfigSet) -> Self {
        let protect_ntfs = config
            .get_bool("core.protectNTFS")
            .or_else(|| config.get_bool("core.protectntfs"))
            .and_then(|r| r.ok())
            .unwrap_or(true);
        let default_hfs = cfg!(target_os = "macos");
        let protect_hfs = config
            .get_bool("core.protectHFS")
            .or_else(|| config.get_bool("core.protecthfs"))
            .and_then(|r| r.ok())
            .unwrap_or(default_hfs);
        Self {
            protect_ntfs,
            protect_hfs,
        }
    }

    /// Protection settings used by object fsck (always check both spellings).
    #[must_use]
    pub const fn fsck() -> Self {
        Self {
            protect_ntfs: true,
            protect_hfs: true,
        }
    }
}

/// Why a single path component fails validation.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum PathComponentError {
    /// Zero-length component.
    #[error("path component is empty")]
    Empty,
    /// Component is exactly `.`.
    #[error("path component is a single dot")]
    Dot,
    /// Component is exactly `..`.
    #[error("path component is parent directory")]
    DotDot,
    /// Component names `.git` (ASCII case rules) or `git~1`.
    #[error("path component is a .git alias")]
    DotGit,
    /// A `/` appears inside one component (tree entries must be single segments).
    #[error("path component contains a slash")]
    ContainsSlash,
    /// A NUL byte appears in the component.
    #[error("path component contains a NUL byte")]
    ContainsNul,
    /// HFS+ ignorable code points spell `.git` or a protected dot-file.
    #[error("path component is an HFS .git alias")]
    HfsDotGit,
    /// NTFS trailing space/dot, short name, or stream spelling for `.git`.
    #[error("path component is an NTFS .git alias")]
    NtfsDotGit,
    /// Backslash introduces an NTFS `.git` segment in the component.
    #[error("path component contains a backslash before a .git alias")]
    NtfsBackslash,
    /// DOS drive prefix or NTFS alternate-data-stream syntax in the component.
    #[error("path component uses a forbidden NTFS drive or stream prefix")]
    NtfsDriveOrStream,
    /// Symlink whose name matches `.gitmodules` (HFS or NTFS spelling).
    #[error("symbolic link must not be named .gitmodules")]
    SymlinkedDotGitmodules,
    /// Symlink whose name matches `.gitattributes` (HFS or NTFS spelling).
    #[error("symbolic link must not be named .gitattributes")]
    SymlinkedDotGitattributes,
    /// Symlink whose name matches `.gitignore` (HFS or NTFS spelling).
    #[error("symbolic link must not be named .gitignore")]
    SymlinkedDotGitignore,
    /// Symlink whose name matches `.mailmap` (HFS or NTFS spelling).
    #[error("symbolic link must not be named .mailmap")]
    SymlinkedDotMailmap,
}

/// Semantic problems detected on a tree entry name (fsck aggregates several at once).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TreeEntryNameAudit {
    /// Empty component.
    pub empty: bool,
    /// Component is `.`.
    pub dot: bool,
    /// Component is `..`.
    pub dotdot: bool,
    /// Slash inside the component.
    pub slash: bool,
    /// NUL inside the component.
    pub nul: bool,
    /// Any `.git` alias (ASCII, HFS, NTFS, backslash, or `git~1`).
    pub dotgit: bool,
}

impl TreeEntryNameAudit {
    /// Merge another audit into this one (bitwise OR of flags).
    pub fn absorb(&mut self, other: Self) {
        self.empty |= other.empty;
        self.dot |= other.dot;
        self.dotdot |= other.dotdot;
        self.slash |= other.slash;
        self.nul |= other.nul;
        self.dotgit |= other.dotgit;
    }
}

/// Validate one path component (no `/` splitting).
///
/// # Errors
///
/// Returns the first [`PathComponentError`] encountered in Git fsck priority order
/// when multiple rules apply.
pub fn validate_component(
    name: &[u8],
    mode: EntryMode,
    opts: ProtectOptions,
    kind: PathValidationKind,
) -> Result<(), PathComponentError> {
    if name.is_empty() {
        return Err(PathComponentError::Empty);
    }
    if name.contains(&0) {
        return Err(PathComponentError::ContainsNul);
    }
    if name.contains(&b'/') {
        return Err(PathComponentError::ContainsSlash);
    }
    if let Some(err) = validate_component_symlink_dotfile(name, mode, opts, kind) {
        return Err(err);
    }
    if opts.protect_ntfs && ntfs_path_syntax_rules_apply() {
        if has_dos_drive_prefix_bytes(name) {
            return Err(PathComponentError::NtfsDriveOrStream);
        }
        if let Ok(name_str) = std::str::from_utf8(name) {
            if scan_ntfs_backslash_dot_special(name_str, ntfs_backslash_dotdot_tail) {
                return Err(PathComponentError::NtfsBackslash);
            }
        }
    }
    let audit = audit_tree_entry_name(name, opts);
    if audit.empty {
        return Err(PathComponentError::Empty);
    }
    if audit.slash {
        return Err(PathComponentError::ContainsSlash);
    }
    if audit.nul {
        return Err(PathComponentError::ContainsNul);
    }
    if audit.dot {
        return Err(PathComponentError::Dot);
    }
    if audit.dotdot {
        return Err(PathComponentError::DotDot);
    }
    if audit.dotgit {
        return Err(classify_dotgit_component_error(name, opts));
    }
    Ok(())
}

/// Validate a repository-relative path by checking each `/`-separated component.
///
/// # Errors
///
/// Same as [`validate_component`] for the first failing segment.
pub fn validate_path(
    path: &[u8],
    mode: EntryMode,
    opts: ProtectOptions,
    kind: PathValidationKind,
) -> Result<(), PathComponentError> {
    if path.is_empty() {
        return Err(PathComponentError::Empty);
    }
    if path.contains(&0) {
        return Err(PathComponentError::ContainsNul);
    }
    for component in path.split(|&b| b == b'/') {
        if component.is_empty() {
            return Err(PathComponentError::Empty);
        }
        validate_component(component, mode, opts, kind)?;
    }
    Ok(())
}

fn ntfs_path_syntax_rules_apply() -> bool {
    cfg!(windows)
}

/// Populate [`TreeEntryNameAudit`] for a tree object entry name (fsck uses all flags).
#[must_use]
pub fn audit_tree_entry_name(name: &[u8], opts: ProtectOptions) -> TreeEntryNameAudit {
    let mut audit = TreeEntryNameAudit::default();
    if name.is_empty() {
        audit.empty = true;
        return audit;
    }
    if name.contains(&0) {
        audit.nul = true;
    }
    if name == b"." {
        audit.dot = true;
    }
    if name == b".." {
        audit.dotdot = true;
    }
    if name.contains(&b'/') {
        audit.slash = true;
    }
    if component_is_dotgit_alias(name, opts) {
        audit.dotgit = true;
    }
    audit
}

impl TreeEntryNameAudit {
    /// Map aggregated flags to a single error (Git fsck reporting order).
    pub fn first_error(self) -> Result<(), PathComponentError> {
        if self.empty {
            return Err(PathComponentError::Empty);
        }
        if self.slash {
            return Err(PathComponentError::ContainsSlash);
        }
        if self.nul {
            return Err(PathComponentError::ContainsNul);
        }
        if self.dot {
            return Err(PathComponentError::Dot);
        }
        if self.dotdot {
            return Err(PathComponentError::DotDot);
        }
        if self.dotgit {
            return Err(PathComponentError::DotGit);
        }
        Ok(())
    }
}

/// Returns `true` when `name` should trigger fsck `hasDotgit` for a tree entry.
#[must_use]
pub fn component_is_dotgit_alias(name: &[u8], opts: ProtectOptions) -> bool {
    if name.eq_ignore_ascii_case(b".git") {
        return true;
    }
    if name.eq_ignore_ascii_case(b"git~1") && opts.protect_ntfs {
        return true;
    }
    let Ok(name_str) = std::str::from_utf8(name) else {
        return false;
    };
    if opts.protect_hfs && is_hfs_dotgit(name_str) {
        return true;
    }
    if opts.protect_ntfs && (is_ntfs_dotgit(name_str) || scan_ntfs_backslash_dotgit(name_str)) {
        return true;
    }
    false
}

fn validate_component_symlink_dotfile(
    name: &[u8],
    mode: EntryMode,
    opts: ProtectOptions,
    kind: PathValidationKind,
) -> Option<PathComponentError> {
    if !mode.is_symlink() {
        return None;
    }
    if name.eq_ignore_ascii_case(b".gitmodules") {
        return Some(PathComponentError::SymlinkedDotGitmodules);
    }
    let Ok(name_str) = std::str::from_utf8(name) else {
        return None;
    };
    if dot_gitmodules_spelling(name_str, opts) {
        return Some(PathComponentError::SymlinkedDotGitmodules);
    }
    if kind == PathValidationKind::Worktree {
        return None;
    }
    if name.eq_ignore_ascii_case(b".gitattributes") {
        return Some(PathComponentError::SymlinkedDotGitattributes);
    }
    if name.eq_ignore_ascii_case(b".gitignore") {
        return Some(PathComponentError::SymlinkedDotGitignore);
    }
    if name.eq_ignore_ascii_case(b".mailmap") {
        return Some(PathComponentError::SymlinkedDotMailmap);
    }
    if dot_gitattributes_spelling(name_str, opts) {
        return Some(PathComponentError::SymlinkedDotGitattributes);
    }
    if opts.protect_hfs && is_hfs_dot_gitignore(name_str) {
        return Some(PathComponentError::SymlinkedDotGitignore);
    }
    if opts.protect_hfs && is_hfs_dot_mailmap(name_str) {
        return Some(PathComponentError::SymlinkedDotMailmap);
    }
    if opts.protect_ntfs && is_ntfs_dot_gitignore(name_str) {
        return Some(PathComponentError::SymlinkedDotGitignore);
    }
    if opts.protect_ntfs && is_ntfs_dot_mailmap(name_str) {
        return Some(PathComponentError::SymlinkedDotMailmap);
    }
    None
}

fn dot_gitmodules_spelling(name: &str, opts: ProtectOptions) -> bool {
    (opts.protect_hfs && is_hfs_dot_gitmodules(name))
        || (opts.protect_ntfs && is_ntfs_dot_gitmodules(name))
        || (opts.protect_ntfs && scan_ntfs_backslash_dot_special(name, is_ntfs_dot_gitmodules))
}

fn dot_gitattributes_spelling(name: &str, opts: ProtectOptions) -> bool {
    (opts.protect_hfs && is_hfs_dot_gitattributes(name))
        || (opts.protect_ntfs && is_ntfs_dot_gitattributes(name))
        || (opts.protect_ntfs && scan_ntfs_backslash_dot_special(name, is_ntfs_dot_gitattributes))
}

fn classify_dotgit_component_error(name: &[u8], opts: ProtectOptions) -> PathComponentError {
    if name.eq_ignore_ascii_case(b".git") || name.eq_ignore_ascii_case(b"git~1") {
        return PathComponentError::DotGit;
    }
    let Ok(name_str) = std::str::from_utf8(name) else {
        return PathComponentError::DotGit;
    };
    if opts.protect_ntfs && scan_ntfs_backslash_dotgit(name_str) {
        return PathComponentError::NtfsBackslash;
    }
    if opts.protect_hfs && is_hfs_dotgit(name_str) {
        return PathComponentError::HfsDotGit;
    }
    if opts.protect_ntfs && is_ntfs_dotgit(name_str) {
        return PathComponentError::NtfsDotGit;
    }
    PathComponentError::DotGit
}

fn scan_ntfs_backslash_dotgit(name: &str) -> bool {
    scan_ntfs_backslash_dot_special(name, is_ntfs_dotgit)
}

fn ntfs_backslash_dotdot_tail(after: &str) -> bool {
    after == ".." || after.starts_with("..\\") || after.starts_with("../")
}

fn scan_ntfs_backslash_dot_special(name: &str, mut pred: impl FnMut(&str) -> bool) -> bool {
    if !name.contains('\\') {
        return false;
    }
    let mut rest = name;
    while let Some(idx) = rest.find('\\') {
        let segment = &rest[..idx];
        if !segment.is_empty() && pred(segment) {
            return true;
        }
        rest = &rest[idx + 1..];
    }
    !rest.is_empty() && pred(rest)
}

fn has_dos_drive_prefix_bytes(name: &[u8]) -> bool {
    name.len() >= 2 && name[0].is_ascii_alphabetic() && name[1] == b':'
}

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

    const BLOB: EntryMode = EntryMode::new(0o100644);
    const SYMLINK: EntryMode = EntryMode::new(0o120000);
    const FSCK: ProtectOptions = ProtectOptions::fsck();
    const OFF: ProtectOptions = ProtectOptions {
        protect_ntfs: false,
        protect_hfs: false,
    };
    const FSCK_KIND: PathValidationKind = PathValidationKind::Fsck;
    const WT_KIND: PathValidationKind = PathValidationKind::Worktree;

    #[test]
    fn empty_dot_and_dotdot_rejected() {
        assert_eq!(
            validate_component(b"", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::Empty
        );
        assert_eq!(
            validate_component(b".", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::Dot
        );
        assert_eq!(
            validate_component(b"..", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::DotDot
        );
    }

    #[test]
    fn slash_and_nul_in_component() {
        assert_eq!(
            validate_component(b"foo/bar", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::ContainsSlash
        );
        assert_eq!(
            validate_component(b"foo\0bar", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::ContainsNul
        );
    }

    #[test]
    fn ascii_dotgit_and_git_tilde_one() {
        for name in [b".git".as_slice(), b".GIT".as_slice()] {
            assert_eq!(
                validate_component(name, BLOB, OFF, FSCK_KIND).unwrap_err(),
                PathComponentError::DotGit
            );
        }
        for name in [b"git~1".as_slice(), b"GIT~1".as_slice()] {
            assert_eq!(
                validate_component(name, BLOB, FSCK, FSCK_KIND).unwrap_err(),
                PathComponentError::DotGit
            );
            assert!(validate_component(name, BLOB, OFF, FSCK_KIND).is_ok());
        }
        assert!(validate_component(b"git~2", BLOB, OFF, FSCK_KIND).is_ok());
    }

    #[test]
    fn hfs_dotgit_unicode_ignored_codepoints() {
        let name = ".gI\u{200c}T";
        assert_eq!(
            validate_component(name.as_bytes(), BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::HfsDotGit
        );
        assert!(validate_component(name.as_bytes(), BLOB, OFF, FSCK_KIND).is_ok());
    }

    #[test]
    fn ntfs_dotgit_trailing_dot_and_spaces() {
        assert_eq!(
            validate_component(b".git.", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::NtfsDotGit
        );
        assert_eq!(
            validate_component(b".git ", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::NtfsDotGit
        );
    }

    #[test]
    fn ntfs_backslash_dotgit_segment() {
        assert_eq!(
            validate_component(b"foo\\.git", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::NtfsBackslash
        );
        for name in [b".git\\config".as_slice(), b".git\\", b".GIT\\config"] {
            assert_eq!(
                validate_component(name, BLOB, FSCK, WT_KIND).unwrap_err(),
                PathComponentError::NtfsBackslash,
                "reject {name:?}"
            );
        }
        if cfg!(windows) {
            assert_eq!(
                validate_component(br"a\..\x", BLOB, FSCK, FSCK_KIND).unwrap_err(),
                PathComponentError::NtfsBackslash
            );
        } else {
            assert!(validate_component(br"a\..\x", BLOB, FSCK, FSCK_KIND).is_ok());
        }
        assert!(validate_component(br"a\..\x", BLOB, OFF, FSCK_KIND).is_ok());
    }

    #[test]
    fn ntfs_alternate_stream_dotgit() {
        assert_eq!(
            validate_component(b".git::$INDEX_ALLOCATION", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::NtfsDotGit
        );
    }

    #[test]
    fn ntfs_dos_drive_prefix_in_component() {
        if cfg!(windows) {
            assert_eq!(
                validate_component(b"C:foo", BLOB, FSCK, FSCK_KIND).unwrap_err(),
                PathComponentError::NtfsDriveOrStream
            );
        } else {
            assert!(validate_component(b"C:foo", BLOB, FSCK, FSCK_KIND).is_ok());
            assert!(validate_component(b"C:foo", BLOB, FSCK, WT_KIND).is_ok());
        }
    }

    #[test]
    fn issue_1037_multibyte_at_byte_six_no_panic() {
        for name in ["abcde日.txt", "ab日本.txt", "file0日本.txt"] {
            assert!(validate_component(name.as_bytes(), BLOB, FSCK, FSCK_KIND).is_ok());
            assert!(!audit_tree_entry_name(name.as_bytes(), FSCK).dotgit);
        }
    }

    #[test]
    fn symlink_dot_special_files() {
        assert_eq!(
            validate_component(b".gitmodules", SYMLINK, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotGitmodules
        );
        assert_eq!(
            validate_component(b".gitattributes", SYMLINK, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotGitattributes
        );
        assert_eq!(
            validate_component(b".gitignore", SYMLINK, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotGitignore
        );
        assert_eq!(
            validate_component(b".mailmap", SYMLINK, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotMailmap
        );
        assert!(validate_component(b".gitmodules", BLOB, FSCK, FSCK_KIND).is_ok());
        assert!(validate_component(b".gitattributes", SYMLINK, FSCK, WT_KIND).is_ok());
    }

    #[test]
    fn symlink_ascii_dot_special_banned_when_protect_flags_off() {
        assert_eq!(
            validate_component(b".gitmodules", SYMLINK, OFF, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotGitmodules
        );
        assert_eq!(
            validate_component(b".gitignore", SYMLINK, OFF, FSCK_KIND).unwrap_err(),
            PathComponentError::SymlinkedDotGitignore
        );
    }

    #[test]
    fn dos_drive_prefix_on_non_utf8_bytes() {
        if cfg!(windows) {
            assert_eq!(
                validate_component(b"C:\xff", BLOB, FSCK, FSCK_KIND).unwrap_err(),
                PathComponentError::NtfsDriveOrStream
            );
        } else {
            assert!(validate_component(b"C:\xff", BLOB, FSCK, FSCK_KIND).is_ok());
        }
    }

    #[test]
    fn validate_path_rejects_empty_slash_delimited_components() {
        for path in [
            b"/a".as_slice(),
            b"a/".as_slice(),
            b"a//b".as_slice(),
            b"//a".as_slice(),
        ] {
            assert_eq!(
                validate_path(path, BLOB, FSCK, FSCK_KIND).unwrap_err(),
                PathComponentError::Empty,
                "path {:?} should be rejected",
                path
            );
        }
        assert!(validate_path(b"a/b", BLOB, FSCK, FSCK_KIND).is_ok());
    }

    #[test]
    fn validate_path_splits_on_slash() {
        assert!(validate_path(b"dir/file.txt", BLOB, FSCK, FSCK_KIND).is_ok());
        assert_eq!(
            validate_path(b"dir/.git/file", BLOB, FSCK, FSCK_KIND).unwrap_err(),
            PathComponentError::DotGit
        );
    }

    #[test]
    fn protect_options_from_config_defaults() {
        let cfg = ConfigSet::new();
        let opts = ProtectOptions::from_config(&cfg);
        assert!(opts.protect_ntfs);
        assert_eq!(opts.protect_hfs, cfg!(target_os = "macos"));
    }

    #[test]
    fn audit_matches_validate_for_tree_cases() {
        let audit = audit_tree_entry_name(b".git", FSCK);
        assert!(audit.dotgit);
        assert_eq!(audit.first_error().unwrap_err(), PathComponentError::DotGit);
    }
}