Mercurial有一种打印根目录(包含.hg)的方法

hg root

git中是否有等价的东西来获取包含.git目录的目录?


当前回答

在Shell框架中预先配置的Shell别名

如果你使用shell框架,可能已经有一个可用的shell别名:

$ GRT in oh-my-zsh (68k) (cd $(git rev-parse——show-toplevel || echo ".")) $ git-root in prezto (8.8k)(显示工作树根的路径) $ g . .Zimfw (1k)(将当前目录更改为工作树的顶层。)

其他回答

今天必须自己解决这个问题。在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配置全局别名。exec”!Exec '允许你做像git Exec make这样的事情,因为man git-config说:

如果别名展开以感叹号作为前缀,则它将被视为shell命令。[…注意,shell命令将从存储库的顶级目录执行,而不一定是当前目录。

知道$GIT_PREFIX将是相对于存储库的顶级目录的当前目录的路径也很方便。但是,知道这只是战斗的一半。Shell变量展开使得它很难使用。所以我建议像这样使用bash -c:

git exec bash -c 'ls -l $GIT_PREFIX'

其他命令包括:

git exec pwd
git exec make
$ git config alias.root '!pwd'
# then you have:
$ git root

git-extras

添加$ git根目录 看到https://github.com/tj/git-extras/blob/master/Commands.md git-root

$ pwd
.../very-deep-from-root-directory
$ cd `git root`
$ git add . && git commit

git-extra的可用性

Homebrew (osx)/linuxbrew(linux) $ brew安装git-extras Debian /ubuntu repos (https://packages.debian.org/sid/git-extras) $ apt-get安装git-extras

在这里写一个简单的答案,这样我们就可以用

git root

要完成这项工作,只需使用

git config --global alias.root "rev-parse --show-toplevel"

然后你可能想在~/.bashrc中添加以下内容:

alias cdroot='cd $(git root)'

这样你就可以用croot到回购的顶部。