Git 断根创建新仓库并迁移到 Gitea#
背景#
场景:
- 原仓库历史较长,不希望保留全部提交历史
- 希望从某个历史 Commit 开始作为新的仓库起点
- 保留该 Commit 对应的代码状态
- 后续提交继续保留(通过 Cherry-pick)
- 最终推送到 Gitea 新仓库
例如:
A → B → C → D(a13ad8e0) → E → F → Gtext目标:
INIT → E' → F' → G'text其中:
INIT为新的根提交- 历史从
a13ad8e0开始重建 - 丢弃
a13ad8e0之前的所有历史
1. 切换到目标 Commit#
例如:
git checkout a13ad8e0bash此时会进入 Detached HEAD 状态:
HEAD is now at a13ad8e0 ...text这是正常现象。
2. 创建 Orphan 分支#
创建一个没有任何历史的新分支:
git checkout --orphan gitea-fastpixelbash或者:
git switch --orphan gitea-fastpixelbash检查状态:
git statusbash正常会看到:
On branch gitea-fastpixel
No commits yet
Changes to be committed:
new file: ...text说明:
- Git 历史为空
- 工作区内容来自
a13ad8e0 - 所有文件准备作为新的初始提交
3. 创建新的根提交#
提交当前代码:
git commit -m "feat: init fastpixel"bash如果 Pre-commit 修改了文件:
git add .
git commit -m "feat: init fastpixel"bash如果被大文件检查拦截:
SKIP=check-added-large-files git commit -m "feat: init fastpixel"bash验证:
git log --onelinebash此时应该只看到:
xxxxxxxx feat: init fastpixeltext这就是新的根提交。
4. Cherry-pick 后续提交#
原分支:
1d7b8003
917000a4
88096330
656ecc94
a4c4b2ef
b2da68d7
9b9e9e2d
be07d678
5ac51f63
a13ad8e0text查看需要同步的提交:
git log --oneline --reverse a13ad8e0..fastpixelbash结果:
5ac51f63
be07d678
9b9e9e2d
...
1d7b8003text执行:
git cherry-pick a13ad8e0..fastpixelbash等价于:
Cherry-pick:
5ac51f63
be07d678
9b9e9e2d
...
1d7b8003text不包含:
a13ad8e0text因为它已经作为新的根提交存在。
5. 处理冲突#
如果出现冲突:
查看状态:
git statusbash解决冲突后:
git add .
git cherry-pick --continuebash放弃整个过程:
git cherry-pick --abortbash6. 修改主分支名称#
Gitea 推荐使用 main:
git branch -m mainbash验证:
git branchbash输出:
* maintext7. 创建 Gitea 仓库#
在 Gitea 中创建新仓库:
Repository Name:
fastpixeltext推荐配置:
Object Format: SHA-1text不要勾选:
☐ README
☐ License
☐ .gitignoretext保持空仓库。
8. 保留公司远程仓库#
查看当前 Remote:
git remote -vbash例如:
origin ssh://company.gittext改名:
git remote rename origin companybash验证:
git remote -vbash结果:
company ssh://company.gittext9. 添加 Gitea Remote#
例如:
git remote add origin git@gitea.home:clloz/fastpixel.gitbash验证:
git remote -vbash结果:
company ssh://company.git
origin git@gitea.home:clloz/fastpixel.gittext10. 推送到 Gitea#
首次推送:
git push -u origin mainbash成功后:
Branch 'main' set up to track remote branch 'main'text11. 验证历史#
查看完整历史:
git log --oneline --graph --decoratebash结果类似:
* 1d7b8003 refactor: ...
* 917000a4 docs: ...
* 88096330 build: ...
...
* xxxxxxxx feat: init fastpixeltext确认:
- 旧历史已断开
- 保留指定 Commit 之后的提交
- Gitea 仓库历史干净
常用命令#
查看将要 Cherry-pick 的提交#
git log --oneline a13ad8e0..fastpixelbash按时间顺序:
git log --oneline --reverse a13ad8e0..fastpixelbash查看所有分支关系#
git log --oneline --graph --decorate --allbash删除错误创建的分支#
git branch -D gitea-fastpixelbash取消暂存#
git rm --cached -r .bash仅移除暂存区,不删除文件。
最终流程#
git checkout a13ad8e0
git checkout --orphan gitea-fastpixel
git commit -m "feat: init fastpixel"
git cherry-pick a13ad8e0..fastpixel
git branch -m main
git remote rename origin company
git remote add origin git@gitea.home:clloz/fastpixel.git
git push -u origin mainbash