将仓库进行完整迁移
一、git操作基础命令
# 查看远程仓库地址
git remote -v
# 添加远程仓库
git remote add [远程仓库别名] <远程仓库URL>
# 修改指定远程仓库的push地址
git remote set-url --push <远程仓库别名> <远程仓库URL>
二、仓库迁移
命令迁移有三种方案。
1. 直接PUSH
# clone 仓库到本地
$ git clone git@host:group1/repo.git && cd repo
# 拉取分支和标签
$ git pull && git pull --tags
# 设置源
$ git remote set-url origin git@host:group2/repo.git
# 推送分支和标签
$ git push && git push --tags
2. 镜像
可以将源端仓库,镜像克隆到本地,再镜像推送到目的端。
$ git clone --mirror git@host:group1/repo.git
$ git push --mirror git@host:group2/repo.git
3. 裸仓库
可以将源端仓库,克隆下来裸仓库,再镜像推送到目的端。
$ git clone --bare git@host:group1/repo.git
$ git push --mirror git@host:group2/repo.git
裸仓库是 git 中的一个概念,只要在克隆时加一个 -–bare 选项即可。裸仓库可以再次push到另一个源,所以可以完成我们仓库迁移的任务。
需要注意,克隆下来的裸仓库中只有 .git 内容,是没有工作目录的。这是不同于镜像仓库的地方。
三、批处理脚本
我们需要迁移的项目有几十个,所以我这边写了个简单的批处理脚本,在此也也分享给有需要的伙伴。
输入文件 repos.txt
中按行写入要迁移的仓库名称:
repo1
repo2
repo3
Linux/MacOS 迁移脚本 migrate.sh
#!/bin/bash
remote_old=git@host1:group1
remote_new=git@host2:group2
while read repo
do
echo $repo
git clone --bare "$remote_old/${repo}.git"
cd "${repo}.git"
git push --mirror "$remote_new/${repo}.git"
cd ..
rm -fr "${repo}.git"
done < repos.txt
Windows 迁移脚本 migrate.bat
@echo off
set remote_old=git@host1:group1
set remote_new=git@host2:group2
set input_file=repos.txt
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ %input_file%"`) do (
call :process %%a
)
goto :eof
:process
SETLOCAL EnableDelayedExpansion
set "repo=!%1!"
set "repo=!repo:*:=!"
echo !repo!
git clone --bare "%remote_old%/!repo!.git"
cd "!repo!.git"
git push --mirror "%remote_new%/!repo!.git"
cd ..
rmdir "!repo!.git"
ENDLOCAL
goto :eof