I'm looking for a function (or macro) that returns the root directory of a git repo when run from a file inside the repo (sort of how @__DIR__
does it, but then should return the git root dir). Has anybody implemented this?
I came up with this approach:
function gitrootdir(currdir)
while true
currdir == homedir() && return nothing
currdir == "/" && return nothing
".git" in readdir(currdir) && return currdir
currdir = dirname(currdir)
end
end
gitrootdir(@__DIR__)
If someone has a better approach or an improvement for this one, please let me know.
There's probably someting in LibGit2
for this
Thanks! There is indeed LibGit2.path(repo::GitRepo)
.
Actually, this didn't work because I would need to previously call LibGit2.GitRepo(path::AbstractString)
which expects the path to the repo's root dir.
your approach seems fine. I'd check isdir(joinpath(currdir, ".git"))
instead to avoid the readdir
call and also abort the loop when dirname(currdir)==currdir
(in theory that's enough and you shouldn't need the additional checks against homedir
and /
, especially since the latter will only work on unixes)
Awesome. Thanks.
may also need a try-catch around isdir
, since that can throw
Martin Roa has marked this topic as resolved.
git rev-parse --show-prefix
tells you where you are relative to the repository root.
Didn't know about that one. Thanks.
There's also git rev-parse --show-toplevel
which returns the root dir of the repo as an absolute path. This would also work in the (unusual) case that someone doesn't have a .git
directory and has GIT_DIR
and GIT_WORK_TREE
defined instead (or the equivalent cli options enabled).
Last updated: Nov 22 2024 at 04:41 UTC