6

Git仓库迁移实操(附批量迁移脚本) - 北鱼扶摇

 1 year ago
source link: https://www.cnblogs.com/xxcbdhxx/p/how-to-migrate-git-repository-with-command-line.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

最近公司组织架构调整,整个组换到新部门,需要将原来组内的项目代码,全部迁移到新的 group 中去(公司用的 gitlab 服务器),要求保留所有的提交记录、分支和标签。

我当然知道 Gitlab 本身是支持创建仓库时通过链接导入的,但前提是管理员开启相关功能。我们此处只讲命令迁移方案。

本文同步发布于个人网站 https://ifuyao.com

一、迁移命令

命令迁移有三种方案。

1. 直接PUSH

  1. 保证本地仓库最新
# 若本地没有仓库,则直接 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

可以将源端仓库,镜像克隆到本地,再镜像推送到目的端。

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

若对您有用,请一键三连(点赞、收藏、转发),谢谢!

本文已独家授权给公众号 逻魔代码 ,未经允许,禁止转载!


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK