Applying/remove labels from a commit

Is it possible to apply or remove an issue label from a commit when an issue is referenced in the commit. I see that I can run actions on a [push] but I’m getting lost when actually trying to parse the commit message and apply/remove labels on the issue referenced.

Let’s say I have issue #1 with a label of ‘waiting for commit’. a commit gets pushed with a message of ‘#1 blah blah’. Is it possible to remove the label ‘waiting for commit’ and apply ‘waiting for review’ on issue #1?

Yes, it’s possible, but it’s not straightforward. If you use an on: push trigger, than you actually get easy access to the commit messages:

  • ${{ github.event.head_commit.message }} for the latest commit
  • ${{ github.event.commits.*.mesage }} for an array of all commit messages

If you want to pass this data on via env: ..., then be sure to cast it from an actual data structure to a JSON string with fromJSON().

As you want to search for the pattern #<digits>, you cannot really use GitHub expressions - it does not support regular expressions. You could use some Bash code, e.g.

- name: Find issue references
    COMMIT_MSGS: ${{ toJSON(github.event.commits.*.message) }}
  shell: bash
  run: |
    echo "$COMMIT_MSGS" | grep -woE '#[0-9]+' | cut -d"#" -f2 | jq -nRc '[inputs]'

That should return a JSON array with issue numbers as strings. You could set this result as output to use it in a subsequent step, but unless you find an action (or write one yourself) that can handle multiple issue numbers at once, this will be limited to a fixed number of issue references that you can react to.

I think it would actually be better to use actions/github-script so that you can use JavaScript in your workflow directly and perform the API interaction to remove labels using its Octokit instance. Or write your own action that does all necessary things. If you want to change the trigger to on: pull_request, then you will need to query the GitHub API anyway to determine what commits were pushed, because github.event does not have commits and head_commit set in this case.

Before diving more into this matter, can you clarify what trigger you want to use? And do you actually want to handle multiple issue references? What if there is a reference like #123 but there is actually no such issue?

1 Like

One caution about github.event.commits: It’s limited to 20 commits. If there are more in the push, you’ll need to use the API or standard Git means to check the rest as mentioned in the push object documentation.

1 Like