how to keep git submodule on-branch status after cloning superproject?

我的梦境 提交于 2019-12-07 00:33:28

For anyone else with this problem:

As the answers have stated, your submodule tracks a commit. This isn't actually an problem, a submodule represents an external dependency at a single point in time (ie, a commit) rather than an active stream of development (a branch). You manually update this dependency at your choosing (and theoretically, are only ever on Master branch)

You only really care about your branch when making commits. Committing without being on a branch makes a detached head, and it starts being easy for your team to lose its work.

I solved this at our studio by adding a pre-commit hook to reject commits if not on a branch:

#!/bin/sh

function parse_git_branch_check {
    if [[ ${branch_name} == "* (detached from "* ]]; then
        echo "********************************************"
        echo "You need to be on a branch before committing"
        echo "********************************************"
        exit 1
    else
        echo "-- You are on branch $branch_name --"
        exit 0
    fi
}
function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d'
}

branch_name=$(parse_git_branch)
parse_git_branch_check;

This hook is committed to the super repo, along with this BAT (yes, I know, sorry) script to install the hooks

REM - Create links for all submodules to our pre-commit hooks for preventing submissions without a branch

if EXIST .git\hooks\pre-commit (
    del .git\hooks\pre-commit
)
mklink /h .git\hooks\pre-commit pre-commit

FOR /F "tokens=*" %%i IN ('DIR .git\modules /A:D /b') do (
    if EXIST .git\modules\%%i\hooks\pre-commit (
        del .git\modules\%%i\hooks\pre-commit
    )
    mklink /h .git\modules\%%i\hooks\pre-commit pre-commit
)

New clones need to run the script, which is not perfect, but the closest to an automatic solution I could come up with.

Git submodules are tracked via specific commit references. Not via branches. Hence even if you are at the HEAD of master, your main project will track a specific commit from common. This is why submodules are very static in reference, and this has caused confusion and problems at times :)

This blog describes this concept fairly well.

There are different use cases for git. But for my case, the following worked for git 1.8.5.2 (and likely later). Basically, first rm the submodule completely and then add it back. Naturally, the submodules are up-to-date and on-track.

cd main
git rm common
rm -rf .git/modules/common
git submodule add -b master url_to_common.git
cd common
git status

Note, the third line rm ... is necessary because git (as of 1.8.5.2) will leave .git/modules/common in the superproject, which prevents the submodule from being added back.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!