Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
当前回答
git-config的手册页(在Alias下)说:
如果别名展开以感叹号作为前缀,则它将被视为外壳 命令。[…注意shell 命令将从存储库的顶级目录执行,这可能不是 必须是当前目录。
在UNIX上,你可以这样做:
git config --global --add alias.root '!pwd'
其他回答
从Git 2.13.0开始,它支持一个新的选项来显示根项目的路径,即使在子模块内部使用也可以工作:
git rev-parse --show-superproject-working-tree
今天必须自己解决这个问题。在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)是解决这个问题的一种方法。
“git rev-parse——git-dir”怎么样?
F:\prog\git\test\copyMerge\dirWithConflicts>git rev-parse --git-dir
F:/prog/git/test/copyMerge/.git
——git-dir选项似乎可以工作。
它甚至可以在裸库中工作,而git rev-parse——show- topllevel会触发(在裸库中)“致命:此操作必须在工作树中运行”。
从git rev-parse手册页:
--git-dir
Show $GIT_DIR if defined else show the path to the .git directory.
您可以在这个git setup-sh脚本中看到它的作用。
如果你在子模块文件夹中,Git >=2.13,使用:
git rev-parse --show-superproject-working-tree
如果你正在使用git rev-parse——show-toplevel,请确保使用的是git 2.25+ (Q1 2020)。
不管你是在git子目录下,还是在顶层,这个shell别名都有效:
alias gr='[ ! -z `git rev-parse --show-toplevel` ] && cd `git rev-parse --show-toplevel || pwd`'
更新为使用现代语法而不是反撇号:
alias gr='[ ! -z $(git rev-parse --show-toplevel) ] && cd $(git rev-parse --show-toplevel || pwd)'