Struct git2::Repository

source ·
pub struct Repository { /* private fields */ }
Expand description

An owned git repository, representing all state associated with the underlying filesystem.

This structure corresponds to a git_repository in libgit2. Many other types in git2-rs are derivative from this structure and are attached to its lifetime.

When a repository goes out of scope it is freed in memory but not deleted from the filesystem.

Implementations§

Attempt to open an already-existing repository at path.

The path can point to either a normal or bare repository.

Attempt to open an already-existing bare repository at path.

The path can point to only a bare repository.

Find and open an existing repository, respecting git environment variables. This acts like open_ext with the REPOSITORY_OPEN_FROM_ENV flag, but additionally respects $GIT_DIR. With $GIT_DIR unset, this will search for a repository starting in the current directory.

Find and open an existing repository, with additional options.

If flags contains REPOSITORY_OPEN_NO_SEARCH, the path must point directly to a repository; otherwise, this may point to a subdirectory of a repository, and open_ext will search up through parent directories.

If flags contains REPOSITORY_OPEN_CROSS_FS, the search through parent directories will not cross a filesystem boundary (detected when the stat st_dev field changes).

If flags contains REPOSITORY_OPEN_BARE, force opening the repository as bare even if it isn’t, ignoring any working directory, and defer loading the repository configuration for performance.

If flags contains REPOSITORY_OPEN_NO_DOTGIT, don’t try appending /.git to path.

If flags contains REPOSITORY_OPEN_FROM_ENV, open_ext will ignore other flags and ceiling_dirs, and respect the same environment variables git does. Note, however, that path overrides $GIT_DIR; to respect $GIT_DIR as well, use open_from_env.

ceiling_dirs specifies a list of paths that the search through parent directories will stop before entering. Use the functions in std::env to construct or manipulate such a path list.

Attempt to open an already-existing repository from a worktree.

Attempt to open an already-existing repository at or above path

This starts at path and looks up the filesystem hierarchy until it finds a repository.

Creates a new repository in the specified folder.

This by default will create any necessary directories to create the repository, and it will read any user-specified templates when creating the repository. This behavior can be configured through init_opts.

Creates a new --bare repository in the specified folder.

The folder must exist prior to invoking this function.

Creates a new repository in the specified folder with the given options.

See RepositoryInitOptions struct for more information.

Clone a remote repository.

See the RepoBuilder struct for more information. This function will delegate to a fresh RepoBuilder

Clone a remote repository, initialize and update its submodules recursively.

This is similar to git clone --recursive.

Attempt to wrap an object database as a repository.

Execute a rev-parse operation against the spec listed.

The resulting revision specification is returned, or an error is returned if one occurs.

Find a single object, as specified by a revision string.

Find a single object and intermediate reference by a revision string.

See man gitrevisions, or http://git-scm.com/docs/git-rev-parse.html#_specifying_revisions for information on the syntax accepted.

In some cases (@{<-n>} or <branchname>@{upstream}), the expression may point to an intermediate reference. When such expressions are being passed in, this intermediate reference is returned.

Tests whether this repository is a bare repository or not.

Tests whether this repository is a shallow clone.

Tests whether this repository is a worktree.

Tests whether this repository is empty.

Returns the path to the .git folder for normal repositories or the repository itself for bare repositories.

Returns the current state of this repository

Get the path of the working directory for this repository.

If this repository is bare, then None is returned.

Set the path to the working directory for this repository.

If update_link is true, create/update the gitlink file in the workdir and set config “core.worktree” (if workdir is not the parent of the .git directory).

Get the currently active namespace for this repository.

If there is no namespace, or the namespace is not a valid utf8 string, None is returned.

Get the currently active namespace for this repository as a byte array.

If there is no namespace, None is returned.

Set the active namespace for this repository.

Set the active namespace for this repository as a byte array.

Remove the active namespace for this repository.

Retrieves the Git merge message. Remember to remove the message when finished.

Remove the Git merge message.

