git-filter-tree 0.3.1

Filter and write trees in Git's object database.
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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! Filter Git tree objects by glob patterns, gitattributes, or a custom predicate.
//!
//! This crate exposes the [`FilterTree`] trait, implemented on
//! [`git2::Repository`], which produces a new tree containing only the entries
//! that match either a set of **glob patterns**, a set of **gitattributes**,
//! or an arbitrary **predicate function**.
//! Trees are walked recursively; patterns are matched against full paths from
//! the tree root.
//!
//! It is the plumbing library behind the `git filter-tree` command and the
//! [`git-rewrite`](https://docs.rs/git-rewrite) porcelain.
//!
//! # Filter by Pattern
//!
//! ```no_run
//! use git_filter_tree::FilterTree as _;
//!
//! let repo = git2::Repository::open_from_env()?;
//! let tree = repo.head()?.peel_to_tree()?;
//!
//! // Produce a new tree that contains only Rust source files.
//! let filtered = repo.filter_by_patterns(&tree, &["**/*.rs"])?;
//! println!("tree sha: {}", filtered.id());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! A trailing `/` is expanded to `dir/**`, so `"src/"` keeps all files under
//! `src/`. Multiple patterns are OR-ed together.
//!
//! # Filter by Attributes
//!
//! ```no_run
//! use git_filter_tree::FilterTree as _;
//!
//! let repo = git2::Repository::open_from_env()?;
//! let tree = repo.head()?.peel_to_tree()?;
//!
//! // Keep only entries that have the `export` attribute set in .gitattributes.
//! let filtered = repo.filter_by_attributes(&tree, &["export"])?;
//! println!("tree sha: {}", filtered.id());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! All listed attributes must be set (AND semantics). Entries with an
//! attribute explicitly unset (`-export`) or unspecified are excluded.
//!
//! # Filter by Predicate
//!
//! ```no_run
//! use git_filter_tree::FilterTree as _;
//! use std::path::Path;
//!
//! let repo = git2::Repository::open_from_env()?;
//! let tree = repo.head()?.peel_to_tree()?;
//!
//! // Keep only files whose path contains "generated".
//! let filtered = repo.filter_by_predicate(&tree, |_repo, path| {
//!     path.to_str().is_some_and(|s| s.contains("generated"))
//! })?;
//! println!("tree sha: {}", filtered.id());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! The predicate receives the repository and the full path of each blob entry
//! relative to the tree root. Subtrees are included as long as at least one
//! descendant matches.
pub mod exe;
use std::path::Path;

pub use git2::{Error, Repository};
use globset::GlobSetBuilder;

pub trait FilterTree {
    /// Filters tree entries by gitattributes-style patterns and returns a new tree with contents
    /// filtered through the provided patterns. Recursively walks the tree and matches patterns
    /// against full paths from the tree root.
    ///
    /// The `patterns` type is an array of string slices and not a glob type because Git has
    /// specific glob syntax that differs from standard shell syntax.
    fn filter_by_patterns<'a>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        patterns: &[&str], // TODO create a `git-glob` crate to handle patterns more gracefully
    ) -> Result<git2::Tree<'a>, Error>;

    /// Filters tree entries by gitattributes and returns a new tree with contents filtered.
    /// Recursively walks the tree and matches attributes against full paths from the tree root.
    ///
    /// The `attributes` type is an array of string slices. For attributes which have values,
    /// not simply set or unset, use typical `.gitattributes` syntax.
    fn filter_by_attributes<'a>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        attributes: &[&str],
    ) -> Result<git2::Tree<'a>, Error>;

    /// Filters tree entries using an arbitrary predicate and returns a new tree.
    /// Recursively walks the tree; the predicate is called for each blob entry
    /// with the repository and the entry's full path relative to the tree root.
    /// Subtrees are retained as long as at least one descendant matches.
    fn filter_by_predicate<'a, F>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        predicate: F,
    ) -> Result<git2::Tree<'a>, Error>
    where
        F: Fn(&git2::Repository, &Path) -> bool;
}

