如何从 git 挂钩中可靠地找到根 git 目录?

How can I find the root git directory reliably from a git hook?

给定 2 git 个存储库(产品 A 和产品 B),带有子模块(CommonSubmodule、SomeOtherSubmodule)

D:\Repositories\ProductA\
D:\Repositories\ProductA\CommonSubmodule
D:\Repositories\ProductA\SomeOtherSubmodule
D:\Repositories\ProductA\SomeOtherSubmodule\
D:\Repositories\ProductB\SomeOtherSubmodule\
D:\Repositories\ProductB\CommonSubmodule\

我在网上找到了一个允许通过 post_checkout 挂钩记录分支的脚本

#!/bin/sh

previous_head_ref=
new_head_ref=
is_branch_checkout=

if [[ "$previous_head_ref" != "$new_head_ref" ]] && [[ "$is_branch_checkout" == 1 ]]; then
    branch=$(git rev-parse --abbrev-ref HEAD)
    #if [[ "develop" != "$branch" ]]; then
        path="$(dirname "[=13=]")/.."
        logfile="$path/x_branch_log"
        ts=$(date +%s)
        echo "$branch|1|$ts" >> $logfile
        echo "Logging $branch|1|$ts to $logfile"
        echo PWD is $PWD
    #fi
fi

在 post_checkout 上下文中,如何在不编码绝对路径的情况下获取根目录 (D:\Repositories),无论挂钩安装在子模块中有多深?

D:\Repositories\

此外,如何获取产品根目录,例如

D:\Repositories\ProductA\
D:\Repositories\ProductB\

根据我在 Git repo root folder 上的回答得到的评论,检查 return 的值

git rev-parse --git-dir

您可能需要迭代(如果您在父仓库的子模块的子模块中),但它应该 return 父仓库的根文件夹。