Repository

Struct Repository 

Source
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

Source

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

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

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

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

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

Source

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 .git directory itself
§Arguments
  • path - Path to the repository root or .git directory.
§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();
Source

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

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::AlreadyARepository if a .git directory already exists at the path.
  • Error::Io if 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());
Source

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::AlreadyARepository if a Git repository already exists at the path.
  • Error::Io if 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());
Source

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

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

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);
}
Source

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

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::InvalidOid if the prefix is too short or contains invalid characters.
  • Error::ObjectNotFound if no object matches the prefix.
  • Error::InvalidOid if 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();
Source

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::ObjectNotFound if the object does not exist.
  • Error::TypeMismatch if 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());
Source

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::ObjectNotFound if the object does not exist.
  • Error::TypeMismatch if 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());
}
Source

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::ObjectNotFound if the object does not exist.
  • Error::TypeMismatch if 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());
Source

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::ObjectNotFound if 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()),
}
Source

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::RefNotFound if 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());
}
Source

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::RefNotFound if 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),
    }
}
Source

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) {
    // ...
}
Source

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

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()),
    }
}
Source

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::PathNotFound if the file does not exist.
§Examples
use zerogit::repository::Repository;

let repo = Repository::open("path/to/repo").unwrap();
repo.add("src/main.rs").unwrap();
Source

pub fn add_all(&self) -> Result<()>

Adds all modified and untracked files to the staging area.

This is equivalent to git add -A.

§Returns

Ok(()) on success.

§Examples
use zerogit::repository::Repository;

let repo = Repository::open("path/to/repo").unwrap();
repo.add_all().unwrap();
Source

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. If None, 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();
Source

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:

  1. Builds a tree from the current index
  2. Creates a commit object with the tree and parent
  3. 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::EmptyCommit if 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();
Source

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 (without refs/heads/ prefix).
  • target - The commit OID to point to. If None, uses current HEAD.
§Returns

The created Branch on success.

§Errors
  • Error::InvalidRefName if the branch name is invalid.
  • Error::RefAlreadyExists if a branch with this name already exists.
  • Error::RefNotFound if 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();
Source

pub fn delete_branch(&self, name: &str) -> Result<()>

Deletes a branch.

§Arguments
  • name - The name of the branch to delete (without refs/heads/ prefix).
§Returns

Ok(()) on success.

§Errors
  • Error::RefNotFound if the branch does not exist.
  • Error::CannotDeleteCurrentBranch if 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();
Source

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::RefNotFound if the target cannot be resolved.
  • Error::DirtyWorkingTree if 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();
Source

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

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

pub fn tags(&self) -> Result<Vec<Tag>>

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

Trait Implementations§

Source§

impl Debug for Repository

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.