Skip to content

Commit 2034485

Browse files
committed
Add support for getting commit parent
Required for walking the commit graph.
1 parent 334beab commit 2034485

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

stdlib/LibGit2/src/commit.jl

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,45 @@ function commit(repo::GitRepo, msg::AbstractString;
147147
end
148148
return commit_id
149149
end
150+
151+
"""
152+
parentcount(c::GitCommit)
153+
154+
Get the number of parents of this commit.
155+
156+
See also [`parent`](@ref), [`parent_id`](@ref).
157+
"""
158+
parentcount(c::GitCommit) =
159+
Int(ccall((:git_commit_parentcount, :libgit2), Cuint, (Ptr{Cvoid},), c))
160+
161+
"""
162+
parent(c::GitCommit, n)
163+
164+
Get the `n`-th (1-based) parent of the commit.
165+
166+
See also [`parentcount`](@ref), [`parent_id`](@ref).
167+
"""
168+
function parent(c::GitCommit, n)
169+
ptr_ref = Ref{Ptr{Cvoid}}()
170+
@check ccall((:git_commit_parent, :libgit2), Cint,
171+
(Ptr{Ptr{Cvoid}}, Ptr{Cvoid}, Cuint), ptr_ref, c, n - 1)
172+
return GitCommit(c.owner, ptr_ref[])
173+
end
174+
175+
"""
176+
parent_id(c::GitCommit, n)
177+
178+
Get the oid of the `n`-th (1-based) parent for a commit.
179+
180+
See also [`parentcount`](@ref), [`parent`](@ref).
181+
"""
182+
function parent_id(c::GitCommit, n)
183+
oid_ptr = ccall((:git_commit_parent_id, :libgit2), Ptr{GitHash},
184+
(Ptr{Cvoid}, Cuint), c, n - 1)
185+
if oid_ptr == C_NULL
186+
# 0-based indexing mimicking the error message from libgit2
187+
throw(GitError(Error.Invalid, Error.ENOTFOUND,
188+
"parent $(n - 1) does not exist"))
189+
end
190+
return unsafe_load(oid_ptr)
191+
end

stdlib/LibGit2/test/libgit2-tests.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,14 @@ mktempdir() do dir
928928
@test cmtr.email == test_sig.email
929929
@test LibGit2.message(cmt) == commit_msg1
930930

931+
# test that the parent is correct
932+
@test LibGit2.parentcount(cmt) == 0
933+
LibGit2.with(LibGit2.GitCommit(repo, commit_oid3)) do cmt3
934+
@test LibGit2.parentcount(cmt3) == 1
935+
@test LibGit2.parent_id(cmt3, 1) == commit_oid1
936+
@test LibGit2.GitHash(LibGit2.parent(cmt3, 1)) == commit_oid1
937+
end
938+
931939
# test showing the commit
932940
showstr = split(sprint(show, cmt), "\n")
933941
# the time of the commit will vary so just test the first two parts

0 commit comments

Comments
 (0)