问题
I'm working with some old code that makes use of Git submodules. The code has several divergent branches which are actively being used, and each of these branches depends on unfortunately a different revision of the relevant submodules; this has made development extremely complicated. One of the problems I face is that, when I switch between branches from e.g. master
to newfeature-foo
using git checkout newfeature-foo
, the state of the submodules remains at that of master
, which often causes compile errors and even worse can cause differences in runtime behavior that wreaks havoc with user testing and general sanity.
For example, given the .gitmodules
configuration:
[submodule "robotcontroller"]
path = robotcontroller
url = https://coolrobots.com/repos/robotcontroller
branch = master
ignore = dirty
- the branch
master
at commit 77d4697 has a reference torobotcontroller @ f57d1b3
- the branch
newfeature-foo
at b38d29f has a reference torobotcontroller @ 60b27d4
- the branch
master
at 873639f doesn't have the submodulerobotcontroller
at all - the branch
newfeature-foo
at 301dca4 has a reference torobotcontroller @ bdf5991
Is there no way e.g. using Git hooks to force the automatic complete re-checking-out of all submodules listed in a .gitmodules
file when it changes on checkout of the "root" Git repository?
回答1:
post-checkout
hook that removes robotcontroller
and update all submodules.
#!/bin/sh
# post-checkout hook that update submodules
prev_HEAD="$1"
new_HEAD="$2"
new_branch="$3"
if [ "$new_branch" = 1 ]; then
if ! grep -Fq robotcontroller .gitmodules; then
rm -rf robotcontroller
fi
git submodule update
fi
exit 0
PS. The correct term for the root Git repository is "superproject". :-)
回答2:
It sounds like there are a lot of things going on in your repo that make things confusing. We could go through a lot of back-and-forth to find the settings that are conflicting, but here's what I would do:
Get rid of ignore = dirty
This just hides useful information - perhaps the submodule is not checking out cleanly because it would override files. At the very least, confirm that the submodule is clean before trying any operations on it - cd mysubmodule
and git status
= clean
来源:https://stackoverflow.com/questions/50176805/git-hook-for-updating-git-submodule-on-branch-change