Get the commit message of the latest commit of the branch that is involved into a opened pull request



The latest commit’s commit message of the branch feature/xyz is add feature xyz with SHA number 1234. The newest commit’s SHA number of the main branch is 3456.

When I push the branch feature/xyz to the repo and open a pull request from feature/xyz to main a workflow pipeline will be triggered, how can I get the commit message add feature xyz?

note: the pull request is open and not merged

name: Dev deploy

      types: [opened, reopened, edited, synchronize]

      name: deploy to dev
      runs-on: ubuntu-22.04

        - name: checkout repo
          uses: actions/[email protected]

        - name: Set env var
          run: |
            echo commit=$(git log --format=%B -n 1) >> $GITHUB_ENV

git log --format=%B -n 1 would give me something like Merge 1234 into 3456.

How can I get the commit message of the last commit from the branch feature/xyz, aka, add feature xyz in this case?


Assuming the following: The main branch contains commits "m1".."m5". The feature/xyz branch contains commits "f1".."f2", starting from "m2", e.g.

$ git log --graph --all --oneline
* 4d5b4ee (feature/xyz) f2
* 62f9a15 f1
| * 6cf050a (HEAD -> main) m5
| * f9bd7c6 m4
| * b7860f8 m3
* 39fee03 m2
* 1c1d702 m1
* e167ed6 .gitignore

then running

$ git checkout main
$ git merge feature/xyz

would create a merge commit, e.g.

$ git log --graph --all --oneline
*   7a8474a (HEAD -> main) Merge branch 'feature/xyz'
| * 4d5b4ee (feature/xyz) f2
| * 62f9a15 f1
* | 6cf050a m5

A merge commit is a commit with two (or more) parents. You probably know that you can use ^ as a postfix to a branch/commit/ref to indicate its parent, but what when there are multiple? Just a single ^ is the same as the first parent which can be explicitly specified as ^1 and correspondingly ^2 refers to the second parent.

$ git rev-parse HEAD^
$ git rev-parse HEAD^1
$ git rev-parse HEAD^2

So what you are asking for sounds like the commit message for the second parent to the merge commit which you can get by running

git show -s --format=format:%s%n%n%b HEAD^2

when the current commit is the merge commit.

I think it is a really bad idea to depend on the last commit on a feature branch to be special and contain some extra valuable commit message so I would recommend against doing this. But the above is an answer to what was asked.

Answered By – hlovdal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published