Determine if directory is under git control

Just found this in git help rev-parse

git rev-parse --is-inside-work-tree

prints true if it is in the work tree, false if it's in the '.git' tree, and fatal error if it's neither. Both 'true' and 'false' are printed on stdout with an exit status of 0, the fatal error is printed on stderr with an exit status of 128.


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.


With gitpython, you can make a function like this:

import git

...

def is_git_repo(path):
    try:
        _ = git.Repo(path).git_dir
        return True
    except git.exc.InvalidGitRepositoryError:
        return False

Well, the directory can also be ignored by the .gitignore file - so you need to check for a .git repository, and if there is one, parse the .gitignore to see whether that directory is indeed in the git repository.

What exactly do you want to do? There may be a simpler way to do this.

EDIT: Do you mean "Is this directory the root of a GIT repository" or, do you mean "Is this directory part of a GIT repository" ?

For the first one, then just check if there is a .git -- since that's at the root, and you're done. For the second one, once you've determined that you're inside a GIT repository, you need to check .gitignore for the subdirectory in question.


For the record, use git status or similar, this is just for completeness: :)

Searching upward a tree is no biggie really, in bash you can do this simple one-liner (if you put it on one line...) ;) Returns 0 if one is found, 1 otherwise.

d=`pwd`
while [ "$d" != "" ]; do
  [ -d "$d"/.git ] && exit 0
  d=${d%/*}
done
exit 1

will search upward looking for a .git folder.