To misuse Git, I write a lot of Git hooks. One of my favorite Git subcommands is
rev-parse, because when you're scripting with Git, you need information about your Git repository just as often as you need information from it.
Getting the top-level directory
For Git, there are no directories farther back than its own top-level folder. That's in part what makes it possible to move a Git directory from, say, your computer to a thumb drive or a server with no loss of functionality.
Git is only aware of the directory containing a hidden
.git directory and any tracked folders below that. The
--show-toplevel option displays the root directory of your current Git repository. This is the place where it all starts, at least for Git.
Here's an obvious example of how you might use it:
$ cd ~/example.git $ git rev-parse --show-toplevel /home/seth/example.git
It becomes more useful when you're farther in your Git repo. No matter where you roam within a repo,
rev-parse --show-toplevel always knows your root directory:
$ cd ~/example.git/foo/bar/baz $ git rev-parse --show-toplevel /home/seth/example.git
In a similar way, you can get a pointer to what makes that directory the top level: the hidden
$ git rev-parse --git-dir /home/seth/example.com/.git
Find your way home
--show-cdup option tells you (or your script, more likely) exactly how to get to the top-level directory from your current working directory. It's a lot easier than trying to reverse engineer the output of
--show-toplevel, and it's more portable than hoping a shell has
$ git rev-parse --show-cdup ../../..
Interestingly, you can lie to
--show-cdup, if you want to. Use the
--prefix option to fake the directory you're making your inquiry from:
$ cd ~/example.git/foo/bar/baz $ git rev-parse --prefix /home/seth/example.git/foo --show-cdup ../
Should you need confirmation of where a command is being executed from, you can use the
--is-inside-git-dir options. These return a Boolean value based on the current working directory:
$ pwd .git/hooks $ git rev-parse --is-inside-git-dir true $ git rev-parse --is-inside-work-tree false
rev-parse subcommand is utilitarian. It's not something most people are likely to need every day. However, if you write a lot of Git hooks or use Git heavily in scripts, it may be the Git subcommand you always wanted without knowing you wanted it.
Try it out the next time you invoke Git in a script.