关于git中submodule的使用

About the use of submodule in git

因为怕博客数据丢了,所以把整个hexo项目文件夹都做成了一个git仓库。
项目结构如下

.
├── _config.yml等其他文件和文件夹
├── themes
|   └── hexo-theme-butterfly
└── public

但是项目中的 themes/hexo-theme-butterfly 作为主题,引用的是他人的项目。
public 作为最终静态页面的根目录也想做一个区分。
所以将他们都做成了git中的submodule

add submodule

git submodule add <repository-url> <submodule-path>

这个命令的运行结果可以概况为两种:
1.如果本地还没有这个 <repository-url> 的仓库,那么结果就是拉取了这个仓库,和 git clone 的区别就是这个仓库是作为一个 submodule 存在于主仓库。
2.如果本地已经存在,那么就是为主仓库添加了一个submodule

运行之后查看 status ,发现暂存区中多了两行,显示是添加后的项目文件夹和 .gitmodules

.gitmodules
submodule-path

这个过程中我还遇到过一个问题,如果这个本地仓库已经存在,并且已经被 track。那么直接使用 git submodule add 是无法添加的。

yuki@Linux:~/yuki_blog$ git submodule add <repository-url> <submodule-path>
fatal: 'submodule-path' already exists in the index

需要先 git rm -r --cached <submodule-path> ,再进行一次 git submodule add
当然,最后从能见的文件中可以看出的区别只有 .gitmodules 的内容不同。
如果直接更改 .gitmodules 的文件内容是否会可以在已经存在本地子仓库的情况下直接添加 submodule 我并没有尝试过。不过我也不建议如此尝试。

.gitmodules file format

贴一下 .gitmodules 的文件格式

[submodule "submodule-path-1"]
path = submodule-path-1
url = repository-url-1

[submodule "submodule-path-2"]
path = submodule-path-2
url = repository-url-2
branch = the branch you specify

关于 branch 行,如果你直接使用

git submodule add <repository-url> <submodule-path>

那么文件中不会有 branch 这一行。
但是如果你指定

git submodule add -b <specify branch> <repository-url> <submodule-path>

那么文件较上一条命令会出现这一行

branch = specify branch

如果克隆/拉取的主仓库中有子模块怎么办

直接 git clnone 或者 git pull 一个仓库时,并不会把它的子模块的文件也下载到本地。
这个时候可以在本地主仓库的目录下

1
2
git submodule init
git submodule update

第一个命令 git submodule init 用于初始化子模块
而第二个命令 git submodule update 用于下载并更新子模块的内容。

to be continued

未完待续

官方忠告

hint: You've added another git repository inside your current repository.
hint: Clones of the outer repository will not contain the contents of
hint: the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use:
hint:
hint:   git submodule add <url> .deploy_git
hint:
hint: If you added this path by mistake, you can remove it from the
hint: index with:
hint:
hint:   git rm --cached .deploy_git
hint:
hint: See "git help submodule" for more information.

有什么问题去看官方文档就好了呀(误)

参考

https://git-scm.com/book/zh/v2/Git-%E5%B7%A5%E5%85%B7-%E5%AD%90%E6%A8%A1%E5%9D%97
https://blog.csdn.net/wujakf/article/details/118333487
https://blog.csdn.net/guotianqing/article/details/82391665
https://iphysresearch.github.io/blog/post/programing/git/git_submodule/
https://www.jianshu.com/p/9000cd49822c

Licensed under CC BY-NC-SA 4.0
Sow nothing, reap nothing.
Built with Hugo 主题 StackJimmy 设计