Git仓库的多个子目录独立成一个新仓库

需求描述

我有一个仓库AAA,目录结构如下:

1
2
3
4
5
6
7
8
$ tree
├── .git
├── common-api
├── commons-pojo
├── commons-utils
├── account
└── payment
└── product

现在我需要把common-api、commons-pojo、commons-utils独立为一个新仓库xxx-common
从网上找到可以用”git filter-branch”和”git subtree split”两种方式独立目录为仓库,但是”git subtree split”只能独立一个目录为仓库,如果需要独立多个目录为仓库需要使用”git filter-branch”。

实施步骤

1. Clone原有仓库到本地

1
git clone git@192.168.0.xxx:test/AAA.git

2. 在本地创建需要保留的分支

下面示例中保留了dev和feature_20190516_xxx_aaa_bbb

1
2
git checkout -b dev origin/dev
git checkout -b feature_20190516_xxx_aaa_bbb origin/feature_20190516_xxx_aaa_bbb

3. 取消远程库的关联

1
git remote rm origin

4. 删除所有tag

需要删除所有的tag,否则会出错

1
git tag -l | xargs git tag -d

5. 保留需要的目录和git历史

把”GIT_COMMIT –”后面的目录改为自己需要保留的

1
2
git filter-branch -f --prune-empty --index-filter \
'git rm --cached -r -q -- . ; git reset -q $GIT_COMMIT -- commons-api commons-pojo commons-utils' -- --all

6. 清理仓库并减小体积

1
2
3
4
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

7. 关联到新的远程库(空仓库),并推送代码到远端

1
2
3
4
git remote add origin git@192.168.0.xxx:test/xxx-common.git
git push -u origin master
git push -u origin dev
git push -u origin feature_20190516_xxx_aaa_bbb
  • Copyrights © 2018-2024 李一
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信