Extracting Commit Messages in GitHub Actions Workflow

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:

In this workflow:

  1. The actions/checkout@v2 action checks out your repository onto the runner, so the git commands can interact with your code.
  2. 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 tells git log to print only the commit message, and -n 1 limits the log to the last commit.
  3. The echo "COMMIT_MSG=$commit_message" >> $GITHUB_ENV command writes the commit message to the COMMIT_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.