pub struct Repository { /* private fields */ }Expand description
A Git repository.
This is the main entry point for interacting with a Git repository. It provides access to objects, references, and the index.
Implementations§
Source§impl Repository
impl Repository
Sourcepub fn diff_trees(
&self,
old_tree: Option<&Tree>,
new_tree: &Tree,
) -> Result<TreeDiff>
pub fn diff_trees( &self, old_tree: Option<&Tree>, new_tree: &Tree, ) -> Result<TreeDiff>
Computes the diff between two trees.
§Arguments
old_tree- The old tree (None for initial commits).new_tree- The new tree.
§Returns
A TreeDiff containing all the changes between the two trees.
§Examples
use zerogit::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let old_tree = repo.tree("abc1234").unwrap();
let new_tree = repo.tree("def5678").unwrap();
let diff = repo.diff_trees(Some(&old_tree), &new_tree).unwrap();
for delta in diff.deltas() {
println!("{} {}", delta.status_char(), delta.path().display());
}Sourcepub fn commit_diff(&self, commit: &Commit) -> Result<TreeDiff>
pub fn commit_diff(&self, commit: &Commit) -> Result<TreeDiff>
Computes the diff for a commit against its first parent.
For root commits (no parent), all files are shown as Added. For merge commits (multiple parents), only the diff against the first parent is returned.
§Arguments
commit- The commit to compute the diff for.
§Returns
A TreeDiff containing all the changes in this commit.
§Examples
use zerogit::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let commit = repo.commit("abc1234").unwrap();
let diff = repo.commit_diff(&commit).unwrap();
for delta in diff.deltas() {
println!("{} {}", delta.status_char(), delta.path().display());
}Sourcepub fn diff_index_to_workdir(&self) -> Result<TreeDiff>
pub fn diff_index_to_workdir(&self) -> Result<TreeDiff>
Computes the diff between the index and the working tree.
This is equivalent to git diff (without arguments), showing unstaged changes.
§Returns
A TreeDiff containing all changes between the index and working tree.
§Examples
use zerogit::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let diff = repo.diff_index_to_workdir().unwrap();
println!("Unstaged changes:");
for delta in diff.deltas() {
println!(" {} {}", delta.status_char(), delta.path().display());
}Sourcepub fn diff_head_to_index(&self) -> Result<TreeDiff>
pub fn diff_head_to_index(&self) -> Result<TreeDiff>
Computes the diff between HEAD and the index.
This is equivalent to git diff --staged or git diff --cached,
showing staged changes.
§Returns
A TreeDiff containing all changes between HEAD and the index.
§Examples
use zerogit::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let diff = repo.diff_head_to_index().unwrap();
println!("Staged changes:");
for delta in diff.deltas() {
println!(" {} {}", delta.status_char(), delta.path().display());
}Sourcepub fn diff_head_to_workdir(&self) -> Result<TreeDiff>
pub fn diff_head_to_workdir(&self) -> Result<TreeDiff>
Computes the diff between HEAD and the working tree.
This is equivalent to git diff HEAD, showing all changes
(both staged and unstaged) since the last commit.
§Returns
A TreeDiff containing all changes between HEAD and the working tree.
§Examples
use zerogit::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let diff = repo.diff_head_to_workdir().unwrap();
println!("All changes from HEAD:");
for delta in diff.deltas() {
println!(" {} {}", delta.status_char(), delta.path().display());
}Source§impl Repository
impl Repository
Sourcepub fn open<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self>
Opens an existing Git repository.
The path can point to either:
- The repository root (containing
.git/) - The
.gitdirectory itself
§Arguments
path- Path to the repository root or.gitdirectory.
§Returns
A Repository instance, or an error if the path is not a valid Git repository.
§Examples
use zerogit::repository::Repository;
// Open by repository root
let repo = Repository::open("path/to/repo").unwrap();
// Open by .git directory
let repo = Repository::open("path/to/repo/.git").unwrap();Sourcepub fn discover<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn discover<P: AsRef<Path>>(path: P) -> Result<Self>
Discovers a Git repository by searching upward from the given path.
Starting from path, this function walks up the directory tree
looking for a .git directory until it finds one or reaches the
filesystem root.
§Arguments
path- Path to start searching from.
§Returns
A Repository instance, or an error if no repository is found.
§Examples
use zerogit::repository::Repository;
// Discover repository from a subdirectory
let repo = Repository::discover("path/to/repo/src/lib").unwrap();Sourcepub fn init<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn init<P: AsRef<Path>>(path: P) -> Result<Self>
Initializes a new Git repository at the given path.
Creates a new repository with the standard .git directory structure,
including the necessary subdirectories and files for a functional Git repository.
§Arguments
path- Path where the repository should be created.
§Returns
A Repository instance pointing to the newly created repository.
§Errors
Error::AlreadyARepositoryif a.gitdirectory already exists at the path.Error::Ioif directory or file creation fails.
§Examples
use zerogit::repository::Repository;
let repo = Repository::init("path/to/new/repo").unwrap();
println!("Created repository at: {}", repo.path().display());Sourcepub fn init_bare<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn init_bare<P: AsRef<Path>>(path: P) -> Result<Self>
Initializes a new bare Git repository at the given path.
Creates a bare repository (without a working directory) at the specified path.
Bare repositories are typically used as remote repositories and contain
the Git database directly in the specified directory rather than in a .git subdirectory.
§Arguments
path- Path where the bare repository should be created.
§Returns
A Repository instance pointing to the newly created bare repository.
§Errors
Error::AlreadyARepositoryif a Git repository already exists at the path.Error::Ioif directory or file creation fails.
§Examples
use zerogit::repository::Repository;
let repo = Repository::init_bare("path/to/bare.git").unwrap();
println!("Created bare repository at: {}", repo.path().display());Sourcepub fn path(&self) -> &Path
pub fn path(&self) -> &Path
Returns the path to the repository root (working directory).
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
println!("Repository root: {}", repo.path().display());Sourcepub fn git_dir(&self) -> &Path
pub fn git_dir(&self) -> &Path
Returns the path to the .git directory.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
println!(".git directory: {}", repo.git_dir().display());Sourcepub fn config(&self) -> Result<Config>
pub fn config(&self) -> Result<Config>
Returns the repository configuration.
This loads configuration from all levels (system, global, local) with proper precedence (local overrides global, global overrides system).
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let config = repo.config().unwrap();
if let Some(name) = config.get("user", "name") {
println!("User: {}", name);
}Sourcepub fn config_local(&self) -> Result<Config>
pub fn config_local(&self) -> Result<Config>
Returns only the repository-local configuration.
This loads only the .git/config file, ignoring global and system configs.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let config = repo.config_local().unwrap();Sourcepub fn resolve_short_oid(&self, short_oid: &str) -> Result<Oid>
pub fn resolve_short_oid(&self, short_oid: &str) -> Result<Oid>
Resolves a short (abbreviated) OID to a full OID.
§Arguments
short_oid- A hexadecimal string of at least 4 characters.
§Returns
The full OID if exactly one object matches the prefix.
§Errors
Error::InvalidOidif the prefix is too short or contains invalid characters.Error::ObjectNotFoundif no object matches the prefix.Error::InvalidOidif multiple objects match the prefix (ambiguous).
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let full_oid = repo.resolve_short_oid("abc1234").unwrap();Sourcepub fn commit(&self, oid_str: &str) -> Result<Commit>
pub fn commit(&self, oid_str: &str) -> Result<Commit>
Retrieves a commit by its OID.
§Arguments
oid_str- The full or abbreviated OID as a hexadecimal string.
§Returns
The commit object on success.
§Errors
Error::ObjectNotFoundif the object does not exist.Error::TypeMismatchif the object is not a commit.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let commit = repo.commit("abc1234").unwrap();
println!("Author: {}", commit.author().name());Sourcepub fn tree(&self, oid_str: &str) -> Result<Tree>
pub fn tree(&self, oid_str: &str) -> Result<Tree>
Retrieves a tree by its OID.
§Arguments
oid_str- The full or abbreviated OID as a hexadecimal string.
§Returns
The tree object on success.
§Errors
Error::ObjectNotFoundif the object does not exist.Error::TypeMismatchif the object is not a tree.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let tree = repo.tree("abc1234").unwrap();
for entry in tree.iter() {
println!("{}: {}", entry.mode().as_octal(), entry.name());
}Sourcepub fn blob(&self, oid_str: &str) -> Result<Blob>
pub fn blob(&self, oid_str: &str) -> Result<Blob>
Retrieves a blob by its OID.
§Arguments
oid_str- The full or abbreviated OID as a hexadecimal string.
§Returns
The blob object on success.
§Errors
Error::ObjectNotFoundif the object does not exist.Error::TypeMismatchif the object is not a blob.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let blob = repo.blob("abc1234").unwrap();
println!("Size: {} bytes", blob.size());Sourcepub fn object(&self, oid_str: &str) -> Result<Object>
pub fn object(&self, oid_str: &str) -> Result<Object>
Retrieves a Git object by its OID.
This method returns the object as a unified Object enum,
which can be any of blob, tree, or commit.
§Arguments
oid_str- The full or abbreviated OID as a hexadecimal string.
§Returns
The object on success.
§Errors
Error::ObjectNotFoundif the object does not exist.
§Examples
use zerogit::repository::Repository;
use zerogit::objects::Object;
let repo = Repository::open("path/to/repo").unwrap();
let obj = repo.object("abc1234").unwrap();
match obj {
Object::Blob(blob) => println!("Blob: {} bytes", blob.size()),
Object::Tree(tree) => println!("Tree: {} entries", tree.len()),
Object::Commit(commit) => println!("Commit: {}", commit.summary()),
}Sourcepub fn head(&self) -> Result<Head>
pub fn head(&self) -> Result<Head>
Returns the current HEAD state.
§Returns
A Head enum representing the current HEAD state (branch or detached).
§Errors
Error::RefNotFoundif HEAD doesn’t exist or points to an unborn branch.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
let head = repo.head().unwrap();
if head.is_detached() {
println!("HEAD is detached at {}", head.oid().short());
} else {
println!("On branch {}", head.branch_name().unwrap());
}Sourcepub fn log(&self) -> Result<LogIterator>
pub fn log(&self) -> Result<LogIterator>
Returns an iterator over the commit history starting from HEAD.
Commits are returned in reverse chronological order (newest first).
§Returns
A LogIterator that yields commits.
§Errors
Error::RefNotFoundif HEAD doesn’t exist.- Other errors if the initial commit cannot be read.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
for result in repo.log().unwrap().take(10) {
match result {
Ok(commit) => println!("{}: {}", commit.author().name(), commit.summary()),
Err(e) => eprintln!("Error: {}", e),
}
}Sourcepub fn log_from(&self, start_oid: Oid) -> Result<LogIterator>
pub fn log_from(&self, start_oid: Oid) -> Result<LogIterator>
Returns an iterator over the commit history starting from a specific commit.
Commits are returned in reverse chronological order (newest first).
§Arguments
start_oid- The OID of the commit to start from.
§Returns
A LogIterator that yields commits.
§Examples
use zerogit::repository::Repository;
use zerogit::objects::Oid;
let repo = Repository::open("path/to/repo").unwrap();
let oid = Oid::from_hex("abc1234567890abcdef1234567890abcdef12345").unwrap();
for commit in repo.log_from(oid).unwrap().take(5) {
// ...
}Sourcepub fn log_with_options(&self, options: LogOptions) -> Result<LogIterator>
pub fn log_with_options(&self, options: LogOptions) -> Result<LogIterator>
Returns an iterator over the commit history with filtering options.
This allows filtering commits by path, date, author, and more.
§Arguments
options- The filtering options to apply.
§Returns
A LogIterator that yields only commits matching the filter criteria.
§Examples
use zerogit::repository::Repository;
use zerogit::log::LogOptions;
let repo = Repository::open("path/to/repo").unwrap();
// Get last 10 commits that modified src/
let log = repo.log_with_options(
LogOptions::new()
.path("src/")
.max_count(10)
).unwrap();
for commit in log {
println!("{}", commit.unwrap().summary());
}Sourcepub fn status(&self) -> Result<Vec<StatusEntry>>
pub fn status(&self) -> Result<Vec<StatusEntry>>
Returns the status of the working tree.
This compares HEAD, the index, and the working tree to detect:
- Untracked files (new files not in Git)
- Modified files (changed since last staged)
- Deleted files (removed from working tree)
- Staged changes (added/modified/deleted in index)
§Returns
A vector of StatusEntry representing all files with changes.
§Examples
use zerogit::repository::Repository;
use zerogit::status::FileStatus;
let repo = Repository::open("path/to/repo").unwrap();
for entry in repo.status().unwrap() {
match entry.status() {
FileStatus::Untracked => println!("?? {}", entry.path().display()),
FileStatus::Modified => println!(" M {}", entry.path().display()),
FileStatus::Deleted => println!(" D {}", entry.path().display()),
FileStatus::Added => println!("A {}", entry.path().display()),
FileStatus::StagedModified => println!("M {}", entry.path().display()),
FileStatus::StagedDeleted => println!("D {}", entry.path().display()),
}
}Sourcepub fn add<P: AsRef<Path>>(&self, path: P) -> Result<()>
pub fn add<P: AsRef<Path>>(&self, path: P) -> Result<()>
Adds a file to the staging area (index).
This reads the file from the working tree, creates a blob object, and updates the index with the file’s information.
§Arguments
path- The path to the file, relative to the repository root.
§Returns
Ok(()) on success.
§Errors
Error::PathNotFoundif the file does not exist.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
repo.add("src/main.rs").unwrap();Sourcepub fn reset<P: AsRef<Path>>(&self, path: Option<P>) -> Result<()>
pub fn reset<P: AsRef<Path>>(&self, path: Option<P>) -> Result<()>
Resets the staging area to match HEAD.
This removes all staged changes, reverting the index to the state of the current HEAD commit.
§Arguments
paths- Optional list of paths to reset. IfNone, resets all staged changes.
§Returns
Ok(()) on success.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
// Reset all staged changes
repo.reset(None::<&str>).unwrap();
// Reset specific file
repo.reset(Some("src/main.rs")).unwrap();Sourcepub fn create_commit(
&self,
message: &str,
author_name: &str,
author_email: &str,
) -> Result<Oid>
pub fn create_commit( &self, message: &str, author_name: &str, author_email: &str, ) -> Result<Oid>
Creates a new commit from the staged changes.
This function:
- Builds a tree from the current index
- Creates a commit object with the tree and parent
- Updates HEAD to point to the new commit
§Arguments
message- The commit message.author_name- The author’s name.author_email- The author’s email.
§Returns
The OID of the new commit.
§Errors
Error::EmptyCommitif there are no staged changes.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
repo.add("file.txt").unwrap();
let commit_oid = repo.create_commit(
"Add file.txt",
"John Doe",
"john@example.com"
).unwrap();Sourcepub fn create_branch(&self, name: &str, target: Option<Oid>) -> Result<Branch>
pub fn create_branch(&self, name: &str, target: Option<Oid>) -> Result<Branch>
Creates a new branch pointing to the specified commit.
§Arguments
name- The name of the branch to create (withoutrefs/heads/prefix).target- The commit OID to point to. IfNone, uses current HEAD.
§Returns
The created Branch on success.
§Errors
Error::InvalidRefNameif the branch name is invalid.Error::RefAlreadyExistsif a branch with this name already exists.Error::RefNotFoundif HEAD cannot be resolved (when target is None).
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
// Create a branch at current HEAD
let branch = repo.create_branch("feature/new-feature", None).unwrap();
// Create a branch at a specific commit
use zerogit::objects::Oid;
let oid = Oid::from_hex("abc1234567890abcdef1234567890abcdef12345").unwrap();
let branch = repo.create_branch("hotfix", Some(oid)).unwrap();Sourcepub fn delete_branch(&self, name: &str) -> Result<()>
pub fn delete_branch(&self, name: &str) -> Result<()>
Deletes a branch.
§Arguments
name- The name of the branch to delete (withoutrefs/heads/prefix).
§Returns
Ok(()) on success.
§Errors
Error::RefNotFoundif the branch does not exist.Error::CannotDeleteCurrentBranchif trying to delete the current branch.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
repo.delete_branch("feature/old-feature").unwrap();Sourcepub fn checkout(&self, target: &str) -> Result<()>
pub fn checkout(&self, target: &str) -> Result<()>
Checks out a branch or commit.
This updates the working tree to match the target and updates HEAD.
§Arguments
target- The branch name or commit OID to checkout.
§Returns
Ok(()) on success.
§Errors
Error::RefNotFoundif the target cannot be resolved.Error::DirtyWorkingTreeif there are uncommitted changes.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
// Checkout a branch
repo.checkout("feature/new-feature").unwrap();
// Checkout a specific commit (detached HEAD)
repo.checkout("abc1234").unwrap();Sourcepub fn branches(&self) -> Result<Vec<Branch>>
pub fn branches(&self) -> Result<Vec<Branch>>
Lists all local branches in the repository.
Returns a vector of Branch objects representing all branches
in refs/heads/. The current branch (if any) is marked with
is_current() == true.
§Returns
A vector of branches, sorted by name.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
for branch in repo.branches().unwrap() {
let marker = if branch.is_current() { "* " } else { " " };
println!("{}{}", marker, branch.name());
}Sourcepub fn remote_branches(&self) -> Result<Vec<RemoteBranch>>
pub fn remote_branches(&self) -> Result<Vec<RemoteBranch>>
Lists all remote-tracking branches in the repository.
Returns a vector of RemoteBranch objects representing all branches
in refs/remotes/.
§Returns
A vector of remote branches, sorted by full name (remote/branch).
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
for rb in repo.remote_branches().unwrap() {
println!("{}/{}", rb.remote(), rb.name());
}Lists all tags in the repository.
Returns a vector of Tag objects representing all tags in refs/tags/.
For annotated tags, the message and tagger information are included.
§Returns
A vector of tags, sorted by name.
§Examples
use zerogit::repository::Repository;
let repo = Repository::open("path/to/repo").unwrap();
for tag in repo.tags().unwrap() {
println!("{} -> {}", tag.name(), tag.target().short());
if let Some(message) = tag.message() {
println!(" {}", message);
}
}