如何检查当前仓库是否为顶级git仓库

4
我正在尝试检查当前仓库是否不是子模块,而是顶层git仓库。我尝试了以下命令:git submodule init 输出:
You need to run this command from the toplevel of the working tree.

但是它将初始化子模块。如果当前的仓库不是子模块而是顶层git仓库,我该如何检查它,而不需要在仓库中进行更改?


可能是一个重复问题,参考有没有一种方法可以通过一个命令获取git根目录? - Todd A. Jacobs
2个回答

3

如果你不在子模块中,你可能需要使用 git rev-parse --show-superproject-working-tree 命令,否则可以回退到 git rev-parse --show-toplevel 命令。例如:

toplevel=$(git rev-parse --show-toplevel)
superproject=$(git rev-parse --show-superproject-working-tree)

if [[ -z "$superproject" ]]; then
    echo "submodule in $superproject"
else
    echo "toplevel is $toplevel"
fi

目前我不知道是否有一个内置的工具可以同时解决这两种情况。


git rev-parse --show-superproject-working-tree 没有返回任何输出,这正常吗? - alper
1
@alper 假设您拥有最新版本的Git,标志文档中说(强调我的):“显示超级项目工作树的根目录的绝对路径(如果存在),该超级项目使用当前存储库作为其子模块。如果当前存储库未被任何项目用作子模块,则不输出任何内容。”因此,没有输出可能是正确的结果。 - Todd A. Jacobs

2
如果您使用git rev-parse --show-superproject-working-tree命令,请确保使用Git 2.20(2018年第4季度)以避免出现错误消息“returned path string doesn't match cwd”。
请参见提交 c5cbb27(由Sam McKelvie(sammck于2018年9月27日提交)。 (由Junio C Hamano -- gitster --提交 d152a74中合并,于2018年10月19日)

rev-parse: --show-superproject-working-tree should work during a merge

Invoking 'git rev-parse --show-superproject-working-tree' exits with

"fatal: BUG: returned path string doesn't match cwd?"

when the superproject has an unmerged entry for the current submodule, instead of displaying the superproject's working tree.

这是最初在这里报道的

The problem is due to the fact that when a merge of the submodule reference is in progress, "git ls-files --stage —full-name <submodule-relative-path>" returns three seperate entries for the submodule (one for each stage) rather than a single entry; e.g.,

$ git ls-files --stage --full-name submodule-child-test
160000 dbbd2766fa330fa741ea59bb38689fcc2d283ac5 1       submodule-child-test
160000 f174d1dbfe863a59692c3bdae730a36f2a788c51 2       submodule-child-test
160000 e6178f3a58b958543952e12824aa2106d560f21d 3       submodule-child-test

The code in get_superproject_working_tree() expected exactly one entry to be returned;
this patch makes it use the first entry if multiple entries are returned.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接