Git 的进阶认识 & 操作场景
2019-02-13· 15min
#git stash 场景
# 常规使用
$ git stash # 保存当前的修改并恢复工作目录到干净状态
$ git stash list # 查看存储的更改
$ git stash apply # 恢复存储的更改
$ git stash drop # 删除存储的更改
$ git stash pop # 恢复并删除存储的更改
# 场景:暂存当前分支进度 & 切换分支 & 恢复
# 1. 暂存当前 original-branch 分支代码
$ git stash
# 2. 切换到 fix-branch 分支
$ git checkout <fix-branch>
# Fix the bug...
$ git commit -m "fix: fix xxx" && git push origin fix-branch
# 3. 切回 original-branch 分支
$ git checkout <original-branch>
# 4. 恢复一开始的暂存代码
$ git stash pop
#git cherry-pick 场景
# 场景:合并 feat 分支某 commit 到 main 分支 {#git-commit-cherry-pick}
$ git checkout main
$ git cherry-pick <commit-hash>
$ git commit -m "Your commit message"
$ git push origin main
# 遇到冲突时:
$ git cherry-pick --continue
$ git cherry-pick --abort
#git cherry 场景
# 场景:查看 feat 分支与 main 分支 的commit区别
$ git cherry main
# feat 分支上有两个提交(1d3b8d6 和 4a7e2f3)不在 main 分支上
# main 分支上有一个提交(9c7d1b4)不在 feat 分支上
+ 1d3b8d6
+ 4a7e2f3
- 9c7d1b4
#git rebase -i 场景
# 常规使用
$ git rebase -i <commit-hash>
# 场景:快捷 dd 剪切一行,快捷 p 粘贴
$ git rebase -i 9dc03a7
pick 9a1026f feat: add xx component
pick 701bc7b docs: update txt
# Rebase 9dc03a7..701bc7b onto 9dc03a7 (2 commands)
#
$ :wq
$ git push origin main
# 遇到冲突时:
$ git rebase --continue
#git commit --amend 场景
# 场景一:修改 commit msg
$ git commit --amend
# ....修改 commit 信息
$ git push orign main
# 场景二:添加文件并修改 commit msg
$ git add <file>
$ git commit --amend
# ....修改 commit 信息
$ git push orign main
# 场景三:添加文件,不修改 commit msg
$ git add <file>
$ git commit --amend --no-edit
$ git push orign main
#git rebase、merge 对比
- merge合并分支时会新增一个 merge commit,然后将两个分支的历史联系起来(历史记录相对冗余)
- rebase将整个分支移动到另一个分支上,有效地整合了所有分支上的提交。(历史记录相对清晰,无多余 merge commit)
#git reset、revert 对比
- reset用于回退版本,可以遗弃不再使用的提交
# 常规使用
$ git reset <commit-hash>
--mixed(默认):仅暂存区变化
--hard参数:工作区也会变化
--soft:暂存区和工作区都不会变化
# ⚠️ 高危操作
# 场景:强制覆盖恢复线上某个 Commit
$ git reset --hard e450d05
$ git push origin main --force
- revert撤销某次操作,保留原来的更改(原 commit 依然会保留 history),用一个新的提交来实现撤销
#git pull、fetch 对比
- git pull从远程仓库获取最新版本再与本地分支 merge,即git pull=git fetch+git merge
#git tag 场景
# 场景一:新建 tag
$ git tag v1.0.15
v1.0.15
$ git push origin v1.0.15
# 场景二:删除本地 & 远端 tag
$ git tag -d v1.0.15
$ git push origin -d v1.0.15