Git tips

合并最新的两个 commit

git reset --soft HEAD~
git commit --amend

合并历史中间连续若干个 commit

假设在分支 master 上有 commit 记录c1 --- c2 --- c3a --- c3b --- c3c --- c4 --- c5,现在想把c3a, c3b, c3c 三个 commit 合并为一个。可以通过以下步骤实现:
1. 创建临时分支 tmp

git checkout -b tmp
  1. 在临时分支 tmp 上回滚到 c2:
git reset --hard commit-id-of-c2
  1. 切换到 master 分支:
git checkout master
  1. master 分支 rebase 到 tmp 分支:
git rebase -i tmp

对于 c3a,c4,c5 选择 pick,而对于 c3b, c3c 选择 squash 或者 fixup
5. 删除临时分支 tmp

git branch -d tmp

取消上一条 git reset 命令

git reset HEAD@{1}

可以使用 git reflog 查看每一步操作历史

查看某次 commit 更改的文件

git show commit-id --name-only

查看某次 commit 更改的内容

git show commit-id

查看某次 commit 增删行数

git show commit-id --stat

获取远程分支

git fetch origin remote_branchname:local_branchname

忽略已跟踪文件的更改

git update-index --assume-unchanged filename

撤销上一步的忽略

git update-index --no-assume-unchanged filename

生成最近的 n 次提交的 patch

git format-patch –n

取消 git commit

vim 命令模式下输入:cq!(quit with a non-success code)

从本地删除远程分支

git push origin --delete remote_branchname

注意: Github 上也可以删除分支,查看 https://github.com/blog/1377-create-and-delete-branches

在本地删除远程已不存在的分支 upstream/tmpbranch

git fetch upstream --prune

git stash

使用情景:在当前分支 branch1 上做了修改,此时想切换到别的分支 branch2,但还不想 commit 现有的修改。具体步骤如下:
1. 保存当前更改:

git stash
  1. 切换到别的分支完成任务:
git checkout branch2
  1. 返回 branch1 分支:
git checkout branch1
  1. 恢复原来的更改:
git stash pop

注意:
– 使用 git stash list 查看现有 stash 列表
– 使用 git stash apply stash@{num} 应用第 num 个 stash

git stash 后不小心使用 git stash clear 清除了所有 stash

使用 git fsck --unreachable | grep commit 列出不可达的 commit,然后 git show 每个 commit 查看修改的内容,找到想要恢复的位置后用 git cherry-pick -m 1 <sha1> 恢复误删的 stash。

追踪代码来源

git blame filename

删除 reflog

git reflog expire --expire=now --allgit gc --prune=now

Reference

Pro Git
Git Reference
廖雪峰 Git 教程

发表评论