一: 添加submodule
方法1
git submodule add https://git.oschina.net/gaofeifps/leg.git
这个步骤会做两件事情
step1: 克隆leg.git 到当前路径的 leg下
并且在leg下创建文件.git (注意这里的.git是文件不是目录)
打开./leg/.git
文件可以看到
gitdir: ../.git/modules/leg
他是把子模块真正的.git目录放到 父模块的.git/路径下,具体路径为.git/module/leg
路径
可以进入目录看到git对象文件。
step2: 添加.gitmodules
文件并且添加内容为
[submodule "leg"]
path = leg
url = https://git.oschina.net/gaofeifps/leg.git
step3: .git/config
添加并标注激活状态
[submodule "leg"]
url = https://git.oschina.net/gaofeifps/leg.git
active = true
方法2
直接创建子目录./svm
,
$: mkdir ./svm
$: cd ./svm
$: git init
$: touch readme
$: git add readme
$: git cm "readme added"
$: cd ../
git st
Untracked files:
(use "git add <file>..." to include in what will be committed)
svm/
git add svm
warning: adding embedded git repository: svm
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> svm
hint:
hint: If you added this path by mistake, you can remove it from the
hint: index with:
hint:
hint: git rm --cached svm
hint:
hint: See "git help submodule" for more information.
此时虽然有警告⚠️, 实际上已经讲svm添加到submdule中, 为了其他clone时能找到svm,
还需要手动修改.gitmodule
[submodule "svm"]
path = svm
url = git@xxx.remote.com.svm.git //远程仓库路径
否则你在git clone http://xxx…xxxxx…top.git以后 git submdule init, 你会发现找不到
git submodule init
fatal: No url found for submodule path 'svm' in .gitmodules
git submodule update
来更新子模块
二: 修改和跟踪
1. modifed content(子模块修改不提交)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
(commit or discard the untracked or modified content in submodules)
modified: leg (modified content)
2. new commit(子模块提交)
子module leg提交修改后,父module下git status
可以看到子模块的状态
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: leg (new commits)
git diff
可以发现父module 的git 只会记录submodule的提交变动,而不是具体的代码变动
diff --git a/leg b/leg
index b65d81d..933f558 160000
--- a/leg
+++ b/leg
@@ -1 +1 @@
-Subproject commit b65d81dad264a7b1858b4632a31486038f7d73a6
+Subproject commit 933f558ca418564202d10dd97210afeedab6478e
这时候需要git add
将子module的提交标签
3. new commit, modifed content(子模块有提交,有修改)
子module leg有新commit, 也有未提交的新修改,在父module 下 git status
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
(commit or discard the untracked or modified content in submodules)
modified: leg (new commits, modified content)
此时 git add
只会提交 submodule 的 new commits, 并不会提交未修改的内容
结论:
父模块只会跟踪子模块的commit记录,永远不会跟踪具体的文件修改
删除submodule
git rm --cached leg
递归pull
git submodule update --init --recursive