第一步:创建远程独立的空仓库
在Git服务器端操作:
git init --bare <GIT仓库绝对路径>
chown -R git:git <GIT仓库绝对路径>
示例:
git init --bare /home/myRepo/test_sub.git
chown -R git:git /home/myRepo/test_sub.git
第二步:克隆需要拆分的git仓库testing.git
git clone http://192.168.2.23:9080/gerrit/p/testing.git
第三步:将testing.git仓库中的test_sub 剥离为temptest_sub
cd testing
git subtree split -P test_sub -b temptest_sub
注意:运行后,git 会遍历原仓库中所有的历史提交,挑选出与指定路径相关的 commit 并存入名为 name-of-new-branch 的临时分支中。另外需要注意的是,如果你在使用 Windows,且该文件夹深度 > 1,你必须使用斜杠 / 作为目录分隔符而不是默认的反斜杠 \。
第四步:在本地创建一个新的 git 仓库并做初始化:
cd ..
mkdir test_sub
cd test_sub
git init
第五步:把原仓库中的临时分支拉到新仓库中:
git pull ../testing temptest_sub
第六步:清理.git的object
git reset --hard
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --aggressive --prune=now
第七步:将新的本地仓库推送到远端
cd到<new-repo>
cd sub_module
(1)添加远端地址:
git remote add origin <new-git-url>
git remote add origin git@192.168.2.108:/home/myRepo/test_sub.git
(2)推送到远端:
git push -u origin master
或者以推关仓库镜像方式推送到远程
git push --mirror git@192.168.2.108:/home/myRepo/test_sub.git
第八步:克隆新提交和仓库并查看log
cd ..
rm -rf test_sub
git clone git@192.168.2.108:/home/myRepo/test_sub.git
cd test_sub
git log
补充资料:
清除目录或文件同时删除相关的commit日志记录
例如
1、删除testing仓库中的test_sub目录
git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch testing/test_sub' --prune-empty --tag-name-filter cat -- --all
1、删除testing仓库中的test_sub目录中a.txt文件
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch testing/test_sub/a.txt' HEAD
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now
git push --all --force