Skip to main content

Crate git_filter_tree

Crate git_filter_tree 

Source
Expand description

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 porcelain.

§Filter by Pattern

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());

A trailing / is expanded to dir/**, so "src/" keeps all files under src/. Multiple patterns are OR-ed together.

§Filter by Attributes

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());

All listed attributes must be set (AND semantics). Entries with an attribute explicitly unset (-export) or unspecified are excluded.

§Filter by Predicate

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());

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.

Modules§

exe

Structs§

Error
A structure to represent errors coming out of libgit2.
Repository
An owned git repository, representing all state associated with the underlying filesystem.

Traits§

FilterTree