Git闯关游戏:Learn Git Branching Level 5-1 多次Rebase

715 阅读2分钟



Level 5-1 《多次Rebase》

2022-08-18_104502.png

这一关使用git rebase做多次复制提交操作,将多个分支整理成一条连续的提交记录,不仅在游戏里学习,你还可以在真实环境中进行实验。



游戏答案:

# bugFix复制到main下面
git rebase main bugFix

# side复制到bugFix下面
git rebase bugFix side

# another复制到side下面
git rebase side another

# main移动到another
git branch -f main another



准备实验环境

下面命令完整CV到Windows cmd命令行窗口中执行:

# 准备一个空目录
mkdir level-5-1
cd level-5-1

# 初始化本地仓库,然后做三次提交
git init

echo 111>>a.txt
git add .
git commit -m "c0"
echo 222>>a.txt
git add .
git commit -m "c1"
echo 333>>a.txt
git add .
git commit -m "c2"

# 在master的上一个提交位置,创建并切换到bugFix分支,然后做一次提交
git checkout "HEAD~1" -b bugFix
echo 444>>a.txt
git add .
git commit -m "c3"


# 在bugFix前两个提交位置,创建并切换到side分支,再做三次提交
git checkout "HEAD~2" -b side
echo 555>>a.txt
git add .
git commit -m "c4"
echo 666>>a.txt
git add .
git commit -m "c5"
echo 777>>a.txt
git add .
git commit -m "c6"

# 在上一个提交位置,创建并切换到another分支,并做一次提交
git checkout "HEAD~1" -b another
echo 888>>a.txt
git add .
git commit -m "c7"

# 切换到master分支
git checkout master

# 查看提交树
git log --graph --pretty=oneline --all

image.png



真实答案:

# bugFix复制到master下面
git rebase master bugFix

image.png

按提示,需要手动解决文件冲突,然后再继续完成rebase。

image.png


# 先手动修正a.txt后再继续

# 提交后继续完成rebase
git add .
git commit --no-edit
git rebase --continue

# side复制到bugFix下面
git rebase bugFix side

与上一步相同,需要先解决文件冲突再继续。


# 先手动修正a.txt后再继续

# 提交后,继续完成rebase
git add .
git commit --no-edit
git rebase --continue

这一步复制了side分支的三个提交:c4,c5,c6

image.png

继续复制another分支:

# another复制到side下面
git rebase side another

这一步要复制another分支的三个提交:c4,c5,c7。

前面一步已经完成了c4和c5的复制,这里把c4和c5跳过,不再重复复制:

image.png


# 跳过c4,跳过后会继续复制c5提交
git rebase --skip

image.png


# 跳过c5,跳过后会继续复制c7提交
git rebase --skip

跳过这两个提交后,会继续复制c7提交,这时会出现文件冲突。

image.png

需要解决冲突后再继续完成rebase:


# 先手动修正a.txt后再继续

# 提交,然后继续完成rebase
git add .
git commit --no-edit
git rebase --continue

# 查看提交树
git log --graph --pretty=oneline --all

image.png