Stream: helpdesk (published)

Topic: ✔ Root dir of a git repo


view this post on Zulip Martin Roa (Jun 01 2022 at 14:20):

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?

view this post on Zulip Martin Roa (Jun 01 2022 at 14:43):

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.

view this post on Zulip Sukera (Jun 01 2022 at 14:46):

There's probably someting in LibGit2 for this

view this post on Zulip Martin Roa (Jun 01 2022 at 14:54):

Thanks! There is indeed LibGit2.path(repo::GitRepo).

view this post on Zulip Martin Roa (Jun 01 2022 at 15:08):

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.

view this post on Zulip Sebastian Pfitzner (Jun 01 2022 at 15:10):

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)

view this post on Zulip Martin Roa (Jun 01 2022 at 15:11):

Awesome. Thanks.

view this post on Zulip Sebastian Pfitzner (Jun 01 2022 at 15:13):

may also need a try-catch around isdir, since that can throw

view this post on Zulip Notification Bot (Jun 01 2022 at 15:39):

Martin Roa has marked this topic as resolved.

view this post on Zulip Gunnar Farnebäck (Jun 01 2022 at 17:35):

git rev-parse --show-prefix tells you where you are relative to the repository root.

view this post on Zulip Martin Roa (Jun 01 2022 at 17:41):

Didn't know about that one. Thanks.

view this post on Zulip Sundar R (Jun 02 2022 at 07:45):

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