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

hg root

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


当前回答

Yes:

git rev-parse --show-toplevel

如果你想更直接地复制Mercurial命令,你可以创建一个别名:

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

现在git根和hg根一样。


注意:在子模块中,这将显示子模块的根目录,而不是父存储库。如果您使用的是Git >=2.13或更高版本,有一种方法可以让子模块显示超级项目的根目录。如果你的git比这更老,请参阅另一个答案。

其他回答

不管你是否已经在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根目录的绝对路径,比如在shell脚本中使用,使用readlink和git rev-parse的组合:

gitroot=$(readlink -f ./$(git rev-parse --show-cdup))

Git-rev-parse——show-cdup给出正确的“..”’s to get 从你的cwd到根目录,如果你在根目录,则返回空字符串。 然后“prepend”。/"来处理空字符串大小写并使用 Readlink -f转换为完整路径。

你也可以在PATH中创建一个git-root命令作为shell脚本来应用这个技术:

cat > ~/bin/git-root << EOF
#!/bin/sh -e
cdup=$(git rev-parse --show-cdup)
exec readlink -f ./$cdup
EOF
chmod 755 ~/bin/git-root

(上面的代码可以粘贴到终端中创建git-root并设置执行位;实际的脚本在第2、3和4行。)

然后你可以运行git root来获得当前树的根。 注意,在shell脚本中,使用“-e”使shell在rev-parse失败时退出,这样如果不在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配置全局别名。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