Mercurial has a way of printing the root directory (that contains .hg) via
hg root
Is there something equivalent in git to get the director
In case anyone needs a POSIX compliant way of doing this, without needing git
executable:
git-root:
#$1: Path to child directory
git_root_recurse_parent() {
# Check if cwd is a git root directory
if [ -d .git/objects -a -d .git/refs -a -f .git/HEAD ] ; then
pwd
return 0
fi
# Check if recursion should end (typically if cwd is /)
if [ "${1}" = "$(pwd)" ] ; then
return 1
fi
# Check parent directory in the same way
local cwd=$(pwd)
cd ..
git_root_recurse_parent "${cwd}"
}
git_root_recurse_parent
If you just want the functionality as part of a script, remove the shebang, and replace the last git_root_recurse_parent
line with:
git_root() {
(git_root_recurse_parent)
}
Has --show-toplevel
only recently been added to git rev-parse
or why is nobody mentioning it?
From the git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
I wanted to expand upon Daniel Brockman's excellent comment.
Defining git config --global alias.exec '!exec '
allows you to do things like git exec make
because, as man git-config
states:
If the alias expansion is prefixed with an exclamation point, it will be treated as a shell command. [...] Note that shell commands will be executed from the top-level directory of a repository, which may not necessarily be the current directory.
It's also handy to know that $GIT_PREFIX
will be the path to the current directory relative to the top-level directory of a repository. But, knowing it is only half the battle™. Shell variable expansion makes it rather hard to use. So I suggest using bash -c
like so:
git exec bash -c 'ls -l $GIT_PREFIX'
other commands include:
git exec pwd
git exec make
Just in case if you're feeding this path to the Git itself, use :/
# this adds the whole working tree from any directory in the repo
git add :/
# and is equal to
git add $(git rev-parse --show-toplevel)
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
If you're already in the top-level or not in a git repository cd $(git rev-parse --show-cdup)
will take you home (just cd). cd ./$(git rev-parse --show-cdup)
is one way of fixing that.