impl FilterTree for git2::Repository {
    fn filter_by_patterns<'a>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        patterns: &[&str],
    ) -> Result<git2::Tree<'a>, Error> {
        if patterns.is_empty() {
            return Err(Error::from_str("At least one pattern is required"));
        }

        // Build GlobSet matcher
        let mut glob_builder = GlobSetBuilder::new();
        for pattern in patterns {
            // A trailing `/` means "this directory" in gitattributes/gitignore
            // semantics.  Normalize to `dir/**` so globset matches all files
            // under the directory recursively.
            let normalized: String;
            let pat = if pattern.ends_with('/') {
                normalized = format!("{}**", pattern);
                normalized.as_str()
            } else {
                pattern
            };
            let glob = globset::Glob::new(pat)
                .map_err(|e| Error::from_str(&format!("Invalid pattern '{}': {}", pattern, e)))?;
            glob_builder.add(glob);
        }

        let matcher = glob_builder
            .build()
            .map_err(|e| Error::from_str(&e.to_string()))?;

        // Recursively filter the tree
        filter_tree_recursive(self, tree, None, &|_repo, path| matcher.is_match(path))
    }

    fn filter_by_predicate<'a, F>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        predicate: F,
    ) -> Result<git2::Tree<'a>, Error>
    where
        F: Fn(&git2::Repository, &Path) -> bool,
    {
        filter_tree_recursive(self, tree, None, &predicate)
    }

    fn filter_by_attributes<'a>(
        &'a self,
        tree: &'a git2::Tree<'a>,
        attributes: &[&str],
    ) -> Result<git2::Tree<'a>, Error> {
        if attributes.is_empty() {
            return Err(git2::Error::from_str("at least one attribute is required"));
        }

        filter_tree_recursive(self, tree, None, &|repo, path| {
            for attribute in attributes {
                match repo.get_attr(path, attribute, git2::AttrCheckFlags::FILE_THEN_INDEX) {
                    Ok(Some(value)) => {
                        let value = git2::AttrValue::from_string(Some(value));
                        match value {
                            git2::AttrValue::Unspecified => return false,
                            git2::AttrValue::False => return false,
                            _ => {}
                        }
                    }
                    Ok(None) => return false,
                    Err(_) => return false,
                }
            }

            true
        })
    }
}

