Get path of the current repo in PyGit2 from anywhere within the repo
<p>I'm using Pygit2 to run certain operations within the repo I'm working on.</p>

<p>If my code file is not at the root of the repo, how can I get the path of the repo from anywhere within the repo?</p>

<p>I can do the below in case the function is called from root, but how to do it if I run it from anywhere within the repository code?</p>

<pre><code>$ cd /home/test/Desktop/code/Project
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

$ ipython3

In [1]: import os, pygit2
In [2]: repo = pygit2.Repository(os.getcwd())
</code></pre>

<p>One option is simply to traverse parent directories until you find a <code>.git</code> directory:</p>

<pre><code>import os
import pathlib
import pygit2

def find_toplevel(path, last=None):
    path = pathlib.Path(path).absolute()

    if path == last:
        return None
    if (path / '.git').is_dir():
        return path

    return find_toplevel(path.parent, last=path)

toplevel = find_toplevel('.')
if toplevel is not None:
  repo = pygit2.Repository(str(toplevel))
</code></pre>

<p>There are some caveats here, of course.  You won't necessarily find a
<code>.git</code> directory if someone has set the <code>GIT_DIR</code> environment
variable.  If you have a git worktree, then <code>.git</code> is a file, not a
directory, and <code>libgit2</code> doesn't seem to handle this (as of version
0.24).</p>

python git python-3.x pygit2