List all remotes for a given repository

Get the information for a particular remote

Add a remote with the default fetch refspec to the repository’s configuration.

Add a remote with the provided fetch refspec to the repository’s configuration.

Create an anonymous remote

Create a remote with the given url and refspec in memory. You can use this when you have a URL instead of a remote’s name. Note that anonymous remotes cannot be converted to persisted remotes.

Give a remote a new name

All remote-tracking branches and configuration settings for the remote are updated.

A temporary in-memory remote cannot be given a name with this method.

No loaded instances of the remote with the old name will change their name or their list of refspecs.

The returned array of strings is a list of the non-default refspecs which cannot be renamed and are returned for further processing by the caller.

Delete an existing persisted remote.

All remote-tracking branches and configuration settings for the remote will be removed.

Add a fetch refspec to the remote’s configuration

Add the given refspec to the fetch list in the configuration. No loaded remote instances will be affected.

Add a push refspec to the remote’s configuration.

Add the given refspec to the push list in the configuration. No loaded remote instances will be affected.

Set the remote’s url in the configuration

Remote objects already in memory will not be affected. This assumes the common case of a single-url remote and will otherwise return an error.

Set the remote’s url for pushing in the configuration.

Remote objects already in memory will not be affected. This assumes the common case of a single-url remote and will otherwise return an error.

None indicates that it should be cleared.

Sets the current head to the specified object and optionally resets the index and working tree to match.

A soft reset means the head will be moved to the commit.

A mixed reset will trigger a soft reset, plus the index will be replaced with the content of the commit tree.

A hard reset will trigger a mixed reset and the working directory will be replaced with the content of the index. (Untracked and ignored files will be left alone, however.)

The target is a commit-ish to which the head should be moved to. The object can either be a commit or a tag, but tags must be dereferenceable to a commit.

The checkout options will only be used for a hard reset.

Updates some entries in the index from the target commit tree.

The scope of the updated entries is determined by the paths being in the iterator provided.

Passing a None target will result in removing entries in the index matching the provided pathspecs.

Retrieve and resolve the reference pointed at by HEAD.

Make the repository HEAD point to the specified reference.

If the provided reference points to a tree or a blob, the HEAD is unaltered and an error is returned.

If the provided reference points to a branch, the HEAD will point to that branch, staying attached, or become attached if it isn’t yet. If the branch doesn’t exist yet, no error will be returned. The HEAD will then be attached to an unborn branch.

Otherwise, the HEAD will be detached and will directly point to the commit.

Determines whether the repository HEAD is detached.

Make the repository HEAD directly point to the commit.

If the provided commitish cannot be found in the repository, the HEAD is unaltered and an error is returned.

If the provided commitish cannot be peeled into a commit, the HEAD is unaltered and an error is returned.

Otherwise, the HEAD will eventually be detached and will directly point to the peeled commit.

Make the repository HEAD directly point to the commit.

If the provided commitish cannot be found in the repository, the HEAD is unaltered and an error is returned. If the provided commitish cannot be peeled into a commit, the HEAD is unaltered and an error is returned. Otherwise, the HEAD will eventually be detached and will directly point to the peeled commit.

Create an iterator for the repo’s references

Create an iterator for the repo’s references that match the specified glob

Load all submodules for this repository and return them.

Gather file status information and populate the returned structure.

Note that if a pathspec is given in the options to filter the status, then the results from rename detection (if you enable it) may not be accurate. To do rename detection properly, this must be called with no pathspec so that all files can be considered.

Test if the ignore rules apply to a given file.

This function checks the ignore rules to see if they would apply to the given file. This indicates if the file would be ignored regardless of whether the file is already in the index or committed to the repository.

One way to think of this is if you were to do “git add .” on the directory containing the file, would it be added or not?

Get file status for a single file.

This tries to get status for the filename that you give. If no files match that name (in either the HEAD, index, or working directory), this returns NotFound.

