Skip to content

Commit

Permalink
Add support for getting commit parent
Browse files Browse the repository at this point in the history
Required for walking the commit graph.
  • Loading branch information
yuyichao committed Sep 10, 2023
1 parent cfb77bb commit e9fe149
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
42 changes: 42 additions & 0 deletions stdlib/LibGit2/src/commit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,45 @@ function commit(repo::GitRepo, msg::AbstractString;
end
return commit_id
end

"""
parentcount(c::GitCommit)
Get the number of parents of this commit.
See also [`parent`](@ref), [`parent_id`](@ref).
"""
parentcount(c::GitCommit) =
Int(ccall((:git_commit_parentcount, :libgit2), Cuint, (Ptr{Cvoid},), c))

"""
parent(c::GitCommit, n)
Get the `n`-th (1-based) parent of the commit.
See also [`parentcount`](@ref), [`parent_id`](@ref).
"""
function parent(c::GitCommit, n)
ptr_ref = Ref{Ptr{Cvoid}}()
@check ccall((:git_commit_parent, :libgit2), Cint,
(Ptr{Ptr{Cvoid}}, Ptr{Cvoid}, Cuint), ptr_ref, c, n - 1)
return GitCommit(c.owner, ptr_ref[])
end

"""
parent_id(c::GitCommit, n)
Get the oid of the `n`-th (1-based) parent for a commit.
See also [`parentcount`](@ref), [`parent`](@ref).
"""
function parent_id(c::GitCommit, n)
oid_ptr = ccall((:git_commit_parent_id, :libgit2), Ptr{GitHash},
(Ptr{Cvoid}, Cuint), c, n - 1)
if oid_ptr == C_NULL
# 0-based indexing mimicking the error message from libgit2
throw(GitError(Error.Invalid, Error.ENOTFOUND,
"parent $(n - 1) does not exist"))
end
return unsafe_load(oid_ptr)
end
8 changes: 8 additions & 0 deletions stdlib/LibGit2/test/libgit2-tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,14 @@ mktempdir() do dir
@test cmtr.email == test_sig.email
@test LibGit2.message(cmt) == commit_msg1

# test that the parent is correct
@test LibGit2.parentcount(cmt) == 0
LibGit2.with(LibGit2.GitCommit(repo, commit_oid3)) do cmt3
@test LibGit2.parentcount(cmt3) == 1
@test LibGit2.parent_id(cmt3, 1) == commit_oid1
@test LibGit2.GitHash(LibGit2.parent(cmt3, 1)) == commit_oid1
end

# test showing the commit
showstr = split(sprint(show, cmt), "\n")
# the time of the commit will vary so just test the first two parts
Expand Down

0 comments on commit e9fe149

Please sign in to comment.