/// Recursively filters a tree, matching patterns against full paths.
/// Returns a new tree containing only entries that match or have matching descendants.
fn filter_tree_recursive<'a, F>(
    repo: &'a Repository,
    tree: &'a git2::Tree<'a>,
    prefix: Option<&str>,
    predicate: &F,
) -> Result<git2::Tree<'a>, Error>
where
    F: Fn(&Repository, &Path) -> bool,
{
    let mut builder = repo.treebuilder(None)?;

    for entry in tree.iter() {
        let Some(name) = entry.name() else {
            return Err(Error::from_str("name has invalid UTF-8"));
        };

        let git_path = match prefix {
            Some(dir) => format!("{}/{}", dir, name),
            None => name.to_string(),
        };
        let full_path = Path::new(&git_path);

        match entry.kind() {
            Some(git2::ObjectType::Blob) => {
                if predicate(repo, &full_path) {
                    builder.insert(name, entry.id(), entry.filemode())?;
                }
            }
            Some(git2::ObjectType::Tree) => {
                let subtree = entry.to_object(repo)?.peel_to_tree()?;
                let filtered_subtree =
                    filter_tree_recursive(repo, &subtree, Some(&git_path), predicate)?;
                if !filtered_subtree.is_empty() {
                    builder.insert(name, filtered_subtree.id(), entry.filemode())?;
                }
            }
            // Skip submodule commit pointers, tags, and any other unexpected
            // object types that can appear as tree entries.
            _ => continue,
        }
    }

    let tree_oid = builder.write()?;
    repo.find_tree(tree_oid)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    fn setup_test_repo() -> (Repository, PathBuf) {
        let thread_id = std::thread::current().id();
        let temp_path = std::env::temp_dir().join(format!("git-filter-tree-test-{:?}", thread_id));
        let _ = fs::remove_dir_all(&temp_path);
        fs::create_dir_all(&temp_path).unwrap();
        let repo = Repository::init_bare(&temp_path).unwrap();
        (repo, temp_path)
    }

    fn cleanup_test_repo(path: PathBuf) {
        let _ = fs::remove_dir_all(path);
    }

    fn create_test_tree<'a>(repo: &'a Repository) -> Result<git2::Tree<'a>, Error> {
        let mut tree_builder = repo.treebuilder(None)?;

        // Create some blob entries
        let blob1 = repo.blob(b"content1")?;
        let blob2 = repo.blob(b"content2")?;
        let blob3 = repo.blob(b"content3")?;

        tree_builder.insert("file1.txt", blob1, 0o100644)?;
        tree_builder.insert("file2.rs", blob2, 0o100644)?;
        tree_builder.insert("test.md", blob3, 0o100644)?;

        let tree_oid = tree_builder.write()?;
        repo.find_tree(tree_oid)
    }

    #[test]
    fn test_filter_single_pattern() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;
        assert_eq!(tree.len(), 3);

        // Filter for .txt files only
        let filtered = repo.filter_by_patterns(&tree, &["*.txt"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("file1.txt").is_some());
        assert!(filtered.get_name("file2.rs").is_none());
        assert!(filtered.get_name("test.md").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_multiple_patterns() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;

        // Filter for .txt and .rs files
        let filtered = repo.filter_by_patterns(&tree, &["*.txt", "*.rs"])?;
        assert_eq!(filtered.len(), 2);
        assert!(filtered.get_name("file1.txt").is_some());
        assert!(filtered.get_name("file2.rs").is_some());
        assert!(filtered.get_name("test.md").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_exact_match() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;

        // Filter for exact filename
        let filtered = repo.filter_by_patterns(&tree, &["file1.txt"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("file1.txt").is_some());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_wildcard_patterns() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;

        // Filter with wildcard pattern
        let filtered = repo.filter_by_patterns(&tree, &["file*"])?;
        assert_eq!(filtered.len(), 2);
        assert!(filtered.get_name("file1.txt").is_some());
        assert!(filtered.get_name("file2.rs").is_some());
        assert!(filtered.get_name("test.md").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_no_matches() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;

        // Filter with pattern that matches nothing
        let filtered = repo.filter_by_patterns(&tree, &["*.nonexistent"])?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_all_matches() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo)?;

        // Filter with pattern that matches everything
        let filtered = repo.filter_by_patterns(&tree, &["*"])?;
        assert_eq!(filtered.len(), 3);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_empty_patterns_error() {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo).unwrap();

        // Empty patterns should return an error
        let result = repo.filter_by_patterns(&tree, &[]);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().message(),
            "At least one pattern is required"
        );

        cleanup_test_repo(temp_path);
    }

    #[test]
    fn test_filter_invalid_pattern_error() {
        let (repo, temp_path) = setup_test_repo();

        let tree = create_test_tree(&repo).unwrap();

        // Invalid glob pattern should return an error
        let result = repo.filter_by_patterns(&tree, &["[invalid"]);
        assert!(result.is_err());

        cleanup_test_repo(temp_path);
    }

    #[test]
    fn test_filter_with_nested_tree() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let mut tree_builder = repo.treebuilder(None)?;

        // Create a nested tree
        let mut subtree_builder = repo.treebuilder(None)?;
        let blob = repo.blob(b"nested content")?;
        subtree_builder.insert("nested.txt", blob, 0o100644)?;
        let subtree_oid = subtree_builder.write()?;

        // Add files and subtree to main tree
        let blob1 = repo.blob(b"content1")?;
        tree_builder.insert("file1.txt", blob1, 0o100644)?;
        tree_builder.insert("subdir", subtree_oid, 0o040000)?;

        let tree_oid = tree_builder.write()?;
        let tree = repo.find_tree(tree_oid)?;

        // Filter - should keep both file and directory
        let filtered = repo.filter_by_patterns(&tree, &["*"])?;
        assert_eq!(filtered.len(), 2);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_preserves_empty_tree() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        // Create an empty tree
        let tree_builder = repo.treebuilder(None)?;
        let tree_oid = tree_builder.write()?;
        let tree = repo.find_tree(tree_oid)?;

        assert_eq!(tree.len(), 0);

        // Filter empty tree
        let filtered = repo.filter_by_patterns(&tree, &["*"])?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_case_sensitive() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let mut tree_builder = repo.treebuilder(None)?;
        let blob1 = repo.blob(b"content1")?;
        let blob2 = repo.blob(b"content2")?;

        tree_builder.insert("File.txt", blob1, 0o100644)?;
        tree_builder.insert("file.txt", blob2, 0o100644)?;

        let tree_oid = tree_builder.write()?;
        let tree = repo.find_tree(tree_oid)?;

        // Filter with exact case match
        let filtered = repo.filter_by_patterns(&tree, &["file.txt"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("file.txt").is_some());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_complex_patterns() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let mut tree_builder = repo.treebuilder(None)?;
        let blob = repo.blob(b"content")?;

        tree_builder.insert("test1.txt", blob, 0o100644)?;
        tree_builder.insert("test2.rs", blob, 0o100644)?;
        tree_builder.insert("data.json", blob, 0o100644)?;
        tree_builder.insert("README.md", blob, 0o100644)?;

        let tree_oid = tree_builder.write()?;
        let tree = repo.find_tree(tree_oid)?;

        // Multiple patterns with different wildcards
        let filtered = repo.filter_by_patterns(&tree, &["test*", "*.md"])?;
        assert_eq!(filtered.len(), 3);
        assert!(filtered.get_name("test1.txt").is_some());
        assert!(filtered.get_name("test2.rs").is_some());
        assert!(filtered.get_name("README.md").is_some());
        assert!(filtered.get_name("data.json").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_trailing_slash_matches_directory_contents() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        // Build a tree with a subdirectory: pyo3/Cargo.toml, pyo3/src/lib.rs,
        // and a top-level file that should NOT match.
        let blob = repo.blob(b"content")?;

        let mut src_builder = repo.treebuilder(None)?;
        src_builder.insert("lib.rs", blob, 0o100644)?;
        let src_oid = src_builder.write()?;

        let mut pyo3_builder = repo.treebuilder(None)?;
        pyo3_builder.insert("Cargo.toml", blob, 0o100644)?;
        pyo3_builder.insert("src", src_oid, 0o040000)?;
        let pyo3_oid = pyo3_builder.write()?;

        let mut root_builder = repo.treebuilder(None)?;
        root_builder.insert("pyo3", pyo3_oid, 0o040000)?;
        root_builder.insert("README.md", blob, 0o100644)?;
        let root_oid = root_builder.write()?;
        let tree = repo.find_tree(root_oid)?;

        // "pyo3/" (trailing slash) must match all files under pyo3/.
        let filtered = repo.filter_by_patterns(&tree, &["pyo3/"])?;
        assert_eq!(filtered.len(), 1, "only the pyo3 dir should remain");
        assert!(filtered.get_name("pyo3").is_some());
        assert!(filtered.get_name("README.md").is_none());

        // The pyo3 subtree itself must retain both entries.
        let pyo3_entry = filtered.get_name("pyo3").unwrap();
        let pyo3_tree = repo.find_tree(pyo3_entry.id())?;
        assert!(pyo3_tree.get_name("Cargo.toml").is_some());
        assert!(pyo3_tree.get_name("src").is_some());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Helpers and tests for filter_by_attributes
    // -----------------------------------------------------------------------

    /// Initializes a non-bare repository so that `.gitattributes` written to
    /// its working directory are picked up by `repo.get_attr(…)`.
    fn setup_attr_test_repo() -> (Repository, PathBuf) {
        let thread_id = std::thread::current().id();
        let temp_path = std::env::temp_dir().join(format!("git-filter-attr-test-{:?}", thread_id));
        let _ = fs::remove_dir_all(&temp_path);
        fs::create_dir_all(&temp_path).unwrap();
        let repo = Repository::init(&temp_path).unwrap();
        (repo, temp_path)
    }

    fn write_gitattributes(repo_path: &Path, content: &str) {
        fs::write(repo_path.join(".gitattributes"), content).unwrap();
    }

    // --- filter_by_attributes: error cases ---------------------------------

    #[test]
    fn test_filter_by_attributes_empty_returns_error() {
        let (repo, temp_path) = setup_attr_test_repo();
        write_gitattributes(&temp_path, "");

        let tree = create_test_tree(&repo).unwrap();
        let result = repo.filter_by_attributes(&tree, &[]);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().message(),
            "at least one attribute is required"
        );

        cleanup_test_repo(temp_path);
    }

    // --- filter_by_attributes: single attribute ----------------------------

    #[test]
    fn test_filter_by_attributes_set_attribute_includes_matching_files() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // Only .txt files carry the export-ignore attribute.
        write_gitattributes(&temp_path, "*.txt export-ignore\n");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("readme.txt", blob, 0o100644)?;
        builder.insert("main.rs", blob, 0o100644)?;
        builder.insert("data.json", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["export-ignore"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("readme.txt").is_some());
        assert!(filtered.get_name("main.rs").is_none());
        assert!(filtered.get_name("data.json").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_explicitly_unset_attribute_excluded() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // .txt gets the attribute; .md explicitly has it unset with `-`.
        write_gitattributes(&temp_path, "*.txt custom-attr\n*.md -custom-attr\n");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("readme.txt", blob, 0o100644)?;
        builder.insert("notes.md", blob, 0o100644)?;
        builder.insert("main.rs", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["custom-attr"])?;
        // .txt is set, .md is explicitly unset, .rs is unspecified
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("readme.txt").is_some());
        assert!(filtered.get_name("notes.md").is_none());
        assert!(filtered.get_name("main.rs").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_no_attributes_set_returns_empty_tree() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // Empty .gitattributes — nothing is attributed.
        write_gitattributes(&temp_path, "");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("file.txt", blob, 0o100644)?;
        builder.insert("file.rs", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["export-ignore"])?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_multiple_attributes_all_required() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // .txt has both attributes; .rs has only one.
        write_gitattributes(&temp_path, "*.txt attr-a attr-b\n*.rs attr-a\n");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("file.txt", blob, 0o100644)?;
        builder.insert("file.rs", blob, 0o100644)?;
        builder.insert("file.md", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        // Both attributes must be present for a file to be included.
        let filtered = repo.filter_by_attributes(&tree, &["attr-a", "attr-b"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("file.txt").is_some());
        assert!(filtered.get_name("file.rs").is_none());
        assert!(filtered.get_name("file.md").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_attribute_with_value() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // linguist-language is set to a string value on .rs files.
        write_gitattributes(&temp_path, "*.rs linguist-language=Rust\n");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("main.rs", blob, 0o100644)?;
        builder.insert("main.py", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        // An attribute with any value (including a string) counts as "set".
        let filtered = repo.filter_by_attributes(&tree, &["linguist-language"])?;
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("main.rs").is_some());
        assert!(filtered.get_name("main.py").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_all_files_match() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // Wildcard rule sets the attribute on every file.
        write_gitattributes(&temp_path, "* generated\n");

        let blob = repo.blob(b"content")?;
        let mut builder = repo.treebuilder(None)?;
        builder.insert("a.txt", blob, 0o100644)?;
        builder.insert("b.rs", blob, 0o100644)?;
        builder.insert("c.md", blob, 0o100644)?;
        let tree = repo.find_tree(builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["generated"])?;
        assert_eq!(filtered.len(), 3);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_nested_tree_filters_recursively() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // Only .proto files carry the attribute.
        write_gitattributes(&temp_path, "*.proto linguist-generated\n");

        let blob = repo.blob(b"content")?;

        // src/api.proto and src/main.rs
        let mut src_builder = repo.treebuilder(None)?;
        src_builder.insert("api.proto", blob, 0o100644)?;
        src_builder.insert("main.rs", blob, 0o100644)?;
        let src_oid = src_builder.write()?;

        let mut root_builder = repo.treebuilder(None)?;
        root_builder.insert("src", src_oid, 0o040000)?;
        root_builder.insert("README.md", blob, 0o100644)?;
        let tree = repo.find_tree(root_builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["linguist-generated"])?;

        // Top-level README.md must be gone; src/ must survive because it has
        // at least one matching descendant.
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("src").is_some());
        assert!(filtered.get_name("README.md").is_none());

        let src_entry = filtered.get_name("src").unwrap();
        let src_tree = repo.find_tree(src_entry.id())?;
        assert_eq!(src_tree.len(), 1);
        assert!(src_tree.get_name("api.proto").is_some());
        assert!(src_tree.get_name("main.rs").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_empty_tree_stays_empty() -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        write_gitattributes(&temp_path, "* export-ignore\n");

        let tree = repo.find_tree(repo.treebuilder(None)?.write()?)?;
        assert_eq!(tree.len(), 0);

        let filtered = repo.filter_by_attributes(&tree, &["export-ignore"])?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_attributes_subdirectory_excluded_when_all_children_unmatched()
    -> Result<(), Error> {
        let (repo, temp_path) = setup_attr_test_repo();
        // Only .txt files match; the `docs/` sub-tree contains only .md files.
        write_gitattributes(&temp_path, "*.txt export-ignore\n");

        let blob = repo.blob(b"content")?;

        let mut docs_builder = repo.treebuilder(None)?;
        docs_builder.insert("guide.md", blob, 0o100644)?;
        docs_builder.insert("api.md", blob, 0o100644)?;
        let docs_oid = docs_builder.write()?;

        let mut root_builder = repo.treebuilder(None)?;
        root_builder.insert("docs", docs_oid, 0o040000)?;
        root_builder.insert("notes.txt", blob, 0o100644)?;
        let tree = repo.find_tree(root_builder.write()?)?;

        let filtered = repo.filter_by_attributes(&tree, &["export-ignore"])?;

        // `docs/` should be pruned entirely because none of its children matched.
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("notes.txt").is_some());
        assert!(filtered.get_name("docs").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_always_false_returns_empty_tree() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();
        let tree = create_test_tree(&repo)?;

        let filtered = repo.filter_by_predicate(&tree, |_repo, _path| false)?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_always_true_returns_full_tree() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();
        let tree = create_test_tree(&repo)?;

        let filtered = repo.filter_by_predicate(&tree, |_repo, _path| true)?;
        assert_eq!(filtered.len(), tree.len());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_matches_on_path() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();
        let tree = create_test_tree(&repo)?;

        // Keep only entries whose path contains "file"
        let filtered = repo.filter_by_predicate(&tree, |_repo, path| {
            path.to_str().is_some_and(|s| s.contains("file"))
        })?;

        assert_eq!(filtered.len(), 2);
        assert!(filtered.get_name("file1.txt").is_some());
        assert!(filtered.get_name("file2.rs").is_some());
        assert!(filtered.get_name("test.md").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_receives_full_nested_path() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let blob = repo.blob(b"content")?;

        let mut sub_builder = repo.treebuilder(None)?;
        sub_builder.insert("deep.rs", blob, 0o100644)?;
        sub_builder.insert("deep.txt", blob, 0o100644)?;
        let sub_oid = sub_builder.write()?;

        let mut root_builder = repo.treebuilder(None)?;
        root_builder.insert("top.rs", blob, 0o100644)?;
        root_builder.insert("src", sub_oid, 0o040000)?;
        let tree = repo.find_tree(root_builder.write()?)?;

        let seen_paths = std::cell::RefCell::new(Vec::new());
        let _ = repo.filter_by_predicate(&tree, |_repo, path| {
            seen_paths
                .borrow_mut()
                .push(path.to_str().unwrap().to_string());
            true
        });
        let seen_paths = seen_paths.into_inner();

        assert!(seen_paths.contains(&"top.rs".to_string()));

        assert!(seen_paths.contains(&"src/deep.rs".to_string()));
        assert!(seen_paths.contains(&"src/deep.txt".to_string()));

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_prunes_subtree_when_no_descendants_match() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let blob = repo.blob(b"content")?;

        let mut sub_builder = repo.treebuilder(None)?;
        sub_builder.insert("a.txt", blob, 0o100644)?;
        sub_builder.insert("b.txt", blob, 0o100644)?;
        let sub_oid = sub_builder.write()?;

        let mut root_builder = repo.treebuilder(None)?;
        root_builder.insert("keep.rs", blob, 0o100644)?;
        root_builder.insert("docs", sub_oid, 0o040000)?;
        let tree = repo.find_tree(root_builder.write()?)?;

        // Only keep .rs files — docs/ subtree should be pruned entirely
        let filtered = repo.filter_by_predicate(&tree, |_repo, path| {
            path.extension().is_some_and(|e| e == "rs")
        })?;

        assert_eq!(filtered.len(), 1);
        assert!(filtered.get_name("keep.rs").is_some());
        assert!(filtered.get_name("docs").is_none());

        cleanup_test_repo(temp_path);
        Ok(())
    }

    #[test]
    fn test_filter_by_predicate_empty_tree_stays_empty() -> Result<(), Error> {
        let (repo, temp_path) = setup_test_repo();

        let tree = repo.find_tree(repo.treebuilder(None)?.write()?)?;
        assert_eq!(tree.len(), 0);

        let filtered = repo.filter_by_predicate(&tree, |_repo, _path| true)?;
        assert_eq!(filtered.len(), 0);

        cleanup_test_repo(temp_path);
        Ok(())
    }
}