If the name matches multiple files (for example, if the path names a directory or if running on a case- insensitive filesystem and yet the HEAD has two entries that both match the path), then this returns Ambiguous because it cannot give correct results.

This does not do any sort of rename detection. Renames require a set of targets and because of the path filtering, there is not enough information to check renames correctly. To check file status with rename detection, there is no choice but to do a full statuses and scan through looking for the path that you are interested in.

Create an iterator which loops over the requested branches.

Get the Index file for this repository.

If a custom index has not been set, the default index for the repository will be returned (the one located in .git/index).

Set the Index file for this repository.

Get the configuration file for this repository.

If a configuration file has not been set, the default config set for the repository will be returned, including global and system configurations (if they are available).

Get the value of a git attribute for a path as a string.

This function will return a special string if the attribute is set to a special value. Interpreting the special string is discouraged. You should always use AttrValue::from_string to interpret the return value and avoid the special string.

As such, the return type of this function will probably be changed in the next major version to prevent interpreting the returned string without checking whether it’s special.

Get the value of a git attribute for a path as a byte slice.

This function will return a special byte slice if the attribute is set to a special value. Interpreting the special byte slice is discouraged. You should always use AttrValue::from_bytes to interpret the return value and avoid the special string.

As such, the return type of this function will probably be changed in the next major version to prevent interpreting the returned byte slice without checking whether it’s special.

Write an in-memory buffer to the ODB as a blob.

The Oid returned can in turn be passed to find_blob to get a handle to the blob.

Read a file from the filesystem and write its content to the Object Database as a loose blob

The Oid returned can in turn be passed to find_blob to get a handle to the blob.

Create a stream to write blob

This function may need to buffer the data on disk and will in general not be the right choice if you know the size of the data to write.

Use BlobWriter::commit() to commit the write to the object db and get the object id.

If the hintpath parameter is filled, it will be used to determine what git filters should be applied to the object before it is written to the object database.

Lookup a reference to one of the objects in a repository.

Get the object database for this repository

Override the object database for this repository

Create a new branch pointing at a target commit

A new direct reference will be created pointing to this target commit. If force is true and a reference already exists with the given name, it’ll be replaced.

Create a new branch pointing at a target commit

This behaves like Repository::branch() but takes an annotated commit, which lets you specify which extended sha syntax string was specified by a user, allowing for more exact reflog messages.

See the documentation for Repository::branch()

Lookup a branch by its name in a repository.

Create new commit in the repository

If the update_ref is not None, name of the reference that will be updated to point to this commit. If the reference is not direct, it will be resolved to a direct reference. Use “HEAD” to update the HEAD of the current branch and make it point to this commit. If the reference doesn’t exist yet, it will be created. If it does exist, the first parent must be the tip of this branch.

Create a commit object and return that as a Buf.

That can be converted to a string like this str::from_utf8(&buf).unwrap().to_string(). And that string can be passed to the commit_signed function, the arguments behave the same as in the commit function.

Create a commit object from the given buffer and signature

Given the unsigned commit object’s contents, its signature and the header field in which to store the signature, attach the signature to the commit and write it into the given repository.

Use None in signature_field to use the default of gpgsig, which is almost certainly what you want.

Returns the resulting (signed) commit id.

Extract the signature from a commit

Returns a tuple containing the signature in the first value and the signed data in the second.

Lookup a reference to one of the commits in a repository.

Creates an AnnotatedCommit from the given commit id.

Lookup a reference to one of the objects in a repository.

Create a new direct reference.

This function will return an error if a reference already exists with the given name unless force is true, in which case it will be overwritten.

Conditionally create new direct reference.

A direct reference (also called an object id reference) refers directly to a specific object id (a.k.a. OID or SHA) in the repository. The id permanently refers to the object (although the reference itself can be moved). For example, in libgit2 the direct ref “refs/tags/v0.17.0” refers to OID 5b9fac39d8a76b9139667c26a63e6b3f204b3977.

The direct reference will be created in the repository and written to the disk.

