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
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.
From git help rev-parse again, I think you can do something like :
git rev-parse --resolve-git-dir <directory>
and check if the command returns the directory path itself. According to the manual git rev-parse returns the path to the directory if the argument contains a git repo or is a file which contains the path to a git repo.
Using git rev-parse --is-inside-work-tree
along with subprocess.Popen
, you can check if "true" is printed from the output indicating the directory does have a git repo:
import subprocess
repo_dir = "../path/to/check/"
command = ['git', 'rev-parse', '--is-inside-work-tree']
process = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=repo_dir,
universal_newlines=True)
process_output = process.communicate()[0]
is_git_repo = str(process_output.strip())
if is_git_repo == "true":
print("success! git repo found under {0}".format(repo_dir))
else:
print("sorry. no git repo found under {0}".format(repo_dir))
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.
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.