How to get the commit of HEAD of a Julia package?

git

#1

Is there a way to get the commit of HEAD of a Julia package from within Julia without using git commands in shell? Googling gave the following command git rev-parse HEAD in git, so is there an equivalent in LibGit2 or Pkg?


#2

The following works:

gitdir = joinpath(Pkg.dir(package_name), ".git")
commit = strip(readstring(`git --git-dir $gitdir rev-parse HEAD`))

#3

It seems that Pkg.dir(package_name) returns an incorrect path when the package is located in a custom path in the LOAD_PATH variable. Should I open an issue? And what is the alternative, searching myself in LOAD_PATH?


#4

The Pkg.dir() function essentially return JULIA_PKGDIR, so this is known. What is your usecase? To record the current state of a package? In Pkg3 this will all be recorded in the Manifest.toml file.


#5

Yes. For now, I can search the paths myself.


#6

This is one way, not sure if it is the best.

julia> r = LibGit2.GitRepo(".")
LibGit2.GitRepo("/Users/kristoffer/julia")

julia> LibGit2.peel(LibGit2.GitCommit, LibGit2.head(r))
Git Commit:
Commit Author: Name: Kristoffer Carlsson, Email: kcarlsson89@gmail.com, Time: 2018-03-12 11:24:27+01:00
Committer: Name: Kristoffer Carlsson, Email: kcarlsson89@gmail.com, Time: 2018-05-14 11:18:17+02:00
SHA: c3cf88ad03abbac9d5d7074863d7277a186cce82
Message:
use Pkg3 for docs

julia> LibGit2.GitHash(ans)
GitHash("c3cf88ad03abbac9d5d7074863d7277a186cce82")

julia> string(ans)
"c3cf88ad03abbac9d5d7074863d7277a186cce82"

#7

This is what I am getting:

julia> r = LibGit2.GitRepo(".")
ERROR: GitError(Code:ENOTFOUND, Class:Repository, Could not find repository from '.')
Stacktrace:
 [1] macro expansion at .\libgit2\error.jl:99 [inlined]
 [2] Base.LibGit2.GitRepo(::String) at .\libgit2\repository.jl:10

#8

Well "." is the path to the repository. I just happened to have my current working dir inside a repo.


#9

Oh I see so you were answering the first question on the Julia alternative. But the Pkg.dir problem means that I still have to search for this path myself.


#10

You can use the internal function find_in_path,

julia> Base.find_in_path("Compat")
"/Users/kristoffer/.julia/v0.6/Compat/src/Compat.jl"

julia> Base.find_in_path("JuAFEM")
"/Users/kristoffer/Dropbox/julia/JuAFEM/src/JuAFEM.jl"

Normal caveates about internal functions apply.


#11

Awesome thanks! What caveats are you talking about?


#12

Like that it is renamed and doesn’t work in the same way on 0.7