Grumdrig Grumdrig - 3 months ago 17
Git Question

Determine if directory is under git control

How can I tell if a given directory is part of a git respository?

(The following is in python, but bash or something would be fine.)

os.path.isdir('.svn')


will tell you if the current directory is controlled by Subversion. Mercurial and Git just have a .hg/.git at the top of the repository, so for
hg
I can use

os.system('hg -q stat 2> /dev/null > /dev/null') == 0)


but
git status
returns a nonzero (error) exit status if nothing's changed.

Is iterating up the path looking for
.git
myself the best I can do?

Answer

In ruby, system('git rev-parse') will return true if the current directory is in a git repo, and false otherwise. I imagine the pythonic equivalent should work similarly.

EDIT: Sure enough:

# in a git repo, running ipython
>>> system('git rev-parse')
0

# not in a git repo
>>> system('git rev-parse')
32768

Note that there is some output on STDERR when you aren't in a repo, if that matters to you.