6

Is it possible to programmatically find the path to the .git directory including for submodules?

I'm trying to write a script that installs a git hook but I can't find a straightforward way to find the .git directory for the project. Ideally it should cover the following cases:

  1. In root directory of project
  2. In sub-directory of project
  3. In root directory of submodule within project
  4. In sub-directory of submodule within project

I could do all of this manually but I'd rather not parse the .git file of a submodule.

Edit: I'd be interested in a solution in python as well.

Jason Axelson
  • 4,485
  • 4
  • 48
  • 56
  • howabout using `find` to search for the `.git` directory? – Fredrik Pihl Feb 28 '13 at 21:42
  • @Fredrik how would you know how many directories to go up? Also what if there is a directory with the exact same name? – Jason Axelson Feb 28 '13 at 21:44
  • 5
    Duplicate of http://stackoverflow.com/questions/14073053/find-path-to-git-hooks-directory-on-the-shell – qqx Feb 28 '13 at 21:55
  • @qqx thanks! That didn't come up when googling. Although http://stackoverflow.com/questions/10848191/git-submodule-commit-hooks did – Jason Axelson Feb 28 '13 at 22:02
  • 1
    This question is still first in Google, so copying the http://stackoverflow.com/questions/14073053/find-path-to-git-hooks-directory-on-the-shell solution below. – ntc2 May 08 '13 at 22:40

2 Answers2

4

git rev-parse --git-dir seems to be what you want. I just tested it with a submodule:

cd mymodule
git rev-parse --git-dir  # --> .git
git submodule add ssh://.../path/to/mysubmodule
cd mysubmodule
git rev-parse --git-dir  # --> /home/.../mymodule/.git/modules/mysubmodule

This surprised me, since there was a .git in mysubmodule, but it turned out to be a file, with the following contents:

gitdir: ../.git/modules/mysubmodule
Brandon
  • 2,367
  • 26
  • 32
2

This SO question uses git rev-parse --show-toplevel to find the top directory.

Community
  • 1
  • 1
vonbrand
  • 11,412
  • 8
  • 32
  • 52