Search code examples
github-actionscicd

Github Actions - Get PR Title


I have a continuous integration workflow that I want to run

  1. on PR merges to the main branch
  2. if there's any pushes to PRs (run tests, and linting)

I also want to get the PR title and description to print to the logs, but the PR title is coming back an empty string.

The code is as follows:

name: Continuous Integration
# according to the docs, this will be triggered every time someone 
# pushes a change to the repo or merges a pull request
on: push
env:
  PR_TITLE: ${{ github.event.pull_request.title }} # this is returning empty
  PR_DESCRIPTION: ${{ github.event.head_commit.message }}
jobs:
  ci:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v3
      - name: Print PR info to console
        run: |
          echo "PR title is: $PR_TITLE"
          echo "PR description is: $PR_DESCRIPTION"
      - name: Python
        uses: actions/setup-python@4
        with:
          python-version: "3.11"
      - name: Unitests and Style check
        pytest
        mypy
      - name: Post actions
        if: success()
        run: |
          echo "Success"

Something that the docs don't say explicitly, at least I couldn't find it but was able to infer from other posts, is that you only have access to the context from the event that triggered the workflow. For instance, I'm using ${{ github.event.pull_request.title }} to get the title, but pull_request is not in the on: statement. Is that a correct assumption? I got that mostly from this post: How to get the title of a Pull Request with Github Actions


Solution

  • The push event doesn't contain the title of the PR in the payload, because it triggers on any push -- not just pushes to a pull request (notably, pushes to a branch for which no PR has been created yet).

    If you really only want to run the workflow on pull requests and pushes to main, I'd recommend switching the trigger to:

    on:
      pull_request:
      push:
        branches: [main]
    

    While you could fetch the pull request title from a push event, consider this:

    • You'd have to find the PR first, e.g. by using the GraphQL query associatedPullRequests on Commit
      • there could be more than one
      • there could be none if the user pushed to a branch w/o PR
      • there could be one, but you don't find it, because it's from a fork
    • You'd have to distinguish the case when running on main

    Using the trigger pull_request solves all these problems, except you'll still have to distinguish whether you're running on main when printing the PR title to the console.

    You could probably do something like this:

    - run: echo "PR title is: ${{ github.event.pull_request.title || 'On Main' }}"