Git变基

1. 场景

在用Git托管代码时发现之前的代码提交记录里有隐私信息配置,代码仓库又是公开的,因此需要修改以往的提交记录里的代码进行信息覆盖,以下解决方法用到的是rebase变基。

2. clone代码

1
2
3
4
5
6
7
8
git clone #仓库链接(当前状态为私仓)
git checkout frontend
git checkout main
git merge frontend
git branch -d frontend
git remote -v
git remote rm origin
git remote add origin https://github.com/Solar-Rain-Git/public-user-center.git

3. 变基

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 1. 创建临时分支
git checkout -b temp-branch

# 2. 启动交互式 rebase
git rebase -i HEAD~6

# 3. 在编辑器中,将需要修改的提交从 pick 改为 edit,然后保存并退出

# 4. 修改文件并提交
# 修改文件
git add <修改的文件>
git commit --amend --no-edit

# 5. 继续 rebase
git rebase --continue

# 6. 切换回主分支并合并
git checkout main
git merge temp-branch

# 7. 删除临时分支
git branch -d temp-branch

# 8.执行1-7步,在第3步删除变基前的提交记录即可

4. 撤销变基

1
2
3
4
5
# 查看 reflog
git reflog

# 重置到变基前的提交
git reset --hard #hash值