I'm writing a script for some colleagues to use on their Git repositories, and I'm confused about how to reliably find the root of the repo's work-tree:
Typically, if the current directory is inside a work-tree, the commands...
git rev-parse --git-dir
git rev-parse --show-toplevel
...would return the roots of the .git
directory and work-tree, respectively. However, if the current directory happens to be inside a .git
directory, then only the first command works. The command git rev-parse --show-toplevel
does not show the top-level of the work-tree (at least, not for me, using git 1.8.4.4 on Linux).
Assuming that git rev-parse --is-bare-repository
returns false
, I would normally guess that the parent directory of git rev-parse --git-dir
is either the working directory (or somewhere inside the working directory), but if the user's GIT_DIR
is set that the .git
directory isn't inside the working directory, that won't work. (For example, when the user is working with submodules, their GIT_DIR might not be inside their work tree.)
What I find confusing is that, when run inside a GIT_DIR
, git rev-parse --show-toplevel
prints no error messages and returns 0:
$ cd $(git rev-parse --git-dir); git rev-parse --show-toplevel ; echo $?
0
Whereas running the same command somewhere that's clearly not a git repository returns an error code:
$ cd /; git rev-parse --show-toplevel ; echo $?
fatal: Not a git repository (or any of the parent directories): .git
128
If there'a a way to find the work-tree from the GIT_DIR
, could someone tell me how...or if it's simply not possible to derive the location of the work tree from the .git directory, help me understand why, philosophically, the .git directory doesn't keep a reference to its work tree?
Thanks in advance for help/pointers!