Extracting Commit Messages in GitHub Actions Workflow
GitHub Actions is a powerful tool for automating tasks in your software development workflow. Sometimes, it’s helpful to access the commit message within your workflow, for example, to trigger certain actions based on the contents of the commit message. In this blog post, we’ll explore how to extract the commit message in a GitHub Actions workflow.
Understanding GitHub Actions Contexts
In GitHub Actions, a “context” is a set of environmental variables and metadata about the current state of the workflow or GitHub environment. The github
context is one of these, and it contains data about the event that triggered the workflow and the workflow run itself.
The github
context provides the commit SHA that triggered the workflow in the github.sha
object. However, the commit message itself isn’t directly available as a part of the github
context, so we need a way to extract it.
Extracting the Commit Message
To retrieve the commit message, we can use git
commands within a workflow run step. We can take advantage of the fact that GitHub Actions checks out the repository and has git
available in the runner’s environment. Here’s how you can do it:
1 2 3 4 5 6 7 8 9 10 11 |
jobs: build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Get commit message run: | commit_message=$(git log --format=%B -n 1 ${{ github.event.after }}) echo "COMMIT_MSG=$commit_message" >> $GITHUB_ENV |
In this workflow:
- The
actions/checkout@v2
action checks out your repository onto the runner, so thegit
commands can interact with your code. - The
git log --format=%B -n 1 ${{ github.event.after }}
command retrieves the commit message of the commit that triggered the workflow. The--format=%B
option tellsgit log
to print only the commit message, and-n 1
limits the log to the last commit. - The
echo "COMMIT_MSG=$commit_message" >> $GITHUB_ENV
command writes the commit message to theCOMMIT_MSG
environment variable, which is then available for subsequent steps in the job.
Conclusion
While the commit message isn’t directly available in the GitHub Actions context, it’s still fairly easy to extract using git
commands. Being able to access the commit message in your GitHub Actions workflows can open up new possibilities for automating and customizing your CI/CD processes.