如何优雅迁移 Git 仓库 ( 包含所有分支 )

460 阅读1分钟

最近需要批量将仓库内网迁移到外网,三步走即可完成!

第一步:

git clone --bare old_repository_url

--bare
Make a bare Git repository. That is, instead of creating  `<directory>`  and placing the administrative files in  `<directory>/.git` , make the  `<directory>`  itself the  `$GIT_DIR` . This obviously implies the  `--no-checkout`  because there is nowhere to check out the working tree. Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping them to  `refs/remotes/origin/` . When this option is used, neither remote-tracking branches nor the related configuration variables are created.

执行完毕之后会在当前的目录下生成 xxx.git 目录文件,进入该目录

第二步

git push --mirror new_repository_url

--mirror
Instead of naming each ref to push, specifies that all refs under  `refs/`  (which includes but is not limited to  `refs/heads/` ,  `refs/remotes/` , and  `refs/tags/` ) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration option  `remote.<remote>.mirror`  is set.

执行完毕后新仓库就有了旧仓库的全量数据,包括 branchs、tags、commits ect.

第三步

git clone new_repository_url 

重新下载,或者在原有项目目录中执行

git remote set-url origin new_repository_url

踩坑指南:

git pull --all
git push --all

上面两条指令看起来也能完成,而且更优雅 ( 快捷对称 ),但实际上 " 暗藏杀机 ": 杀机1:git pull --all 仅仅是拉取所有分支,并不包含分支代码,官方说明:

--all 
Fetch all remotes.

杀机2:git push --all 确实可以把本地所有分支代码提交到远程仓库,但也会不慎把只存在本地的分支也一并提交,官方说明:

--all
Push all branches (i.e. refs under  `refs/heads/` ); cannot be used with other <refspec>.