TTaJTa4
TTaJTa4

Reputation: 840

How to check if the current repository is the top level git repo

I'm trying to check if the current repo is not a submodule but the top level git repository. I have tried the following command: git submodule init

Output:

You need to run this command from the toplevel of the working tree.

But it will init the submodule. How can I check the current repository if it isn't a submodule but the top level git repository, without making a change in the repository?

Upvotes: 4

Views: 2515

Answers (2)

VonC
VonC

Reputation: 1326932

If you do use git rev-parse --show-superproject-working-tree, make sure to use Git 2.20 (Q4 2018), in order to avoid the error message "returned path string doesn't match cwd"

See commit c5cbb27 (27 Sep 2018) by Sam McKelvie (sammck).
(Merged by Junio C Hamano -- gitster -- in commit d152a74, 19 Oct 2018)

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.

(That was first reported here)

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.

Upvotes: 2

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84403

You probably want git rev-parse --show-superproject-working-tree, with a fallback to git rev-parse --show-toplevel if you aren't in a submodule. For example:

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

I'm not currently aware of a builtin that provides an all-in-one answer for both situations.

Upvotes: 3

Related Questions