Skip to content

从 SVN 迁移到 Git,并保留历史记录

本文介绍了借助 git-svn 工具将仓库从 SVN 迁移到 Git 过程,并且保留历史记录。

1. 准备工作

  • SVN 仓库和用户:用户应具有读取权限
  • GitLab 仓库和 Owner用户:创建好空的仓库备用
  • 操作主机:用于安装迁移工具和执行命令,支持 macOS 或 Ubuntu 系统

2. 安装工具

Git 官方提供的一个工具 git-svn,它提供的克隆命令可以完整地保留提交历史记录。

根据你的操作系统选择对应的安装命令:

bash
# macOS
brew install git git-svn

# Debian/Ubuntu
apt install -y git git-svn

安装完成后,可通过以下命令验证安装版本:

bash
git svn --version

输出示例:

git-svn version 2.51.0 (svn 1.14.5)

3. 克隆 SVN 仓库

使用 git svn clone 命令拉取 SVN 仓库代码:

bash
git svn clone http://svn.company.com/project

根据提示输入 SVN 用户名和密码,执行过程中的日志输出示例:

Initialized empty Git repository in /opt/project/.git/
...
Checked Ahrough pom.xml
	A	src/main/java/com/company/apex/web/controller/SystemController.java
	A	src/main/java/com/company/apex/web/controller/UploadController.java
	A	src/main/java/com/company/apex/web/util/UserUtil.java
	A	src/main/java/com/company/apex/web/util/SQLInjectUtil.java
	... 省略部分输出
r20895 = 3fae179d110506255aa151f03b1792ff7d6b8349 (refs/remotes/git-svn)
	... 省略部分输出
r20898 = 6f01370331cba400568e8db2370a30cb190e06f9 (refs/remotes/git-svn)
Checked out HEAD:
  http://svn.company.com/project r20898

优化建议:如果 SVN 仓库历史记录过多导致克隆耗时过长,可以使用 -r 参数指定起始版本号,只拉取指定版本之后的提交记录:

bash
git svn clone -r20000:HEAD http://svn.company.com/project

4. 检查日志、分支和标签

  1. 查看日志
bash
$ git log
commit 28f7e8dbe353d191d43027e9b422544b0a236be3 (HEAD -> main, git-svn)
Author: wangchunming <wangchunming@01958c64-bb14-db4b-96b0-55b2ffb2332e>
Date:   Fri Feb 28 09:37:52 2025 +0000

    xss问题解决

    git-svn-id: http://svn.company.com/project/trunk@20908 01958c64-bb14-db4b-96b0-55b2ffb2332e

commit 332d41e1fe31b3092d6fe676cdf071ab6b0586f1
Author: liujianan <liujianan@01958c64-bb14-db4b-96b0-55b2ffb2332e>
Date:   Fri Feb 28 09:30:39 2025 +0000

    解决 字典xss漏洞

    git-svn-id: http://svn.company.com/project/trunk@20907 01958c64-bb14-db4b-96b0-55b2ffb2332e

commit 39304a27237ffcec6501814e9a475d3dbbc02212
Author: yanjunfeng <yanjunfeng@01958c64-bb14-db4b-96b0-55b2ffb2332e>
Date:   Fri Feb 28 08:46:42 2025 +0000
  1. 查看分支和标签
# 查看分支
git branch --all
# 查看Tag
git tag

4. 推送到 GitLab

把下面命令中的地址替换为 GitLab 新仓库地址,然后执行命令

bash
git remote add origin http://gitlab.company.com/project
git push -u origin main

重要提醒:迁移完成后,建议及时将旧的 SVN 仓库设置为只读状态,避免数据不一致。

5. 常见问题与解决方案

5.1 用户信息显示问题

问题描述:GitLab 中可以看到 SVN 提交的作者名称,但点击用户链接无法查看用户详细信息。

原因分析:SVN 提交记录中仅包含用户名,而 Git 提交需要用户名和邮箱地址的完整信息。

解决方案:使用 git svn clone 命令的 --authors-file 参数,指定用户映射文件。

创建用户映射文件(如 authors.txt),格式如下:

zhangsan = 张三 <[email protected]>
lisi = 李四 <[email protected]>

然后重新执行克隆命令:

bash
git svn clone --authors-file=authors.txt http://svn.company.com/project

5.2 增量同步问题

问题描述:迁移完成后,如果 SVN 仓库中有新的提交,如何同步到 GitLab?

解决方案:使用以下命令进行增量同步:

bash
git svn rebase
git push origin main

5.3 对比 .svn 和 .git 目录大小

本次迁移的这个仓库文件数量共2099个,文件夹596个,最大修订号 20908。从SVN 克隆下来是154MB, .svn 占用 78.0 MB; 切换到 Git 以后,克隆下来是97.3MB , .git 占用仅为20.4MB; 此场景下,.svn 大约是 .git 大小的 4 倍。

总访问量
总访问人数 人次