How to find last git commit before a merge
If you have already merged branch
into master
, here is one way to find the merge commit :
# With the ancestry-path option, 'git rev-list branch..master' (or git log)
# will only list commits which are parents of 'master'
# *and* children of 'branch'
#
# If 'branch' was merged into 'master', the last commit in this list
# is the merge commit :
$ git rev-list --ancestry-path branch..master | tail -1
The state of master
before the merge is this commit's first parent :
$ h=`git rev-list --ancestry-path branch..master | tail -1`
$ git log $h^
Here's a programmatic solution. We query for the following to get the hash of the previous master commit before the merge happened:
git merge-base master master~1
If the last PR is a merge, then master~1
belongs to the PR. merge-base
get the common ancestor's SHA which will be the previous master commit due to how PR is structured.
If the last PR is a squash, then master~1
is on master and is what we want. Since master~1
is a parent commit of master
this time, git merge-base master master~1
get the common ancestor and so correctly return the SHA of master~1
.
With the SHA, we can get other details of the commit with git log
etc.
Observe that this might not give us the last master commit if there are many PR merges without firstly rebasing to latest master. However, this is consistent with what the OP wanted, which is last master commit before merge.
The quick way to determine commit after merge occured is to use the reflog.
Assuming that last occured operation was a merge, then:
git log HEAD@{1} -1
HEAD@{1}
refers to the previous HEAD before the last operation, so you can address it using log and reflog.
git log
will show you sequence of the commits in the current branch, so after a merge it always will be a merge commit, and right before it will be commits from the merged branch. git reflog
shows the sequence of operations in your repository (for example merge, rebase). As explained in the docs:
Reference logs, or "reflogs", record when the tips of branches and other references were updated in the local repository. Reflogs are useful in various Git commands, to specify the old value of a reference.
A quick way to do this is to type
git log --pretty=format:'%h : %s' --graph
then just follow down the graph on the right hand side till you find the merge point. You can also do
git log --pretty=format:'%h : %s' --graph > temp.txt
which puts the output into a file, temp.txt
, that which you can open in your editor and use the search facility to look for text like merge.
This approach is useful to answer lots of other questions about the lineage of your latest commit so have put
alias git_graph="git log --pretty=format:'%h : %s' --graph"
in my .bash_profile
file so I can just use ```git_log`` to see this information.