Git子模块

2014/07/11

参考文档

将项目中的子目录转换为子模块,记得先备份文件

# 先将子目录撤回
git rm -rf themes/light/
# 加入子模块
git submodule add git@github.com:mfkddcwy/hexo-theme-light.git themes/light/
# 查看状态
git status
# 提交修改
git commit -a -m 'git submodule'

# 查看状态
git submodule status

克隆一个带子模块的项目

# 初始化你的本地配置文件
git submodule init

# 从项目拉取所有数据并检出你上层项目里所列的合适的提交
git submodule update

子模块的问题

使用子模块并非没有任何缺点。首先,你在子模块目录中工作时必须相对小心。当你运行git submodule update,它会检出项目的指定版本,但是不在分支内。这叫做获得一个分离的头——这意味着 HEAD 文件直接指向一次提交,而不是一个符号引用。问题在于你通常并不想在一个分离的头的环境下工作,因为太容易丢失变更了。如果你先执行了一次submodule update,然后在那个子模块目录里不创建分支就进行提交,然后再次从上层项目里运行git submodule update同时不进行提交,Git会毫无提示地覆盖你的变更。技术上讲你不会丢失工作,但是你将失去指向它的分支,因此会很难取到。

How do I remove a Git submodule?

To remove a submodule you need to:

  1. Delete the relevant section from the .gitmodules file.
  2. Stage the .gitmodules changes git add .gitmodules.
  3. Delete the relevant section from .git/config.
  4. Run git rm --cached path_to_submodule (no trailing slash (没有斜线)).
  5. Run rm -rf .git/modules/path_to_submodule.
  6. Commit git commit -m "Removed submodule <name>".
  7. Delete the now untracked submodule files rm -rf path_to_submodule.

Via the page https://git.wiki.kernel.org/index.php/GitSubmoduleTutorial#Removal