submodule 高频使用方法
添加新的子项目
submodue
git submodule add https://github.com/githubtraining/example-submodule
git commit -m "adding new submodule"
该submodule add命令会添加一个名为的新文件.gitmodules以及一个包含来自example-submodule. 两者都添加到您的索引(暂存区)中,您只需提交它们。子模块的历史保持独立于父项目。
查看子项目的差异
submodue
查看子模块的差异:
# show changes to the submodule commit
git diff example-submodule
# show oneline log of new commits in the submodule
git diff --submodule example-submodule
# show changes to the files in the submodule
git diff --submodule=diff
使用子项目克隆存储库
submodue
要克隆存储库及其子模块:
git clone --recurse-submodules URL
如果你忘记了--recurse-submodules,你可以克隆并初始化所有子模块:
git submodule update --init --recursive
--recursive仅当任何子模块本身具有子模块时才需要添加。
引入超级项目更新
submodue
默认情况下,子模块存储库被获取,但在超级项目中运行时不会更新git pull。您需要使用 git submodule update,或将--recurse-submodules标志添加到pull :
git pull
git submodule update --init --recursive
# or, in one step (Git >= 2.14)
git pull --recurse-submodules
--init如果超级项目添加了新的子模块,--recursive 则需要,如果任何子模块本身具有子模块,则需要。
如果超级项目更改了子模块的 URL,则需要单独的命令:
# copy the new URL to your local config
git submodule sync --recursive
# update the submodule from the new URL
git submodule update --init --recursive
--recursive 仅当任何子模块本身具有子模块时才需要。
改变分支
submodue
默认情况下,子模块工作树在更改分支时不会更新以匹配超级项目中记录的提交。您需要使用git submodule update,或将--recurse-submodules标志添加到switch :
git switch <branch>
git submodule update --recursive
# or, in one step (Git >= 2.13)
git switch --recurse-submodules <branch>
引入子项目更新
submodue
# Update the submodule repository
git submodule update --remote
# Record the changes in the superproject
git commit -am "Update submodule"
如果您有多个子模块,可以在git submodule update --remote命令末尾添加子模块的路径,以指定要更新哪个子项目。
默认情况下,会将子模块更新为子模块远程分支git submodule update --remote上的最新提交。master
您可以使用以下方法更改未来调用的默认分支:
# Git >= 2.22
git submodule set-branch other-branch
# or
git config -f .gitmodules submodule.example-submodule.branch other-branch
对子项目进行更改
在大多数情况下,最佳做法是在子项目存储库的单独克隆中进行更改并将它们拉入父项目。如果这不切实际,请遵循以下说明:
submodue
访问子模块目录并创建一个分支:
cd example-submodule
git switch -c branch-name master
更改需要两次提交,一次在子项目存储库中,一次在父存储库中。不要忘记推入子模块和超级项目!
将更改推送到子项目存储库
submodue
在子模块目录中:
git commit -am ''
git push origin HEAD:<远程分支名字>
或者在父目录中:
git commit -am ''
git push --recurse-submodules=on-demand
高效配置
submodue
diff 时始终显示子模块日志:
git config --global diff.submodule log
git status在您的消息中显示子模块更改的简短摘要:
git config --global status.submoduleSummary true
将push默认设置为--recurse-submodules=on-demand:
git config --global push.recurseSubmodules on-demand
如果支持该标志,则将所有命令(除了clone)默认为(这适用于Git 2.15):--recurse-submodules``git pull
git config --global submodule.recurse true
本文详细介绍了如何使用Git管理子模块,包括添加新子项目、查看子项目差异、克隆含子模块的仓库、更新超级项目、切换分支、更新子项目以及推送更改到子项目存储库。此外,还提到了一些高效的配置设置,如在diff和status中显示子模块信息。
2068

被折叠的 条评论
为什么被折叠?



