Rebase 练习项目
你将构建什么
仓库哪里主要有 高级之后你的 feature 分支是 创建. 你将 rebase 你的 feature 提交 on 顶部的 新主要, producing linear history.
学习目标
- 创建 divergent 分支场景
- Rebase feature 分支到 更新主要
- Compare rebase history 使用合并 history
- 理解当 rebase 是 appropriate 对比合并
前置要求
- git 分支, 合并, 提交 (分支 Workflow Simulation)
步骤
- 1
设置 divergent 分支
创建仓库, 制作提交 on 主要, 分支 off, 然后 advance 两者都主要 and feature 分支 independently. 这个创建 divergence.
代码mkdir rebase-practice cd rebase-practice git init echo "base" > file.txt git add . git commit -m "Base commit" git checkout -b feature echo "feature change" >> file.txt git commit -am "Add feature change" git checkout main echo "main update" >> file.txt git commit -am "Update on main"预期结果
主要 and feature 每个有 提交 other 做不.
- 2
View divergent history
Use git log --图到 see 如何分支 diverged. history shows Fork 哪里 feature and 主要 went separate 方式.
代码git log --oneline --graph --all预期结果
图 showing 主要 and feature diverging 从基础提交.
- 3
Rebase feature 到主要
切换到 feature and rebase 到主要. 这个 replays 你的 feature 提交 on 顶部的 主要's latest 提交, 创建 linear history.
代码git checkout feature git rebase main git log --oneline --graph --all预期结果
feature 提交现在 sits on 顶部的 主要's 提交 — linear history.
提示
如果 conflict occurs, resolve 它, git 添加, and git rebase --continue.
- 4
Compare 使用合并方法
Reset feature 分支 and try 合并相反的 rebasing. Compare two histories 到 see difference: 合并创建合并提交, rebase 做不.
代码# Reset feature to pre-rebase state (for comparison) git reset --hard ORIG_HEAD # Merge instead git checkout main git merge feature --no-ff git log --oneline --graph --all # Note the merge commit that rebase would not have created预期结果
合并 history shows 合并提交; rebase history 是 linear.
- 5
验证仓库状态
使用 git status 和 git log 确认当前仓库状态干净、提交历史符合预期。在执行任何破坏性操作前,先看清当前状态是 Git 的最佳实践。
代码git status # Should show: nothing to commit, working tree clean git log --oneline -5 # Review the last 5 commits to confirm history git branch -v # List branches with last commit info预期结果
git status 显示工作树干净;git log 显示预期的提交历史。
自己动手试试
你学到了什么
你练习 rebasing feature 分支到 更新主要 and compared linear history 使用合并's 合并-提交 history. Rebase gives cleaner history 但 rewrites 提交 — use 它 for 局部分支, 合并 for shared 分支.
相关资源
相关课程
- git rebase
学习 rebase, conflicts, and abort.
相关速查表
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。