The LibGit2 module provides bindings tolibgit2, a portable C library that implements core functionality for theGit version control system. These bindings are currently used to power Julia's package manager. It is expected that this module will eventually be moved into a separate package.
Some of this documentation assumes some prior knowledge of the libgit2 API. For more information on some of the objects and methods referenced here, consult the upstreamlibgit2 API reference.
LibGit2.Buffer
—TypeLibGit2.Buffer
A data buffer for exporting data from libgit2. Matches thegit_buf
struct.
When fetching data from LibGit2, a typical usage would look like:
buf_ref = Ref(Buffer())@check ccall(..., (Ptr{Buffer},), buf_ref)# operation on buf_reffree(buf_ref)
In particular, note thatLibGit2.free
should be called afterward on theRef
object.
LibGit2.CheckoutOptions
—TypeLibGit2.CheckoutOptions
Matches thegit_checkout_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.checkout_strategy
: determine how to handle conflicts and whether to force the checkout/recreate missing files.disable_filters
: if nonzero, do not apply filters like CLRF (to convert file newlines between UNIX and DOS).dir_mode
: read/write/access mode for any directories involved in the checkout. Default is0755
.file_mode
: read/write/access mode for any files involved in the checkout. Default is0755
or0644
, depending on the blob.file_open_flags
: bitflags used to open any files during the checkout.notify_flags
: Flags for what sort of conflicts the user should be notified about.notify_cb
: An optional callback function to notify the user if a checkout conflict occurs. If this function returns a non-zero value, the checkout will be cancelled.notify_payload
: Payload for the notify callback function.progress_cb
: An optional callback function to display checkout progress.progress_payload
: Payload for the progress callback.paths
: If not empty, describes which paths to search during the checkout. If empty, the checkout will occur over all files in the repository.baseline
: Expected content of theworkdir
, captured in a (pointer to a)GitTree
. Defaults to the state of the tree at HEAD.baseline_index
: Expected content of theworkdir
, captured in a (pointer to a)GitIndex
. Defaults to the state of the index at HEAD.target_directory
: If not empty, checkout to this directory instead of theworkdir
.ancestor_label
: In case of conflicts, the name of the common ancestor side.our_label
: In case of conflicts, the name of "our" side.their_label
: In case of conflicts, the name of "their" side.perfdata_cb
: An optional callback function to display performance data.perfdata_payload
: Payload for the performance callback.LibGit2.CloneOptions
—TypeLibGit2.CloneOptions
Matches thegit_clone_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.checkout_opts
: The options for performing the checkout of the remote as part of the clone.fetch_opts
: The options for performing the pre-checkout fetch of the remote as part of the clone.bare
: If0
, clone the full remote repository. If non-zero, perform a bare clone, in which there is no local copy of the source files in the repository and thegitdir
andworkdir
are the same.localclone
: Flag whether to clone a local object database or do a fetch. The default is to let git decide. It will not use the git-aware transport for a local clone, but will use it for URLs which begin withfile://
.checkout_branch
: The name of the branch to checkout. If an empty string, the default branch of the remote will be checked out.repository_cb
: An optional callback which will be used to create thenew repository into which the clone is made.repository_cb_payload
: The payload for the repository callback.remote_cb
: An optional callback used to create theGitRemote
before making the clone from it.remote_cb_payload
: The payload for the remote callback.LibGit2.DescribeOptions
—TypeLibGit2.DescribeOptions
Matches thegit_describe_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.max_candidates_tags
: consider this many most recent tags inrefs/tags
to describe a commit. Defaults to 10 (so that the 10 most recent tags would be examined to see if they describe a commit).describe_strategy
: whether to consider all entries inrefs/tags
(equivalent togit-describe --tags
) or all entries inrefs/
(equivalent togit-describe --all
). The default is to only show annotated tags. IfConsts.DESCRIBE_TAGS
is passed, all tags, annotated or not, will be considered. IfConsts.DESCRIBE_ALL
is passed, any ref inrefs/
will be considered.pattern
: only consider tags which matchpattern
. Supports glob expansion.only_follow_first_parent
: when finding the distance from a matching reference to the described object, only consider the distance from the first parent.show_commit_oid_as_fallback
: if no matching reference can be found which describes a commit, show the commit'sGitHash
instead of throwing an error (the default behavior).LibGit2.DescribeFormatOptions
—TypeLibGit2.DescribeFormatOptions
Matches thegit_describe_format_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.abbreviated_size
: lower bound on the size of the abbreviatedGitHash
to use, defaulting to7
.always_use_long_format
: set to1
to use the long format for strings even if a short format can be used.dirty_suffix
: if set, this will be appended to the end of the description string if theworkdir
is dirty.LibGit2.DiffDelta
—TypeLibGit2.DiffDelta
Description of changes to one entry. Matches thegit_diff_delta
struct.
The fields represent:
status
: One ofConsts.DELTA_STATUS
, indicating whether the file has been added/modified/deleted.flags
: Flags for the delta and the objects on each side. Determines whether to treat the file(s) as binary/text, whether they exist on each side of the diff, and whether the object ids are known to be correct.similarity
: Used to indicate if a file has been renamed or copied.nfiles
: The number of files in the delta (for instance, if the delta was run on a submodule commit id, it may contain more than one file).old_file
: ADiffFile
containing information about the file(s) before the changes.new_file
: ADiffFile
containing information about the file(s) after the changes.LibGit2.DiffFile
—TypeLibGit2.DiffFile
Description of one side of a delta. Matches thegit_diff_file
struct.
The fields represent:
id
: theGitHash
of the item in the diff. If the item is empty on this side of the diff (for instance, if the diff is of the removal of a file), this will beGitHash(0)
.path
: aNULL
terminated path to the item relative to the working directory of the repository.size
: the size of the item in bytes.flags
: a combination of thegit_diff_flag_t
flags. Thei
th bit of this integer sets thei
th flag.mode
: thestat
mode for the item.id_abbrev
: only present in LibGit2 versions newer than or equal to0.25.0
. The length of theid
field when converted usingstring
. Usually equal toOID_HEXSZ
(40).LibGit2.DiffOptionsStruct
—TypeLibGit2.DiffOptionsStruct
Matches thegit_diff_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.flags
: flags controlling which files will appear in the diff. Defaults toDIFF_NORMAL
.ignore_submodules
: whether to look at files in submodules or not. Defaults toSUBMODULE_IGNORE_UNSPECIFIED
, which means the submodule's configuration will control whether it appears in the diff or not.pathspec
: path to files to include in the diff. Default is to use all files in the repository.notify_cb
: optional callback which will notify the user of changes to the diff as file deltas are added to it.progress_cb
: optional callback which will display diff progress. Only relevant on libgit2 versions at least as new as 0.24.0.payload
: the payload to pass tonotify_cb
andprogress_cb
.context_lines
: the number ofunchanged lines used to define the edges of a hunk. This is also the number of lines which will be shown before/after a hunk to provide context. Default is 3.interhunk_lines
: the maximum number ofunchanged linesbetween two separate hunks allowed before the hunks will be combined. Default is 0.id_abbrev
: sets the length of the abbreviatedGitHash
to print. Default is7
.max_size
: the maximum file size of a blob. Above this size, it will be treated as a binary blob. The default is 512 MB.old_prefix
: the virtual file directory in which to place old files on one side of the diff. Default is"a"
.new_prefix
: the virtual file directory in which to place new files on one side of the diff. Default is"b"
.LibGit2.FetchHead
—TypeLibGit2.FetchHead
Contains the information about HEAD during a fetch, including the name and URL of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD has been merged locally.
The fields represent:
name
: The name in the local reference database of the fetch head, for example,"refs/heads/master"
.url
: The URL of the fetch head.oid
: TheGitHash
of the tip of the fetch head.ismerge
: Boolean flag indicating whether the changes at the remote have been merged into the local copy yet or not. Iftrue
, the local copy is up to date with the remote fetch head.LibGit2.FetchOptions
—TypeLibGit2.FetchOptions
Matches thegit_fetch_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.callbacks
: remote callbacks to use during the fetch.prune
: whether to perform a prune after the fetch or not. The default is to use the setting from theGitConfig
.update_fetchhead
: whether to update theFetchHead
after the fetch. The default is to perform the update, which is the normal git behavior.download_tags
: whether to download tags present at the remote or not. The default is to request the tags for objects which are being downloaded anyway from the server.proxy_opts
: options for connecting to the remote through a proxy. SeeProxyOptions
. Only present on libgit2 versions newer than or equal to 0.25.0.custom_headers
: any extra headers needed for the fetch. Only present on libgit2 versions newer than or equal to 0.24.0.LibGit2.GitAnnotated
—TypeGitAnnotated(repo::GitRepo, commit_id::GitHash)GitAnnotated(repo::GitRepo, ref::GitReference)GitAnnotated(repo::GitRepo, fh::FetchHead)GitAnnotated(repo::GitRepo, committish::AbstractString)
An annotated git commit carries with it information about how it was looked up and why, so that rebase or merge operations have more information about the context of the commit. Conflict files contain information about the source/target branches in the merge which are conflicting, for instance. An annotated commit can refer to the tip of a remote branch, for instance when aFetchHead
is passed, or to a branch head described usingGitReference
.
LibGit2.GitBlame
—TypeGitBlame(repo::GitRepo, path::AbstractString; options::BlameOptions=BlameOptions())
Construct aGitBlame
object for the file atpath
, using change information gleaned from the history ofrepo
. TheGitBlame
object records who changed which chunks of the file when, and how.options
controls how to separate the contents of the file and which commits to probe - seeBlameOptions
for more information.
LibGit2.GitBlob
—TypeGitBlob(repo::GitRepo, hash::AbstractGitHash)GitBlob(repo::GitRepo, spec::AbstractString)
Return aGitBlob
object fromrepo
specified byhash
/spec
.
hash
is a full (GitHash
) or partial (GitShortHash
) hash.spec
is a textual specification: seethe git docs for a full list.LibGit2.GitCommit
—TypeGitCommit(repo::GitRepo, hash::AbstractGitHash)GitCommit(repo::GitRepo, spec::AbstractString)
Return aGitCommit
object fromrepo
specified byhash
/spec
.
hash
is a full (GitHash
) or partial (GitShortHash
) hash.spec
is a textual specification: seethe git docs for a full list.LibGit2.GitConfig
—TypeGitConfig(path::AbstractString, level::Consts.GIT_CONFIG=Consts.CONFIG_LEVEL_APP, force::Bool=false)
Create a newGitConfig
by loading configuration information from the file atpath
. Seeaddfile
for more information about thelevel
,repo
andforce
options.
GitConfig(repo::GitRepo)
Get the stored configuration for the git repositoryrepo
. Ifrepo
does not have a specific configuration file set, the default git configuration will be used.
GitConfig(level::Consts.GIT_CONFIG=Consts.CONFIG_LEVEL_DEFAULT)
Get the default git configuration by loading the global and system configuration files into a prioritized configuration. This can be used to access default configuration options outside a specific git repository.
LibGit2.GitHash
—TypeGitHash
A git object identifier, based on the sha-1 hash. It is a 20 byte string (40 hex digits) used to identify aGitObject
in a repository.
LibGit2.GitObject
—TypeGitObject(repo::GitRepo, hash::AbstractGitHash)GitObject(repo::GitRepo, spec::AbstractString)
Return the specified object (GitCommit
,GitBlob
,GitTree
orGitTag
) fromrepo
specified byhash
/spec
.
hash
is a full (GitHash
) or partial (GitShortHash
) hash.spec
is a textual specification: seethe git docs for a full list.LibGit2.GitRemote
—TypeGitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) -> GitRemote
Look up a remote git repository using its name and URL. Uses the default fetch refspec.
Examples
repo = LibGit2.init(repo_path)remote = LibGit2.GitRemote(repo, "upstream", repo_url)
GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) -> GitRemote
Look up a remote git repository using the repository's name and URL, as well as specifications for how to fetch from the remote (e.g. which remote branch to fetch from).
Examples
repo = LibGit2.init(repo_path)refspec = "+refs/heads/mybranch:refs/remotes/origin/mybranch"remote = LibGit2.GitRemote(repo, "upstream", repo_url, refspec)
LibGit2.GitRemoteAnon
—FunctionGitRemoteAnon(repo::GitRepo, url::AbstractString) -> GitRemote
Look up a remote git repository using only its URL, not its name.
Examples
repo = LibGit2.init(repo_path)remote = LibGit2.GitRemoteAnon(repo, repo_url)
LibGit2.GitRepo
—TypeLibGit2.GitRepo(path::AbstractString)
Open a git repository atpath
.
LibGit2.GitRepoExt
—FunctionLibGit2.GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT))
Open a git repository atpath
with extended controls (for instance, if the current user must be a member of a special access group to readpath
).
LibGit2.GitRevWalker
—TypeGitRevWalker(repo::GitRepo)
AGitRevWalker
walks through therevisions (i.e. commits) of a git repositoryrepo
. It is a collection of the commits in the repository, and supports iteration and calls toLibGit2.map
andLibGit2.count
(for instance,LibGit2.count
could be used to determine what percentage of commits in a repository were made by a certain author).
cnt = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker LibGit2.count((oid,repo)->(oid == commit_oid1), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME)end
Here,LibGit2.count
finds the number of commits along the walk with a certainGitHash
. Since theGitHash
is unique to a commit,cnt
will be1
.
LibGit2.GitShortHash
—TypeGitShortHash(hash::GitHash, len::Integer)
A shortened git object identifier, which can be used to identify a git object when it is unique, consisting of the initiallen
hexadecimal digits ofhash
(the remaining digits are ignored).
LibGit2.GitSignature
—TypeLibGit2.GitSignature
This is a Julia wrapper around a pointer to agit_signature
object.
LibGit2.GitStatus
—TypeLibGit2.GitStatus(repo::GitRepo; status_opts=StatusOptions())
Collect information about the status of each file in the git repositoryrepo
(e.g. is the file modified, staged, etc.).status_opts
can be used to set various options, for instance whether or not to look at untracked files or whether to include submodules or not. SeeStatusOptions
for more information.
LibGit2.GitTag
—TypeGitTag(repo::GitRepo, hash::AbstractGitHash)GitTag(repo::GitRepo, spec::AbstractString)
Return aGitTag
object fromrepo
specified byhash
/spec
.
hash
is a full (GitHash
) or partial (GitShortHash
) hash.spec
is a textual specification: seethe git docs for a full list.LibGit2.GitTree
—TypeGitTree(repo::GitRepo, hash::AbstractGitHash)GitTree(repo::GitRepo, spec::AbstractString)
Return aGitTree
object fromrepo
specified byhash
/spec
.
hash
is a full (GitHash
) or partial (GitShortHash
) hash.spec
is a textual specification: seethe git docs for a full list.LibGit2.IndexEntry
—TypeLibGit2.IndexEntry
In-memory representation of a file entry in the index. Matches thegit_index_entry
struct.
LibGit2.IndexTime
—TypeLibGit2.IndexTime
Matches thegit_index_time
struct.
LibGit2.BlameOptions
—TypeLibGit2.BlameOptions
Matches thegit_blame_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.flags
: one ofConsts.BLAME_NORMAL
orConsts.BLAME_FIRST_PARENT
(the other blame flags are not yet implemented by libgit2).min_match_characters
: the minimum number ofalphanumeric characters which much change in a commit in order for the change to be associated with that commit. The default is 20. Only takes effect if one of theConsts.BLAME_*_COPIES
flags are used, which libgit2 does not implement yet.newest_commit
: theGitHash
of the newest commit from which to look at changes.oldest_commit
: theGitHash
of the oldest commit from which to look at changes.min_line
: the first line of the file from which to starting blaming. The default is1
.max_line
: the last line of the file to which to blame. The default is0
, meaning the last line of the file.LibGit2.MergeOptions
—TypeLibGit2.MergeOptions
Matches thegit_merge_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.flags
: anenum
for flags describing merge behavior. Defined ingit_merge_flag_t
. The corresponding Julia enum isGIT_MERGE
and has values:MERGE_FIND_RENAMES
: detect if a file has been renamed between the common ancestor and the "ours" or "theirs" side of the merge. Allows merges where a file has been renamed.MERGE_FAIL_ON_CONFLICT
: exit immediately if a conflict is found rather than trying to resolve it.MERGE_SKIP_REUC
: do not write the REUC extension on the index resulting from the merge.MERGE_NO_RECURSIVE
: if the commits being merged have multiple merge bases, use the first one, rather than trying to recursively merge the bases.rename_threshold
: how similar two files must to consider one a rename of the other. This is an integer that sets the percentage similarity. The default is 50.target_limit
: the maximum number of files to compare with to look for renames. The default is 200.metric
: optional custom function to use to determine the similarity between two files for rename detection.recursion_limit
: the upper limit on the number of merges of common ancestors to perform to try to build a new virtual merge base for the merge. The default is no limit. This field is only present on libgit2 versions newer than 0.24.0.default_driver
: the merge driver to use if both sides have changed. This field is only present on libgit2 versions newer than 0.25.0.file_favor
: how to handle conflicting file contents for thetext
driver.MERGE_FILE_FAVOR_NORMAL
: if both sides of the merge have changes to a section, make a note of the conflict in the index whichgit checkout
will use to create a merge file, which the user can then reference to resolve the conflicts. This is the default.MERGE_FILE_FAVOR_OURS
: if both sides of the merge have changes to a section, use the version in the "ours" side of the merge in the index.MERGE_FILE_FAVOR_THEIRS
: if both sides of the merge have changes to a section, use the version in the "theirs" side of the merge in the index.MERGE_FILE_FAVOR_UNION
: if both sides of the merge have changes to a section, include each unique line from both sides in the file which is put into the index.file_flags
: guidelines for merging files.LibGit2.ProxyOptions
—TypeLibGit2.ProxyOptions
Options for connecting through a proxy.
Matches thegit_proxy_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.proxytype
: anenum
for the type of proxy to use. Defined ingit_proxy_t
. The corresponding Julia enum isGIT_PROXY
and has values:PROXY_NONE
: do not attempt the connection through a proxy.PROXY_AUTO
: attempt to figure out the proxy configuration from the git configuration.PROXY_SPECIFIED
: connect using the URL given in theurl
field of this struct.url
: the URL of the proxy.credential_cb
: a pointer to a callback function which will be called if the remote requires authentication to connect.certificate_cb
: a pointer to a callback function which will be called if certificate verification fails. This lets the user decide whether or not to keep connecting. If the function returns1
, connecting will be allowed. If it returns0
, the connection will not be allowed. A negative value can be used to return errors.payload
: the payload to be provided to the two callback functions.Examples
julia> fo = LibGit2.FetchOptions( proxy_opts = LibGit2.ProxyOptions(url = Cstring("https://my_proxy_url.com")))julia> fetch(remote, "master", options=fo)
LibGit2.PushOptions
—TypeLibGit2.PushOptions
Matches thegit_push_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.parallelism
: if a pack file must be created, this variable sets the number of worker threads which will be spawned by the packbuilder. If0
, the packbuilder will auto-set the number of threads to use. The default is1
.callbacks
: the callbacks (e.g. for authentication with the remote) to use for the push.proxy_opts
: only relevant if the LibGit2 version is greater than or equal to0.25.0
. Sets options for using a proxy to communicate with a remote. SeeProxyOptions
for more information.custom_headers
: only relevant if the LibGit2 version is greater than or equal to0.24.0
. Extra headers needed for the push operation.LibGit2.RebaseOperation
—TypeLibGit2.RebaseOperation
Describes a single instruction/operation to be performed during the rebase. Matches thegit_rebase_operation
struct.
The fields represent:
optype
: the type of rebase operation currently being performed. The options are:REBASE_OPERATION_PICK
: cherry-pick the commit in question.REBASE_OPERATION_REWORD
: cherry-pick the commit in question, but rewrite its message using the prompt.REBASE_OPERATION_EDIT
: cherry-pick the commit in question, but allow the user to edit the commit's contents and its message.REBASE_OPERATION_SQUASH
: squash the commit in question into the previous commit. The commit messages of the two commits will be merged.REBASE_OPERATION_FIXUP
: squash the commit in question into the previous commit. Only the commit message of the previous commit will be used.REBASE_OPERATION_EXEC
: do not cherry-pick a commit. Run a command and continue if the command exits successfully.id
: theGitHash
of the commit being worked on during this rebase step.exec
: in caseREBASE_OPERATION_EXEC
is used, the command to run during this step (for instance, running the test suite after each commit).LibGit2.RebaseOptions
—TypeLibGit2.RebaseOptions
Matches thegit_rebase_options
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.quiet
: inform other git clients helping with/working on the rebase that the rebase should be done "quietly". Used for interoperability. The default is1
.inmemory
: start an in-memory rebase. Callers working on the rebase can go through its steps and commit any changes, but cannot rewind HEAD or update the repository. Theworkdir
will not be modified. Only present on libgit2 versions newer than or equal to 0.24.0.rewrite_notes_ref
: name of the reference to notes to use to rewrite the commit notes as the rebase is finished.merge_opts
: merge options controlling how the trees will be merged at each rebase step. Only present on libgit2 versions newer than or equal to 0.24.0.checkout_opts
: checkout options for writing files when initializing the rebase, stepping through it, and aborting it. SeeCheckoutOptions
for more information.LibGit2.RemoteCallbacks
—TypeLibGit2.RemoteCallbacks
Callback settings. Matches thegit_remote_callbacks
struct.
LibGit2.SignatureStruct
—TypeLibGit2.SignatureStruct
An action signature (e.g. for committers, taggers, etc). Matches thegit_signature
struct.
The fields represent:
name
: The full name of the committer or author of the commit.email
: The email at which the committer/author can be contacted.when
: aTimeStruct
indicating when the commit was authored/committed into the repository.LibGit2.StatusEntry
—TypeLibGit2.StatusEntry
Providing the differences between the file as it exists in HEAD and the index, and providing the differences between the index and the working directory. Matches thegit_status_entry
struct.
The fields represent:
status
: contains the status flags for the file, indicating if it is current, or has been changed in some way in the index or work tree.head_to_index
: a pointer to aDiffDelta
which encapsulates the difference(s) between the file as it exists in HEAD and in the index.index_to_workdir
: a pointer to aDiffDelta
which encapsulates the difference(s) between the file as it exists in the index and in theworkdir
.LibGit2.StatusOptions
—TypeLibGit2.StatusOptions
Options to control howgit_status_foreach_ext()
will issue callbacks. Matches thegit_status_opt_t
struct.
The fields represent:
version
: version of the struct in use, in case this changes later. For now, always1
.show
: a flag for which files to examine and in which order. The default isConsts.STATUS_SHOW_INDEX_AND_WORKDIR
.flags
: flags for controlling any callbacks used in a status call.pathspec
: an array of paths to use for path-matching. The behavior of the path-matching will vary depending on the values ofshow
andflags
.baseline
is the tree to be used for comparison to the working directory and index; defaults to HEAD.LibGit2.StrArrayStruct
—TypeLibGit2.StrArrayStruct
A LibGit2 representation of an array of strings. Matches thegit_strarray
struct.
When fetching data from LibGit2, a typical usage would look like:
sa_ref = Ref(StrArrayStruct())@check ccall(..., (Ptr{StrArrayStruct},), sa_ref)res = convert(Vector{String}, sa_ref[])free(sa_ref)
In particular, note thatLibGit2.free
should be called afterward on theRef
object.
Conversely, when passing a vector of strings to LibGit2, it is generally simplest to rely on implicit conversion:
strs = String[...]@check ccall(..., (Ptr{StrArrayStruct},), strs)
Note that no call tofree
is required as the data is allocated by Julia.
LibGit2.TimeStruct
—TypeLibGit2.TimeStruct
Time in a signature. Matches thegit_time
struct.
LibGit2.addfile
—Functionaddfile(cfg::GitConfig, path::AbstractString, level::Consts.GIT_CONFIG=Consts.CONFIG_LEVEL_APP, repo::Union{GitRepo, Nothing} = nothing, force::Bool=false)
Add an existing git configuration file located atpath
to the currentGitConfig
cfg
. If the file does not exist, it will be created.
level
sets the git configuration priority level and is determined byrepo
is an optional repository to allow parsing of conditional includes.force
isfalse
and a configuration for the given priority level already exists,addfile
will error. Ifforce
istrue
, the existing configuration will be replaced by the one in the file atpath
.
LibGit2.add!
—Functionadd!(repo::GitRepo, files::AbstractString...; flags::Cuint = Consts.INDEX_ADD_DEFAULT)add!(idx::GitIndex, files::AbstractString...; flags::Cuint = Consts.INDEX_ADD_DEFAULT)
Add all the files with paths specified byfiles
to the indexidx
(or the index of therepo
). If the file already exists, the index entry will be updated. If the file does not exist already, it will be newly added into the index.files
may contain glob patterns which will be expanded and any matching files will be added (unlessINDEX_ADD_DISABLE_PATHSPEC_MATCH
is set, see below). If a file has been ignored (in.gitignore
or in the config), itwill not be added,unless it is already being tracked in the index, in which case itwill be updated. The keyword argumentflags
is a set of bit-flags which control the behavior with respect to ignored files:
Consts.INDEX_ADD_DEFAULT
- default, described above.Consts.INDEX_ADD_FORCE
- disregard the existing ignore rules and force addition of the file to the index even if it is already ignored.Consts.INDEX_ADD_CHECK_PATHSPEC
- cannot be used at the same time asINDEX_ADD_FORCE
. Check that each file infiles
which exists on disk is not in the ignore list. If one of the filesis ignored, the function will returnEINVALIDSPEC
.Consts.INDEX_ADD_DISABLE_PATHSPEC_MATCH
- turn off glob matching, and only add files to the index which exactly match the paths specified infiles
.LibGit2.add_fetch!
—Functionadd_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String)
Add afetch refspec for the specifiedrmt
. This refspec will contain information about which branch(es) to fetch from.
Examples
julia> LibGit2.add_fetch!(repo, remote, "upstream");julia> LibGit2.fetch_refspecs(remote)String["+refs/heads/*:refs/remotes/upstream/*"]
LibGit2.add_push!
—Functionadd_push!(repo::GitRepo, rmt::GitRemote, push_spec::String)
Add apush refspec for the specifiedrmt
. This refspec will contain information about which branch(es) to push to.
Examples
julia> LibGit2.add_push!(repo, remote, "refs/heads/master");julia> remote = LibGit2.get(LibGit2.GitRemote, repo, branch);julia> LibGit2.push_refspecs(remote)String["refs/heads/master"]
LibGit2.addblob!
—FunctionLibGit2.addblob!(repo::GitRepo, path::AbstractString)
Read the file atpath
and adds it to the object database ofrepo
as a loose blob. Return theGitHash
of the resulting blob.
Examples
hash_str = string(commit_oid)blob_file = joinpath(repo_path, ".git", "objects", hash_str[1:2], hash_str[3:end])id = LibGit2.addblob!(repo, blob_file)
LibGit2.author
—Functionauthor(c::GitCommit)
Return theSignature
of the author of the commitc
. The author is the person who made changes to the relevant file(s). See alsocommitter
.
LibGit2.authors
—Functionauthors(repo::GitRepo) -> Vector{Signature}
Return all authors of commits to therepo
repository.
Examples
repo = LibGit2.GitRepo(repo_path)repo_file = open(joinpath(repo_path, test_file), "a")println(repo_file, commit_msg)flush(repo_file)LibGit2.add!(repo, test_file)sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0)commit_oid1 = LibGit2.commit(repo, "commit1"; author=sig, committer=sig)println(repo_file, randstring(10))flush(repo_file)LibGit2.add!(repo, test_file)commit_oid2 = LibGit2.commit(repo, "commit2"; author=sig, committer=sig)# will be a Vector of [sig, sig]auths = LibGit2.authors(repo)
LibGit2.branch
—Functionbranch(repo::GitRepo)
Equivalent togit branch
. Create a new branch from the current HEAD.
LibGit2.branch!
—Functionbranch!(repo::GitRepo, branch_name::AbstractString, commit::AbstractString=""; kwargs...)
Checkout a new git branch in therepo
repository.commit
is theGitHash
, in string form, which will be the start of the new branch. Ifcommit
is an empty string, the current HEAD will be used.
The keyword arguments are:
track::AbstractString=""
: the name of the remote branch this new branch should track, if any. If empty (the default), no remote branch will be tracked.force::Bool=false
: iftrue
, branch creation will be forced.set_head::Bool=true
: iftrue
, after the branch creation finishes the branch head will be set as the HEAD ofrepo
.Equivalent togit checkout [-b|-B] <branch_name> [<commit>] [--track <track>]
.
Examples
repo = LibGit2.GitRepo(repo_path)LibGit2.branch!(repo, "new_branch", set_head=false)
LibGit2.checkout!
—Functioncheckout!(repo::GitRepo, commit::AbstractString=""; force::Bool=true)
Equivalent togit checkout [-f] --detach <commit>
. Checkout the git commitcommit
(aGitHash
in string form) inrepo
. Ifforce
istrue
, force the checkout and discard any current changes. Note that this detaches the current HEAD.
Examples
repo = LibGit2.GitRepo(repo_path)open(joinpath(LibGit2.path(repo), "file1"), "w") do f write(f, "111")endLibGit2.add!(repo, "file1")commit_oid = LibGit2.commit(repo, "add file1")open(joinpath(LibGit2.path(repo), "file1"), "w") do f write(f, "112")end# would fail without the force=true# since there are modifications to the fileLibGit2.checkout!(repo, string(commit_oid), force=true)
LibGit2.clone
—Functionclone(repo_url::AbstractString, repo_path::AbstractString, clone_opts::CloneOptions)
Clone the remote repository atrepo_url
(which can be a remote URL or a path on the local filesystem) torepo_path
(which must be a path on the local filesystem). Options for the clone, such as whether to perform a bare clone or not, are set byCloneOptions
.
Examples
repo_url = "https://github.com/JuliaLang/Example.jl"repo = LibGit2.clone(repo_url, "/home/me/projects/Example")
clone(repo_url::AbstractString, repo_path::AbstractString; kwargs...)
Clone a remote repository located atrepo_url
to the local filesystem locationrepo_path
.
The keyword arguments are:
branch::AbstractString=""
: which branch of the remote to clone, if not the default repository branch (usuallymaster
).isbare::Bool=false
: iftrue
, clone the remote as a bare repository, which will makerepo_path
itself the git directory instead ofrepo_path/.git
. This means that a working tree cannot be checked out. Plays the role of the git CLI argument--bare
.remote_cb::Ptr{Cvoid}=C_NULL
: a callback which will be used to create the remote before it is cloned. IfC_NULL
(the default), no attempt will be made to create the remote - it will be assumed to already exist.credentials::Creds=nothing
: provides credentials and/or settings when authenticating against a private repository.callbacks::Callbacks=Callbacks()
: user provided callbacks and payloads.Equivalent togit clone [-b <branch>] [--bare] <repo_url> <repo_path>
.
Examples
repo_url = "https://github.com/JuliaLang/Example.jl"repo1 = LibGit2.clone(repo_url, "test_path")repo2 = LibGit2.clone(repo_url, "test_path", isbare=true)julia_url = "https://github.com/JuliaLang/julia"julia_repo = LibGit2.clone(julia_url, "julia_path", branch="release-0.6")
LibGit2.commit
—Functioncommit(repo::GitRepo, msg::AbstractString; kwargs...) -> GitHash
Wrapper aroundgit_commit_create
. Create a commit in the repositoryrepo
.msg
is the commit message. Return the OID of the new commit.
The keyword arguments are:
refname::AbstractString=Consts.HEAD_FILE
: if not NULL, the name of the reference to update to point to the new commit. For example,"HEAD"
will update the HEAD of the current branch. If the reference does not yet exist, it will be created.author::Signature = Signature(repo)
is aSignature
containing information about the person who authored the commit.committer::Signature = Signature(repo)
is aSignature
containing information about the person who committed the commit to the repository. Not necessarily the same asauthor
, for instance ifauthor
emailed a patch tocommitter
who committed it.tree_id::GitHash = GitHash()
is a git tree to use to create the commit, showing its ancestry and relationship with any other history.tree
must belong torepo
.parent_ids::Vector{GitHash}=GitHash[]
is a list of commits byGitHash
to use as parent commits for the new one, and may be empty. A commit might have multiple parents if it is a merge commit, for example.LibGit2.commit(rb::GitRebase, sig::GitSignature)
Commit the current patch to the rebaserb
, usingsig
as the committer. Is silent if the commit has already been applied.
LibGit2.committer
—Functioncommitter(c::GitCommit)
Return theSignature
of the committer of the commitc
. The committer is the person who committed the changes originally authored by theauthor
, but need not be the same as theauthor
, for example, if theauthor
emailed a patch to acommitter
who committed it.
LibGit2.count
—FunctionLibGit2.count(f::Function, walker::GitRevWalker; oid::GitHash=GitHash(), by::Cint=Consts.SORT_NONE, rev::Bool=false)
Using theGitRevWalker
walker
to "walk" over every commit in the repository's history, find the number of commits which returntrue
whenf
is applied to them. The keyword arguments are: *oid
: TheGitHash
of the commit to begin the walk from. The default is to usepush_head!
and therefore the HEAD commit and all its ancestors. *by
: The sorting method. The default is not to sort. Other options are to sort by topology (LibGit2.Consts.SORT_TOPOLOGICAL
), to sort forwards in time (LibGit2.Consts.SORT_TIME
, most ancient first) or to sort backwards in time (LibGit2.Consts.SORT_REVERSE
, most recent first). *rev
: Whether to reverse the sorted order (for instance, if topological sorting is used).
Examples
cnt = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker LibGit2.count((oid, repo)->(oid == commit_oid1), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME)end
LibGit2.count
finds the number of commits along the walk with a certainGitHash
commit_oid1
, starting the walk from that commit and moving forwards in time from it. Since theGitHash
is unique to a commit,cnt
will be1
.
LibGit2.counthunks
—Functioncounthunks(blame::GitBlame)
Return the number of distinct "hunks" with a file. A hunk may contain multiple lines. A hunk is usually a piece of a file that was added/changed/removed together, for example, a function added to a source file or an inner loop that was optimized out of that function later.
LibGit2.create_branch
—FunctionLibGit2.create_branch(repo::GitRepo, bname::AbstractString, commit_obj::GitCommit; force::Bool=false)
Create a new branch in the repositoryrepo
with namebname
, which points to commitcommit_obj
(which has to be part ofrepo
). Ifforce
istrue
, overwrite an existing branch namedbname
if it exists. Ifforce
isfalse
and a branch already exists namedbname
, this function will throw an error.
LibGit2.credentials_callback
—Functioncredential_callback(...) -> Cint
A LibGit2 credential callback function which provides different credential acquisition functionality w.r.t. a connection protocol. Thepayload_ptr
is required to contain aLibGit2.CredentialPayload
object which will keep track of state and settings.
Theallowed_types
contains a bitmask ofLibGit2.Consts.GIT_CREDTYPE
values specifying which authentication methods should be attempted.
Credential authentication is done in the following order (if supported):
If a user is presented with a credential prompt they can abort the prompt by typing^D
(pressing the control key together with thed
key).
Note: Due to the specifics of thelibgit2
authentication procedure, when authentication fails, this function is called again without any indication whether authentication was successful or not. To avoid an infinite loop from repeatedly using the same faulty credentials, we will keep track of state using the payload.
For addition details see the LibGit2 guide onauthenticating against a server.
LibGit2.credentials_cb
—FunctionC function pointer forcredentials_callback
LibGit2.default_signature
—FunctionReturn signature object. Free it after use.
LibGit2.delete_branch
—FunctionLibGit2.delete_branch(branch::GitReference)
Delete the branch pointed to bybranch
.
LibGit2.diff_files
—Functiondiff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; kwarg...) -> Vector{AbstractString}
Show which files have changed in the git repositoryrepo
between branchesbranch1
andbranch2
.
The keyword argument is:
filter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED]))
, and it sets options for the diff. The default is to show files added, modified, or deleted.Return only thenames of the files which have changed,not their contents.
Examples
LibGit2.branch!(repo, "branch/a")LibGit2.branch!(repo, "branch/b")# add a file to repoopen(joinpath(LibGit2.path(repo),"file"),"w") do f write(f, "hello repo")endLibGit2.add!(repo, "file")LibGit2.commit(repo, "add file")# returns ["file"]filt = Set([LibGit2.Consts.DELTA_ADDED])files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)# returns [] because existing files weren't modifiedfilt = Set([LibGit2.Consts.DELTA_MODIFIED])files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)
Equivalent togit diff --name-only --diff-filter=<filter> <branch1> <branch2>
.
LibGit2.entryid
—Functionentryid(te::GitTreeEntry)
Return theGitHash
of the object to whichte
refers.
LibGit2.entrytype
—Functionentrytype(te::GitTreeEntry)
Return the type of the object to whichte
refers. The result will be one of the types whichobjtype
returns, e.g. aGitTree
orGitBlob
.
LibGit2.fetch
—Functionfetch(rmt::GitRemote, refspecs; options::FetchOptions=FetchOptions(), msg="")
Fetch from the specifiedrmt
remote git repository, usingrefspecs
to determine which remote branch(es) to fetch. The keyword arguments are:
options
: determines the options for the fetch, e.g. whether to prune afterwards. SeeFetchOptions
for more information.msg
: a message to insert into the reflogs.fetch(repo::GitRepo; kwargs...)
Fetches updates from an upstream of the repositoryrepo
.
The keyword arguments are:
remote::AbstractString="origin"
: which remote, specified by name, ofrepo
to fetch from. If this is empty, the URL will be used to construct an anonymous remote.remoteurl::AbstractString=""
: the URL ofremote
. If not specified, will be assumed based on the given name ofremote
.refspecs=AbstractString[]
: determines properties of the fetch.credentials=nothing
: provides credentials and/or settings when authenticating against a privateremote
.callbacks=Callbacks()
: user provided callbacks and payloads.Equivalent togit fetch [<remoteurl>|<repo>] [<refspecs>]
.
LibGit2.fetchheads
—Functionfetchheads(repo::GitRepo) -> Vector{FetchHead}
Return the list of all the fetch heads forrepo
, each represented as aFetchHead
, including their names, URLs, and merge statuses.
Examples
julia> fetch_heads = LibGit2.fetchheads(repo);julia> fetch_heads[1].name"refs/heads/master"julia> fetch_heads[1].ismergetruejulia> fetch_heads[2].name"refs/heads/test_branch"julia> fetch_heads[2].ismergefalse
LibGit2.fetch_refspecs
—Functionfetch_refspecs(rmt::GitRemote) -> Vector{String}
Get thefetch refspecs for the specifiedrmt
. These refspecs contain information about which branch(es) to fetch from.
Examples
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");julia> LibGit2.add_fetch!(repo, remote, "upstream");julia> LibGit2.fetch_refspecs(remote)String["+refs/heads/*:refs/remotes/upstream/*"]
LibGit2.fetchhead_foreach_cb
—FunctionC function pointer forfetchhead_foreach_callback
LibGit2.merge_base
—Functionmerge_base(repo::GitRepo, one::AbstractString, two::AbstractString) -> GitHash
Find a merge base (a common ancestor) between the commitsone
andtwo
.one
andtwo
may both be in string form. Return theGitHash
of the merge base.
LibGit2.merge!
—Methodmerge!(repo::GitRepo; kwargs...) -> Bool
Perform a git merge on the repositoryrepo
, merging commits with diverging history into the current branch. Returntrue
if the merge succeeded,false
if not.
The keyword arguments are:
committish::AbstractString=""
: Merge the named commit(s) incommittish
.branch::AbstractString=""
: Merge the branchbranch
and all its commits since it diverged from the current branch.fastforward::Bool=false
: Iffastforward
istrue
, only merge if the merge is a fast-forward (the current branch head is an ancestor of the commits to be merged), otherwise refuse to merge and returnfalse
. This is equivalent to the git CLI option--ff-only
.merge_opts::MergeOptions=MergeOptions()
:merge_opts
specifies options for the merge, such as merge strategy in case of conflicts.checkout_opts::CheckoutOptions=CheckoutOptions()
:checkout_opts
specifies options for the checkout step.Equivalent togit merge [--ff-only] [<committish> | <branch>]
.
If you specify abranch
, this must be done in reference format, since the string will be turned into aGitReference
. For example, if you wanted to merge branchbranch_a
, you would callmerge!(repo, branch="refs/heads/branch_a")
.
LibGit2.merge!
—Methodmerge!(repo::GitRepo, anns::Vector{GitAnnotated}; kwargs...) -> Bool
Merge changes from the annotated commits (captured asGitAnnotated
objects)anns
into the HEAD of the repositoryrepo
. The keyword arguments are:
merge_opts::MergeOptions = MergeOptions()
: options for how to perform the merge, including whether fastforwarding is allowed. SeeMergeOptions
for more information.checkout_opts::CheckoutOptions = CheckoutOptions()
: options for how to perform the checkout. SeeCheckoutOptions
for more information.anns
may refer to remote or local branch heads. Returntrue
if the merge is successful, otherwise returnfalse
(for instance, if no merge is possible because the branches have no common ancestor).
Examples
upst_ann = LibGit2.GitAnnotated(repo, "branch/a")# merge the branch inLibGit2.merge!(repo, [upst_ann])
LibGit2.merge!
—Methodmerge!(repo::GitRepo, anns::Vector{GitAnnotated}, fastforward::Bool; kwargs...) -> Bool
Merge changes from the annotated commits (captured asGitAnnotated
objects)anns
into the HEAD of the repositoryrepo
. Iffastforward
istrue
,only a fastforward merge is allowed. In this case, if conflicts occur, the merge will fail. Otherwise, iffastforward
isfalse
, the merge may produce a conflict file which the user will need to resolve.
The keyword arguments are:
merge_opts::MergeOptions = MergeOptions()
: options for how to perform the merge, including whether fastforwarding is allowed. SeeMergeOptions
for more information.checkout_opts::CheckoutOptions = CheckoutOptions()
: options for how to perform the checkout. SeeCheckoutOptions
for more information.anns
may refer to remote or local branch heads. Returntrue
if the merge is successful, otherwise returnfalse
(for instance, if no merge is possible because the branches have no common ancestor).
Examples
upst_ann_1 = LibGit2.GitAnnotated(repo, "branch/a")# merge the branch in, fastforwardLibGit2.merge!(repo, [upst_ann_1], true)# merge conflicts!upst_ann_2 = LibGit2.GitAnnotated(repo, "branch/b")# merge the branch in, try to fastforwardLibGit2.merge!(repo, [upst_ann_2], true) # will return falseLibGit2.merge!(repo, [upst_ann_2], false) # will return true
LibGit2.ffmerge!
—Functionffmerge!(repo::GitRepo, ann::GitAnnotated)
Fastforward merge changes into current HEAD. This is only possible if the commit referred to byann
is descended from the current HEAD (e.g. if pulling changes from a remote branch which is simply ahead of the local branch tip).
LibGit2.fullname
—FunctionLibGit2.fullname(ref::GitReference)
Return the name of the reference pointed to by the symbolic referenceref
. Ifref
is not a symbolic reference, return an empty string.
LibGit2.features
—Functionfeatures()
Return a list of git features the current version of libgit2 supports, such as threading or using HTTPS or SSH.
LibGit2.filename
—Functionfilename(te::GitTreeEntry)
Return the filename of the object on disk to whichte
refers.
LibGit2.filemode
—Functionfilemode(te::GitTreeEntry) -> Cint
Return the UNIX filemode of the object on disk to whichte
refers as an integer.
LibGit2.gitdir
—FunctionLibGit2.git_url
—FunctionLibGit2.git_url(; kwargs...) -> String
Create a string based upon the URL components provided. When thescheme
keyword is not provided the URL produced will use the alternativescp-like syntax.
Keywords
scheme::AbstractString=""
: the URL scheme which identifies the protocol to be used. For HTTP use "http", SSH use "ssh", etc. Whenscheme
is not provided the output format will be "ssh" but using the scp-like syntax.username::AbstractString=""
: the username to use in the output if provided.password::AbstractString=""
: the password to use in the output if provided.host::AbstractString=""
: the hostname to use in the output. A hostname is required to be specified.port::Union{AbstractString,Integer}=""
: the port number to use in the output if provided. Cannot be specified when using the scp-like syntax.path::AbstractString=""
: the path to use in the output if provided.Avoid using passwords in URLs. Unlike the credential objects, Julia is not able to securely zero or destroy the sensitive data after use and the password may remain in memory; possibly to be exposed by an uninitialized memory.
Examples
julia> LibGit2.git_url(username="git", host="github.com", path="JuliaLang/julia.git")"git@github.com:JuliaLang/julia.git"julia> LibGit2.git_url(scheme="https", host="github.com", path="/JuliaLang/julia.git")"https://github.com/JuliaLang/julia.git"julia> LibGit2.git_url(scheme="ssh", username="git", host="github.com", port=2222, path="JuliaLang/julia.git")"ssh://git@github.com:2222/JuliaLang/julia.git"
LibGit2.@githash_str
—Macro@githash_str -> AbstractGitHash
Construct a git hash object from the given string, returning aGitShortHash
if the string is shorter than 40 hexadecimal digits, otherwise aGitHash
.
Examples
julia> LibGit2.githash"d114feb74ce633"GitShortHash("d114feb74ce633")julia> LibGit2.githash"d114feb74ce63307afe878a5228ad014e0289a85"GitHash("d114feb74ce63307afe878a5228ad014e0289a85")
LibGit2.head
—FunctionLibGit2.head(repo::GitRepo) -> GitReference
Return aGitReference
to the current HEAD ofrepo
.
head(pkg::AbstractString) -> String
Return current HEADGitHash
of thepkg
repo as a string.
LibGit2.head!
—FunctionLibGit2.head!(repo::GitRepo, ref::GitReference) -> GitReference
Set the HEAD ofrepo
to the object pointed to byref
.
LibGit2.head_oid
—FunctionLibGit2.head_oid(repo::GitRepo) -> GitHash
Lookup the object id of the current HEAD of git repositoryrepo
.
LibGit2.headname
—FunctionLibGit2.headname(repo::GitRepo)
Lookup the name of the current HEAD of git repositoryrepo
. Ifrepo
is currently detached, return the name of the HEAD it's detached from.
LibGit2.init
—FunctionLibGit2.init(path::AbstractString, bare::Bool=false) -> GitRepo
Open a new git repository atpath
. Ifbare
isfalse
, the working tree will be created inpath/.git
. Ifbare
istrue
, no working directory will be created.
LibGit2.is_ancestor_of
—Functionis_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) -> Bool
Returntrue
ifa
, aGitHash
in string form, is an ancestor ofb
, aGitHash
in string form.
Examples
julia> repo = GitRepo(repo_path);julia> LibGit2.add!(repo, test_file1);julia> commit_oid1 = LibGit2.commit(repo, "commit1");julia> LibGit2.add!(repo, test_file2);julia> commit_oid2 = LibGit2.commit(repo, "commit2");julia> LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo)true
LibGit2.isbinary
—Functionisbinary(blob::GitBlob) -> Bool
Use a heuristic to guess if a file is binary: searching for NULL bytes and looking for a reasonable ratio of printable to non-printable characters among the first 8000 bytes.
LibGit2.iscommit
—Functioniscommit(id::AbstractString, repo::GitRepo) -> Bool
Check if commitid
(which is aGitHash
in string form) is in the repository.
Examples
julia> repo = GitRepo(repo_path);julia> LibGit2.add!(repo, test_file);julia> commit_oid = LibGit2.commit(repo, "add test_file");julia> LibGit2.iscommit(string(commit_oid), repo)true
LibGit2.isdiff
—FunctionLibGit2.isdiff(repo::GitRepo, treeish::AbstractString, pathspecs::AbstractString=""; cached::Bool=false)
Checks if there are any differences between the tree specified bytreeish
and the tracked files in the working tree (ifcached=false
) or the index (ifcached=true
).pathspecs
are the specifications for options for the diff.
Examples
repo = LibGit2.GitRepo(repo_path)LibGit2.isdiff(repo, "HEAD") # should be falseopen(joinpath(repo_path, new_file), "a") do f println(f, "here's my cool new file")endLibGit2.isdiff(repo, "HEAD") # now true
Equivalent togit diff-index <treeish> [-- <pathspecs>]
.
LibGit2.isdirty
—FunctionLibGit2.isdirty(repo::GitRepo, pathspecs::AbstractString=""; cached::Bool=false) -> Bool
Check if there have been any changes to tracked files in the working tree (ifcached=false
) or the index (ifcached=true
).pathspecs
are the specifications for options for the diff.
Examples
repo = LibGit2.GitRepo(repo_path)LibGit2.isdirty(repo) # should be falseopen(joinpath(repo_path, new_file), "a") do f println(f, "here's my cool new file")endLibGit2.isdirty(repo) # now trueLibGit2.isdirty(repo, new_file) # now true
Equivalent togit diff-index HEAD [-- <pathspecs>]
.
LibGit2.isorphan
—FunctionLibGit2.isorphan(repo::GitRepo)
Check if the current branch is an "orphan" branch, i.e. has no commits. The first commit to this branch will have no parents.
LibGit2.isset
—Functionisset(val::Integer, flag::Integer)
Test whether the bits ofval
indexed byflag
are set (1
) or unset (0
).
LibGit2.iszero
—Functioniszero(id::GitHash) -> Bool
Determine whether all hexadecimal digits of the givenGitHash
are zero.
LibGit2.lookup_branch
—Functionlookup_branch(repo::GitRepo, branch_name::AbstractString, remote::Bool=false) -> Union{GitReference, Nothing}
Determine if the branch specified bybranch_name
exists in the repositoryrepo
. Ifremote
istrue
,repo
is assumed to be a remote git repository. Otherwise, it is part of the local filesystem.
Return either aGitReference
to the requested branch if it exists, ornothing
if not.
LibGit2.map
—FunctionLibGit2.map(f::Function, walker::GitRevWalker; oid::GitHash=GitHash(), range::AbstractString="", by::Cint=Consts.SORT_NONE, rev::Bool=false)
Using theGitRevWalker
walker
to "walk" over every commit in the repository's history, applyf
to each commit in the walk. The keyword arguments are: *oid
: TheGitHash
of the commit to begin the walk from. The default is to usepush_head!
and therefore the HEAD commit and all its ancestors. *range
: A range ofGitHash
s in the formatoid1..oid2
.f
will be applied to all commits between the two. *by
: The sorting method. The default is not to sort. Other options are to sort by topology (LibGit2.Consts.SORT_TOPOLOGICAL
), to sort forwards in time (LibGit2.Consts.SORT_TIME
, most ancient first) or to sort backwards in time (LibGit2.Consts.SORT_REVERSE
, most recent first). *rev
: Whether to reverse the sorted order (for instance, if topological sorting is used).
Examples
oids = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker LibGit2.map((oid, repo)->string(oid), walker, by=LibGit2.Consts.SORT_TIME)end
Here,LibGit2.map
visits each commit using theGitRevWalker
and finds itsGitHash
.
LibGit2.mirror_callback
—FunctionMirror callback function
Function sets+refs/*:refs/*
refspecs andmirror
flag for remote reference.
LibGit2.mirror_cb
—FunctionC function pointer formirror_callback
LibGit2.message
—Functionmessage(c::GitCommit, raw::Bool=false)
Return the commit message describing the changes made in commitc
. Ifraw
isfalse
, return a slightly "cleaned up" message (which has any leading newlines removed). Ifraw
istrue
, the message is not stripped of any such newlines.
LibGit2.merge_analysis
—Functionmerge_analysis(repo::GitRepo, anns::Vector{GitAnnotated}) -> analysis, preference
Run analysis on the branches pointed to by the annotated branch tipsanns
and determine under what circumstances they can be merged. For instance, ifanns[1]
is simply an ancestor ofann[2]
, thenmerge_analysis
will report that a fast-forward merge is possible.
Return two outputs,analysis
andpreference
.analysis
has several possible values: *MERGE_ANALYSIS_NONE
: it is not possible to merge the elements ofanns
. *MERGE_ANALYSIS_NORMAL
: a regular merge, when HEAD and the commits that the user wishes to merge have all diverged from a common ancestor. In this case the changes have to be resolved and conflicts may occur. *MERGE_ANALYSIS_UP_TO_DATE
: all the input commits the user wishes to merge can be reached from HEAD, so no merge needs to be performed. *MERGE_ANALYSIS_FASTFORWARD
: the input commit is a descendant of HEAD and so no merge needs to be performed - instead, the user can simply checkout the input commit(s). *MERGE_ANALYSIS_UNBORN
: the HEAD of the repository refers to a commit which does not exist. It is not possible to merge, but it may be possible to checkout the input commits.preference
also has several possible values: *MERGE_PREFERENCE_NONE
: the user has no preference. *MERGE_PREFERENCE_NO_FASTFORWARD
: do not allow any fast-forward merges. *MERGE_PREFERENCE_FASTFORWARD_ONLY
: allow only fast-forward merges and no other type (which may introduce conflicts).preference
can be controlled through the repository or global git configuration.
LibGit2.name
—FunctionLibGit2.name(ref::GitReference)
Return the full name ofref
.
name(rmt::GitRemote)
Get the name of a remote repository, for instance"origin"
. If the remote is anonymous (seeGitRemoteAnon
) the name will be an empty string""
.
Examples
julia> repo_url = "https://github.com/JuliaLang/Example.jl";julia> repo = LibGit2.clone(cache_repo, "test_directory");julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);julia> name(remote)"origin"
LibGit2.name(tag::GitTag)
The name oftag
(e.g."v0.5"
).
LibGit2.need_update
—Functionneed_update(repo::GitRepo)
Equivalent togit update-index
. Returntrue
ifrepo
needs updating.
LibGit2.objtype
—Functionobjtype(obj_type::Consts.OBJECT)
Return the type corresponding to the enum value.
LibGit2.path
—FunctionLibGit2.path(repo::GitRepo)
Return the base file path of the repositoryrepo
.
workdir
for more details).LibGit2.peel
—Functionpeel([T,] ref::GitReference)
Recursively peelref
until an object of typeT
is obtained. If noT
is provided, thenref
will be peeled until an object other than aGitTag
is obtained.
Only annotated tags can be peeled toGitTag
objects. Lightweight tags (the default) are references underrefs/tags/
which point directly toGitCommit
objects.
peel([T,] obj::GitObject)
Recursively peelobj
until an object of typeT
is obtained. If noT
is provided, thenobj
will be peeled until the type changes.
GitTag
will be peeled to the object it references.GitCommit
will be peeled to aGitTree
.LibGit2.posixpath
—FunctionLibGit2.posixpath(path)
Standardise the path stringpath
to use POSIX separators.
LibGit2.push
—Functionpush(rmt::GitRemote, refspecs; force::Bool=false, options::PushOptions=PushOptions())
Push to the specifiedrmt
remote git repository, usingrefspecs
to determine which remote branch(es) to push to. The keyword arguments are:
force
: iftrue
, a force-push will occur, disregarding conflicts.options
: determines the options for the push, e.g. which proxy headers to use. SeePushOptions
for more information.You can add information about the push refspecs in two other ways: by setting an option in the repository'sGitConfig
(withpush.default
as the key) or by callingadd_push!
. Otherwise you will need to explicitly specify a push refspec in the call topush
for it to have any effect, like so:LibGit2.push(repo, refspecs=["refs/heads/master"])
.
push(repo::GitRepo; kwargs...)
Pushes updates to an upstream ofrepo
.
The keyword arguments are:
remote::AbstractString="origin"
: the name of the upstream remote to push to.remoteurl::AbstractString=""
: the URL ofremote
.refspecs=AbstractString[]
: determines properties of the push.force::Bool=false
: determines if the push will be a force push, overwriting the remote branch.credentials=nothing
: provides credentials and/or settings when authenticating against a privateremote
.callbacks=Callbacks()
: user provided callbacks and payloads.Equivalent togit push [<remoteurl>|<repo>] [<refspecs>]
.
LibGit2.push!
—MethodLibGit2.push!(w::GitRevWalker, cid::GitHash)
Start theGitRevWalker
walker
at commitcid
. This function can be used to apply a function to all commits since a certain year, by passing the first commit of that year ascid
and then passing the resultingw
toLibGit2.map
.
LibGit2.push_head!
—FunctionLibGit2.push_head!(w::GitRevWalker)
Push the HEAD commit and its ancestors onto theGitRevWalker
w
. This ensures that HEAD and all its ancestor commits will be encountered during the walk.
LibGit2.push_refspecs
—Functionpush_refspecs(rmt::GitRemote) -> Vector{String}
Get thepush refspecs for the specifiedrmt
. These refspecs contain information about which branch(es) to push to.
Examples
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");julia> LibGit2.add_push!(repo, remote, "refs/heads/master");julia> close(remote);julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");julia> LibGit2.push_refspecs(remote)String["refs/heads/master"]
LibGit2.raw
—Functionraw(id::GitHash) -> Vector{UInt8}
Obtain the raw bytes of theGitHash
as a vector of length 20.
LibGit2.read_tree!
—FunctionLibGit2.read_tree!(idx::GitIndex, tree::GitTree)LibGit2.read_tree!(idx::GitIndex, treehash::AbstractGitHash)
Read the treetree
(or the tree pointed to bytreehash
in the repository owned byidx
) into the indexidx
. The current index contents will be replaced.
LibGit2.rebase!
—FunctionLibGit2.rebase!(repo::GitRepo, upstream::AbstractString="", newbase::AbstractString="")
Attempt an automatic merge rebase of the current branch, fromupstream
if provided, or otherwise from the upstream tracking branch.newbase
is the branch to rebase onto. By default this isupstream
.
If any conflicts arise which cannot be automatically resolved, the rebase will abort, leaving the repository and working tree in its original state, and the function will throw aGitError
. This is roughly equivalent to the following command line statement:
git rebase --merge [<upstream>]if [ -d ".git/rebase-merge" ]; then git rebase --abortfi
LibGit2.ref_list
—FunctionLibGit2.ref_list(repo::GitRepo) -> Vector{String}
Get a list of all reference names in therepo
repository.
LibGit2.reftype
—FunctionLibGit2.reftype(ref::GitReference) -> Cint
Return aCint
corresponding to the type ofref
:
0
if the reference is invalid1
if the reference is an object id2
if the reference is symbolicLibGit2.remotes
—FunctionLibGit2.remotes(repo::GitRepo)
Return a vector of the names of the remotes ofrepo
.
LibGit2.remove!
—Functionremove!(repo::GitRepo, files::AbstractString...)remove!(idx::GitIndex, files::AbstractString...)
Remove all the files with paths specified byfiles
in the indexidx
(or the index of therepo
).
LibGit2.reset
—Functionreset(val::Integer, flag::Integer)
Unset the bits ofval
indexed byflag
, returning them to0
.
LibGit2.reset!
—Functionreset!(payload, [config]) -> CredentialPayload
Reset thepayload
state back to the initial values so that it can be used again within the credential callback. If aconfig
is provided the configuration will also be updated.
Updates some entries, determined by thepathspecs
, in the index from the target commit tree.
Sets the current head to the specified commit oid and optionally resets the index and working tree to match.
git reset [<committish>] [–] <pathspecs>...
reset!(repo::GitRepo, id::GitHash, mode::Cint=Consts.RESET_MIXED)
Reset the repositoryrepo
to its state atid
, using one of three modes set bymode
:
Consts.RESET_SOFT
- move HEAD toid
.Consts.RESET_MIXED
- default, move HEAD toid
and reset the index toid
.Consts.RESET_HARD
- move HEAD toid
, reset the index toid
, and discard all working changes.Examples
# fetch changesLibGit2.fetch(repo)isfile(joinpath(repo_path, our_file)) # will be false# fastforward merge the changesLibGit2.merge!(repo, fastforward=true)# because there was not any file locally, but there is# a file remotely, we need to reset the branchhead_oid = LibGit2.head_oid(repo)new_head = LibGit2.reset!(repo, head_oid, LibGit2.Consts.RESET_HARD)
In this example, the remote which is being fetched fromdoes have a file calledour_file
in its index, which is why we must reset.
Equivalent togit reset [--soft | --mixed | --hard] <id>
.
Examples
repo = LibGit2.GitRepo(repo_path)head_oid = LibGit2.head_oid(repo)open(joinpath(repo_path, "file1"), "w") do f write(f, "111")endLibGit2.add!(repo, "file1")mode = LibGit2.Consts.RESET_HARD# will discard the changes to file1# and unstage itnew_head = LibGit2.reset!(repo, head_oid, mode)
LibGit2.restore
—Functionrestore(s::State, repo::GitRepo)
Return a repositoryrepo
to a previousState
s
, for example the HEAD of a branch before a merge attempt.s
can be generated using thesnapshot
function.
LibGit2.revcount
—FunctionLibGit2.revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString)
List the number of revisions betweencommit1
andcommit2
(committish OIDs in string form). Sincecommit1
andcommit2
may be on different branches,revcount
performs a "left-right" revision list (and count), returning a tuple ofInt
s - the number of left and right commits, respectively. A left (or right) commit refers to which side of a symmetric difference in a tree the commit is reachable from.
Equivalent togit rev-list --left-right --count <commit1> <commit2>
.
Examples
repo = LibGit2.GitRepo(repo_path)repo_file = open(joinpath(repo_path, test_file), "a")println(repo_file, "hello world")flush(repo_file)LibGit2.add!(repo, test_file)commit_oid1 = LibGit2.commit(repo, "commit 1")println(repo_file, "hello world again")flush(repo_file)LibGit2.add!(repo, test_file)commit_oid2 = LibGit2.commit(repo, "commit 2")LibGit2.revcount(repo, string(commit_oid1), string(commit_oid2))
This will return(-1, 0)
.
LibGit2.set_remote_url
—Functionset_remote_url(repo::GitRepo, remote_name, url)set_remote_url(repo::String, remote_name, url)
Set both the fetch and pushurl
forremote_name
for theGitRepo
or the git repository located atpath
. Typically git repos use"origin"
as the remote name.
Examples
repo_path = joinpath(tempdir(), "Example")repo = LibGit2.init(repo_path)LibGit2.set_remote_url(repo, "upstream", "https://github.com/JuliaLang/Example.jl")LibGit2.set_remote_url(repo_path, "upstream2", "https://github.com/JuliaLang/Example2.jl")
LibGit2.shortname
—FunctionLibGit2.shortname(ref::GitReference)
Return a shortened version of the name ofref
that's "human-readable".
julia> repo = GitRepo(path_to_repo);julia> branch_ref = LibGit2.head(repo);julia> LibGit2.name(branch_ref)"refs/heads/master"julia> LibGit2.shortname(branch_ref)"master"
LibGit2.snapshot
—Functionsnapshot(repo::GitRepo) -> State
Take a snapshot of the current state of the repositoryrepo
, storing the current HEAD, index, and any uncommitted work. The outputState
can be used later during a call torestore
to return the repository to the snapshotted state.
LibGit2.split_cfg_entry
—FunctionLibGit2.split_cfg_entry(ce::LibGit2.ConfigEntry) -> Tuple{String,String,String,String}
Break theConfigEntry
up to the following pieces: section, subsection, name, and value.
Examples
Given the git configuration file containing:
[credential "https://example.com"] username = me
TheConfigEntry
would look like the following:
julia> entryConfigEntry("credential.https://example.com.username", "me")julia> LibGit2.split_cfg_entry(entry)("credential", "https://example.com", "username", "me")
Refer to thegit config syntax documentation for more details.
LibGit2.status
—FunctionLibGit2.status(repo::GitRepo, path::String) -> Union{Cuint, Cvoid}
Lookup the status of the file atpath
in the git repositoryrepo
. For instance, this can be used to check if the file atpath
has been modified and needs to be staged and committed.
LibGit2.stage
—Functionstage(ie::IndexEntry) -> Cint
Get the stage number ofie
. The stage number0
represents the current state of the working tree, but other numbers can be used in the case of a merge conflict. In such a case, the various stage numbers on anIndexEntry
describe which side(s) of the conflict the current state of the file belongs to. Stage0
is the state before the attempted merge, stage1
is the changes which have been made locally, stages2
and larger are for changes from other branches (for instance, in the case of a multi-branch "octopus" merge, stages2
,3
, and4
might be used).
LibGit2.tag_create
—FunctionLibGit2.tag_create(repo::GitRepo, tag::AbstractString, commit; kwargs...)
Create a new git tagtag
(e.g."v0.5"
) in the repositoryrepo
, at the commitcommit
.
The keyword arguments are:
msg::AbstractString=""
: the message for the tag.force::Bool=false
: iftrue
, existing references will be overwritten.sig::Signature=Signature(repo)
: the tagger's signature.LibGit2.tag_delete
—FunctionLibGit2.tag_delete(repo::GitRepo, tag::AbstractString)
Remove the git tagtag
from the repositoryrepo
.
LibGit2.tag_list
—FunctionLibGit2.tag_list(repo::GitRepo) -> Vector{String}
Get a list of all tags in the git repositoryrepo
.
LibGit2.target
—FunctionLibGit2.target(tag::GitTag)
TheGitHash
of the target object oftag
.
LibGit2.toggle
—Functiontoggle(val::Integer, flag::Integer)
Flip the bits ofval
indexed byflag
, so that if a bit is0
it will be1
after the toggle, and vice-versa.
LibGit2.transact
—FunctionLibGit2.treewalk
—Functiontreewalk(f, tree::GitTree, post::Bool=false)
Traverse the entries intree
and its subtrees in post or pre order. Preorder means beginning at the root and then traversing the leftmost subtree (and recursively on down through that subtree's leftmost subtrees) and moving right through the subtrees. Postorder means beginning at the bottom of the leftmost subtree, traversing upwards through it, then traversing the next right subtree (again beginning at the bottom) and finally visiting the tree root last of all.
The function parameterf
should have following signature:
(String, GitTreeEntry) -> Cint
A negative value returned fromf
stops the tree walk. A positive value means that the entry will be skipped ifpost
isfalse
.
LibGit2.upstream
—Functionupstream(ref::GitReference) -> Union{GitReference, Nothing}
Determine if the branch containingref
has a specified upstream branch.
Return either aGitReference
to the upstream branch if it exists, ornothing
if the requested branch does not have an upstream counterpart.
LibGit2.update!
—Functionupdate!(repo::GitRepo, files::AbstractString...)update!(idx::GitIndex, files::AbstractString...)
Update all the files with paths specified byfiles
in the indexidx
(or the index of therepo
). Match the state of each file in the index with the current state on disk, removing it if it has been removed on disk, or updating its entry in the object database.
LibGit2.url
—Functionurl(rmt::GitRemote)
Get the fetch URL of a remote git repository.
Examples
julia> repo_url = "https://github.com/JuliaLang/Example.jl";julia> repo = LibGit2.init(mktempdir());julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);julia> LibGit2.url(remote)"https://github.com/JuliaLang/Example.jl"
LibGit2.version
—Functionversion() -> VersionNumber
Return the version of libgit2 in use, as aVersionNumber
.
LibGit2.with
—Functionwith(f::Function, obj)
Resource management helper function. Appliesf
toobj
, making sure to callclose
onobj
afterf
successfully returns or throws an error. Ensures that allocated git resources are finalized as soon as they are no longer needed.
LibGit2.with_warn
—Functionwith_warn(f::Function, ::Type{T}, args...)
Resource management helper function. Applyf
toargs
, first constructing an instance of typeT
fromargs
. Makes sure to callclose
on the resulting object afterf
successfully returns or throws an error. Ensures that allocated git resources are finalized as soon as they are no longer needed. If an error is thrown byf
, a warning is shown containing the error.
LibGit2.workdir
—FunctionLibGit2.workdir(repo::GitRepo)
Return the location of the working directory ofrepo
. This will throw an error for bare repositories.
This will typically be the parent directory ofgitdir(repo)
, but can be different in some cases: e.g. if either thecore.worktree
configuration variable or theGIT_WORK_TREE
environment variable is set.
LibGit2.GitObject
—Method(::Type{T})(te::GitTreeEntry) where T<:GitObject
Get the git object to whichte
refers and return it as its actual type (the typeentrytype
would show), for instance aGitBlob
orGitTag
.
Examples
tree = LibGit2.GitTree(repo, "HEAD^{tree}")tree_entry = tree[1]blob = LibGit2.GitBlob(tree_entry)
LibGit2.UserPasswordCredential
—TypeCredential that support onlyuser
andpassword
parameters
LibGit2.SSHCredential
—TypeSSH credential type
LibGit2.isfilled
—Functionisfilled(cred::AbstractCredential) -> Bool
Verifies that a credential is ready for use in authentication.
LibGit2.CachedCredentials
—TypeCaches credential information for re-use
LibGit2.CredentialPayload
—TypeLibGit2.CredentialPayload
Retains the state between multiple calls to the credential callback for the same URL. ACredentialPayload
instance is expected to bereset!
whenever it will be used with a different URL.
LibGit2.approve
—Functionapprove(payload::CredentialPayload; shred::Bool=true) -> Nothing
Store thepayload
credential for re-use in a future authentication. Should only be called when authentication was successful.
Theshred
keyword controls whether sensitive information in the payload credential field should be destroyed. Should only be set tofalse
during testing.
LibGit2.reject
—Functionreject(payload::CredentialPayload; shred::Bool=true) -> Nothing
Discard thepayload
credential from begin re-used in future authentication. Should only be called when authentication was unsuccessful.
Theshred
keyword controls whether sensitive information in the payload credential field should be destroyed. Should only be set tofalse
during testing.
LibGit2.Consts.GIT_CONFIG
—TypePriority level of a config file.
These priority levels correspond to the natural escalation logic (from higher to lower) when searching for config entries in git.
CONFIG_LEVEL_DEFAULT
- Open the global, XDG and system configuration files if any available.CONFIG_LEVEL_PROGRAMDATA
- System-wide on Windows, for compatibility with portable gitCONFIG_LEVEL_SYSTEM
- System-wide configuration file;/etc/gitconfig
on Linux systemsCONFIG_LEVEL_XDG
- XDG compatible configuration file; typically~/.config/git/config
CONFIG_LEVEL_GLOBAL
- User-specific configuration file (also called Global configuration file); typically~/.gitconfig
CONFIG_LEVEL_LOCAL
- Repository specific configuration file;$WORK_DIR/.git/config
on non-bare reposCONFIG_LEVEL_APP
- Application specific configuration file; freely defined by applicationsCONFIG_HIGHEST_LEVEL
- Represents the highest level available config file (i.e. the most specific config file available that actually is loaded)Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.