Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
当前回答
今天必须自己解决这个问题。在c#中解决了它,因为我需要它的程序,但我猜它可以轻松重写。考虑到这是公共领域。
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;
}
其他回答
不管你是否已经在git仓库的顶层,cd $(git rev-parse——show-cdup)将带你回家(只是cd)。CD ./$(git rev-parse——show-cdup)是解决这个问题的一种方法。
如果有人需要POSIX兼容的方式来做到这一点,而不需要git可执行文件:
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
如果你只是想把这个功能作为脚本的一部分,删除shebang,并把最后一行git_root_recurse_parent替换为:
git_root() {
(git_root_recurse_parent)
}
正如其他人所注意到的,解决方案的核心是使用git rev-parse——show-cdup。然而,也有一些边缘情况需要解决:
When the cwd already is the root of the working tree, the command yields an empty string. Actually it produces an empty line, but command substitution strip off the trailing line break. The final result is an empty string. Most answers suggest prepending the output with ./ so that an empty output becomes "./" before it is fed to cd. When GIT_WORK_TREE is set to a location that is not the parent of the cwd, the output may be an absolute pathname. Prepending ./ is wrong in this situation. If a ./ is prepended to an absolute path, it becomes a relative path (and they only refer to the same location if the cwd is the root directory of the system). The output may contain whitespace. This really only applies in the second case, but it has an easy fix: use double quotes around the command substitution (and any subsequent uses of the value).
正如其他答案所指出的,我们可以做cd”。/$(git rev-parse——show-cdup))”,但这会在第二个边缘大小写中中断(如果去掉双引号,则会在第三个边缘大小写中中断)。
许多shell将cd ""视为无操作,因此对于这些shell,我们可以执行cd "$(git rev-parse——show-cdup)"(双引号保护第一个边大小写中的空字符串作为参数,并在第三个边大小写中保留空白)。POSIX说cd ""的结果是未指定的,所以最好避免做这种假设。
在上述所有情况下工作的解决方案需要某种类型的测试。显式完成后,它可能是这样的:
cdup="$(git rev-parse --show-cdup)" && test -n "$cdup" && cd "$cdup"
第一个边不做cd操作。
如果运行cd可以接受。对于第一个边情况,则条件可以在参数展开中执行:
cdup="$(git rev-parse --show-cdup)" && cd "${cdup:-.}"
——show- topllevel是最近才添加到git rev-parse的吗?为什么没有人提到它?
从git rev-parse手册页:
--show-toplevel
Show the absolute path of the top-level directory.
Yes:
git rev-parse --show-toplevel
如果你想更直接地复制Mercurial命令,你可以创建一个别名:
git config --global alias.root 'rev-parse --show-toplevel'
现在git根和hg根一样。
注意:在子模块中,这将显示子模块的根目录,而不是父存储库。如果您使用的是Git >=2.13或更高版本,有一种方法可以让子模块显示超级项目的根目录。如果你的git比这更老,请参阅另一个答案。