Valid reference names must follow one of two patterns:

  1. Top-level names must contain only capital letters and underscores, and must begin and end with a letter. (e.g. “HEAD”, “ORIG_HEAD”).
  2. Names prefixed with “refs/” can be almost anything. You must avoid the characters ~, ^, :, \\, ?, [, and *, and the sequences “..” and “@{” which have special meaning to revparse.

This function will return an error if a reference already exists with the given name unless force is true, in which case it will be overwritten.

The message for the reflog will be ignored if the reference does not belong in the standard set (HEAD, branches and remote-tracking branches) and it does not have a reflog.

It will return GIT_EMODIFIED if the reference’s value at the time of updating does not match the one passed through current_id (i.e. if the ref has changed since the user read it).

Create a new symbolic reference.

This function will return an error if a reference already exists with the given name unless force is true, in which case it will be overwritten.

Create a new symbolic reference.

This function will return an error if a reference already exists with the given name unless force is true, in which case it will be overwritten.

It will return GIT_EMODIFIED if the reference’s value at the time of updating does not match the one passed through current_value (i.e. if the ref has changed since the user read it).

Lookup a reference to one of the objects in a repository.

Lookup a reference to one of the objects in a repository. Repository::find_reference with teeth; give the method your reference in human-readable format e.g. ‘main’ instead of ‘refs/heads/main’, and it will do-what-you-mean, returning the Reference.

Lookup a reference by name and resolve immediately to OID.

This function provides a quick way to resolve a reference name straight through to the object id that it refers to. This avoids having to allocate or free any Reference objects for simple situations.

Creates a git_annotated_commit from the given reference.

Creates a git_annotated_commit from FETCH_HEAD.

Create a new action signature with default user and now timestamp.

This looks up the user.name and user.email from the configuration and uses the current time as the timestamp, and creates a new signature based on that information. It will return NotFound if either the user.name or user.email are not set.

Set up a new git submodule for checkout.

This does “git submodule add” up to the fetch and checkout of the submodule contents. It preps a new submodule, creates an entry in .gitmodules and creates an empty initialized repository either at the given path in the working directory or in .git/modules with a gitlink from the working directory to the new repo.

To fully emulate “git submodule add” call this function, then open() the submodule repo and perform the clone step as needed. Lastly, call add_finalize() to wrap up adding the new submodule and .gitmodules to the index to be ready to commit.

Lookup submodule information by name or path.

Given either the submodule name or path (they are usually the same), this returns a structure describing the submodule.

Get the status for a submodule.

This looks at a submodule and tries to determine the status. It will return a combination of the SubmoduleStatus values.

Set the ignore rule for the submodule in the configuration

This does not affect any currently-loaded instances.

Set the update rule for the submodule in the configuration

This setting won’t affect any existing instances.

Set the URL for the submodule in the configuration

After calling this, you may wish to call Submodule::sync to write the changes to the checked out submodule repository.

Set the branch for the submodule in the configuration

After calling this, you may wish to call Submodule::sync to write the changes to the checked out submodule repository.

Lookup a reference to one of the objects in a repository.

Create a new TreeBuilder, optionally initialized with the entries of the given Tree.

The tree builder can be used to create or modify trees in memory and write them as tree objects to the database.

Create a new tag in the repository from an object

A new reference will also be created pointing to this tag object. If force is true and a reference already exists with the given name, it’ll be replaced.

The message will not be cleaned up.

The tag name will be checked for validity. You must avoid the characters ‘~’, ‘^’, ‘:’, ’ \ ’, ‘?’, ‘[’, and ‘*’, and the sequences “..” and “ @ {“ which have special meaning to revparse.

Create a new tag in the repository from an object without creating a reference.

The message will not be cleaned up.

The tag name will be checked for validity. You must avoid the characters ‘~’, ‘^’, ‘:’, ’ \ ’, ‘?’, ‘[’, and ‘*’, and the sequences “..” and “ @ {“ which have special meaning to revparse.

Create a new lightweight tag pointing at a target object

A new direct reference will be created pointing to this target object. If force is true and a reference already exists with the given name, it’ll be replaced.

Lookup a tag object from the repository.

Delete an existing tag reference.

The tag name will be checked for validity, see tag for some rules about valid names.

Get a list with all the tags in the repository.

An optional fnmatch pattern can also be specified.

iterate over all tags calling cb on each. the callback is provided the tag id and name

Updates files in the index and the working tree to match the content of the commit pointed at by HEAD.

Updates files in the working tree to match the content of the index.

If the index is None, the repository’s index will be used.

Updates files in the index and working tree to match the content of the tree pointed at by the treeish.

Merges the given commit(s) into HEAD, writing the results into the working directory. Any changes are staged for commit and any conflicts are written to the index. Callers should inspect the repository’s index after this completes, resolve any conflicts and prepare a commit.

For compatibility with git, the repository is put into a merging state. Once the commit is done (or if the user wishes to abort), you should clear this state by calling cleanup_state().

Merge two commits, producing an index that reflects the result of the merge. The index may be written as-is to the working directory or checked out. If the index is to be converted to a tree, the caller should resolve any conflicts that arose as part of the merge.

Merge two trees, producing an index that reflects the result of the merge. The index may be written as-is to the working directory or checked out. If the index is to be converted to a tree, the caller should resolve any conflicts that arose as part of the merge.

Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc. For example: MERGE_HEAD, MERGE_MSG, etc.

Analyzes the given branch(es) and determines the opportunities for merging them into the HEAD of the repository.

Analyzes the given branch(es) and determines the opportunities for merging them into a reference.

Initializes a rebase operation to rebase the changes in branch relative to upstream onto another branch. To begin the rebase process, call next().

Opens an existing rebase that was previously started by either an invocation of rebase() or by another client.

Add a note for an object

The notes_ref argument is the canonical name of the reference to use, defaulting to “refs/notes/commits”. If force is specified then previous notes are overwritten.

Get the default notes reference for this repository

Creates a new iterator for notes in this repository.

The notes_ref argument is the canonical name of the reference to use, defaulting to “refs/notes/commits”.

The iterator returned yields pairs of (Oid, Oid) where the first element is the id of the note and the second id is the id the note is annotating.

Read the note for an object.

The notes_ref argument is the canonical name of the reference to use, defaulting to “refs/notes/commits”.

The id specified is the Oid of the git object to read the note from.

Remove the note for an object.

The notes_ref argument is the canonical name of the reference to use, defaulting to “refs/notes/commits”.

The id specified is the Oid of the git object to remove the note from.

Create a revwalk that can be used to traverse the commit graph.

Get the blame for a single file.

Find a merge base between two commits

Find a merge base given a list of commits

Find all merge bases between two commits

Find all merge bases given a list of commits

Count the number of unique commits between two commit objects

There is no need for branches containing the commits to have any upstream relationship, but it helps to think of one as a branch and the other as its upstream, the ahead and behind values will be what git would report for the branches.

Determine if a commit is the descendant of another commit

Read the reflog for the given reference

If there is no reflog file for the given reference yet, an empty reflog object will be returned.

Delete the reflog for the given reference

Rename a reflog

The reflog to be renamed is expected to already exist.

Check if the given reference has a reflog.

Ensure that the given reference has a reflog.

Describes a commit

Performs a describe operation on the current commit and the worktree. After performing a describe on HEAD, a status is run and description is considered to be dirty if there are.

Directly run a diff on two blobs.

Compared to a file, a blob lacks some contextual information. As such, the DiffFile given to the callback will have some fake data; i.e. mode will be 0 and path will be None.

None is allowed for either old_blob or new_blob and will be treated as an empty blob, with the oid set to zero in the DiffFile. Passing None for both blobs is a noop; no callbacks will be made at all.

We do run a binary content check on the blob content and if either blob looks like binary data, the DiffFile binary attribute will be set to 1 and no call to the hunk_cb nor line_cb will be made (unless you set the force_text option).

Create a diff with the difference between two tree objects.

This is equivalent to git diff <old-tree> <new-tree>

The first tree will be used for the “old_file” side of the delta and the second tree will be used for the “new_file” side of the delta. You can pass None to indicate an empty tree, although it is an error to pass None for both the old_tree and new_tree.

Create a diff between a tree and repository index.

This is equivalent to git diff --cached <treeish> or if you pass the HEAD tree, then like git diff --cached.

The tree you pass will be used for the “old_file” side of the delta, and the index will be used for the “new_file” side of the delta.

If you pass None for the index, then the existing index of the repo will be used. In this case, the index will be refreshed from disk (if it has changed) before the diff is generated.

If the tree is None, then it is considered an empty tree.

Create a diff between two index objects.

The first index will be used for the “old_file” side of the delta, and the second index will be used for the “new_file” side of the delta.

Create a diff between the repository index and the workdir directory.

This matches the git diff command. See the note below on tree_to_workdir for a discussion of the difference between git diff and git diff HEAD and how to emulate a git diff <treeish> using libgit2.

The index will be used for the “old_file” side of the delta, and the working directory will be used for the “new_file” side of the delta.

If you pass None for the index, then the existing index of the repo will be used. In this case, the index will be refreshed from disk (if it has changed) before the diff is generated.

Create a diff between a tree and the working directory.

The tree you provide will be used for the “old_file” side of the delta, and the working directory will be used for the “new_file” side.

This is not the same as git diff <treeish> or git diff-index <treeish>. Those commands use information from the index, whereas this function strictly returns the differences between the tree and the files in the working directory, regardless of the state of the index. Use tree_to_workdir_with_index to emulate those commands.

To see difference between this and tree_to_workdir_with_index, consider the example of a staged file deletion where the file has then been put back into the working dir and further modified. The tree-to-workdir diff for that file is ‘modified’, but git diff would show status ‘deleted’ since there is a staged delete.

If None is passed for tree, then an empty tree is used.

Create a diff between a tree and the working directory using index data to account for staged deletes, tracked files, etc.

This emulates git diff <tree> by diffing the tree to the index and the index to the working directory and blending the results into a single diff that includes staged deleted, etc.

Create a PackBuilder

Save the local modifications to a new stash.

Save the local modifications to a new stash. unlike stash_save it allows to pass a null message

Apply a single stashed state from the stash list.

Loop over all the stashed states and issue a callback for each one.

Return true to continue iterating or false to stop.

Remove a single stashed state from the stash list.

Apply a single stashed state from the stash list and remove it from the list if successful.

Add ignore rules for a repository.

The format of the rules is the same one of the .gitignore file.

Clear ignore rules that were explicitly added.

Test if the ignore rules apply to a given path.

Perform a cherrypick

Create an index of uncommitted changes, representing the result of cherry-picking.

Find the remote name of a remote-tracking branch

Retrieves the name of the reference supporting the remote tracking branch, given the name of a local branch reference.

Retrieve the name of the upstream remote of a local branch.

Apply a Diff to the given repo, making changes directly in the working directory, the index, or both.

Apply a Diff to the provided tree, and return the resulting Index.

Reverts the given commit, producing changes in the index and working directory.

Reverts the given commit against the given “our” commit, producing an index that reflects the result of the revert.

Lists all the worktrees for the repository

Opens a worktree by name for the given repository

This can open any worktree that the worktrees method returns.

Creates a new worktree for the repository

Create a new transaction

Gets this repository’s mailmap.

If a merge is in progress, invoke ‘callback’ for each commit ID in the MERGE_HEAD file.

Invoke ‘callback’ for each entry in the given FETCH_HEAD file.

callback will be called with with following arguments:

  • &str: the reference name
  • &[u8]: the remote url
  • &Oid: the reference target OID
  • bool: was the reference the result of a merge

Trait Implementations§

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.