Giter Site home page Giter Site logo

github-action-required-labels's Introduction

github-action-required-labels

This action allows you to fail the build if/unless a certain combination of labels are applied to a pull request.

Usage

This action has three required inputs; labels, mode and count

Name Description Required Default
labels New line separated list of labels to match (legacy support for a comma separated list remains when use_regex=false) true
mode The mode of comparison to use. One of: exactly, minimum, maximum true
count The required number of labels to match true
token The GitHub token to use when calling the API false ${{ github.token }}
message The message to log and to add to the PR (if add_comment=true). See the README for available placeholders false
add_comment Add a comment to the PR if required labels are missing. If a comment already exists, it will be updated. When the action passes, the comment will be deleted false false
exit_type The exit type of the action. One of: failure, success false
use_regex Evaluate the values in labels as regular expressions false

This action calls the GitHub API to fetch labels for a PR rather than reading event.json. This allows the action to run as intended when an earlier step adds a label. It will use github.token by default, and you can set the token input to provide alternative authentication.

If successful, any matching labels will be output in outputs.labels as a comma separated string.

Tip

Label matching is case-insensitive.

Examples

Complete example

name: Pull Request Labels
on:
  pull_request:
    types: [opened, labeled, unlabeled, synchronize]
jobs:
  label:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: mheap/github-action-required-labels@v5
        with:
          mode: exactly
          count: 1
          labels: |
            semver:patch
            semver:minor
            semver:major

Prevent merging if a label exists

- uses: mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 0
    labels: "do not merge"

Post a comment when the check fails

You can choose to add a comment to the PR when the action fails. The default format is:

Label error. Requires {{ errorString }} {{ count }} of: {{ provided }}. Found: {{ applied }}

- uses: mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 1
    labels: |
      semver:patch
      semver:minor
      semver:major
    add_comment: true

If a comment already exists, it will be updated. When the action passes, the comment will be deleted.

Customising the failure message / comment

You can also customise the message used by providing the message input:

- uses: mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 1
    labels: |
      semver:patch
      semver:minor
      semver:major
    add_comment: true
    message: "This PR is being prevented from merging because you have added one of our blocking labels: {{ provided }}. You'll need to remove it before this PR can be merged."

The following tokens are available for use in custom messages:

Token Value
mode One of: exactly, minimum, maximum
count The value of the count input
errorString One of: exactly, at least, at most
provided The value of the labels input
applied The labels that are applied to the PR

Require multiple labels

- uses: mheap/github-action-required-labels@v5
  with:
    mode: minimum
    count: 2
    labels: |
      community-reviewed
      team-reviewed
      codeowner-reviewed

Use regular expressions

- uses: mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 1
    labels: "semver:.*"
    use_regex: true

Preventing comment collisions

This action uses a combination of the workflow name/path, job ID, and step ID to add an invisible "match token" to the beginning of any comments it creates. That way, it can later know which comments it owns when modifying them, while supporting multiple "instances" of this action to be run at the same time within a repo.

However, note that if any of those three identifiers change, any "in flight" comments on open PRs may be orphaned (since the final match token will have changed between runs). If you rename any of those identifiers, you will have to delete any orphaned comments manually.

Controlling failure

You can set exit_type to success then inspect outputs.status to see if the action passed or failed. This is useful when you want to perform additional actions if a label is not present, but not fail the entire build.

- uses: mheap/github-action-required-labels@v5
  with:
    mode: minimum
    count: 2
    labels: |
      community-reviewed
      team-reviewed
      codeowner-reviewed
    exit_type: success # Can be: success or failure (default: failure)

If the action passed, outputs.status will be success. If it failed, outputs.status will be failure.

Here is a complete workflow example for this use case:

name: Pull Request Labels
on:
  pull_request:
    types: [opened, labeled, unlabeled, synchronize]
jobs:
  label:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    outputs:
      status: ${{ steps.check-labels.outputs.status }}
    steps:
      - id: check-labels
        uses: mheap/github-action-required-labels@v5
        with:
          mode: exactly
          count: 1
          labels: |
            semver:patch
            semver:minor
            semver:major
          exit_type: success
  do-other:
    runs-on: ubuntu-latest
    needs: label
    steps:
      - run: echo SUCCESS
        if: needs.label.outputs.status == 'success'
      - run: echo FAILURE && exit 1
        if: needs.label.outputs.status == 'failure'

Using Output Labels

If the action was successful you can access the matching labels via outputs.labels. This is useful if you want to use the labels in a later step.

name: Pull Request Labels
on:
  pull_request:
    types: [opened, labeled, unlabeled, synchronize]
jobs:
  label:
    runs-on: ubuntu-latest
    steps:
      - id: check-labels
        uses: mheap/github-action-required-labels@v5
        with:
          mode: minimum
          count: 1
          labels: |
            feature-1
            feature-2
            feature-3
      - run: |
          echo "Enabled Features:"
          for f in $(echo "{{steps.check-labels.outputs.labels}}" | sed "s/,/ /g")
          do
            echo "$f"
          done

github-action-required-labels's People

Contributors

acoffman avatar codfish avatar dependabot[bot] avatar gileswells avatar jeff-miller-cfa avatar mheap avatar mtblue81 avatar nathanielhill avatar whodoneitagain avatar yannickm95 avatar zhimsel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

github-action-required-labels's Issues

Idea: Update existing comment(s)?

This action is great, though it would be nice if we could update or remove and recreate comments rather than just adding new ones πŸ™‚

Speed/Caching Improvements?

This action is twice as slow as the previous label checker we were using, but it doesn't generate extra notifications which is why we went with it.

Do you think there's room for speeding it up?

Idea: make the exit status configurable

Hi! Thanks for maintaining this, we use it for a rather complicated PR approval process involving chromatic and it helped us immensely reducing build time!

One small suggestion:

We would love a configuration option to replace tools.exit.failure with tools.exit.neutral, so we don't really "fail" the PR but keep it "pending" so to speak.

Maybe something like:

- uses: mheap/github-action-required-labels@v1
  with:
    mode: exactly
    count: 1
    exitNeutral: true
    labels: "semver:patch, semver:minor, semver:major"

If you consider it but don't have time, I could try and create a pull request, seems to be easy enough. Thank you for consideration!

Action fails with The GITHUB_TOKEN environment variable must be set to add a comment

Looks like add_comment: false is converted to a string and since 'false' is truthy, it fails.

4ae53dd#diff-e727e4bdf3657fd1d798edcd6b099d6e092f8573cba266154583a746bba0f346R95

Run mheap/github-action-required-labels@v2
  with:
    mode: exactly
    count: 1
    labels: API Functional Pass
    add_comment: false
Error: The GITHUB_TOKEN environment variable must be set to add a comment
βœ–  fatal     Error: The GITHUB_TOKEN environment variable must be set to add a comment 
    at exitWithError (/home/runner/work/_actions/mheap/github-action-required-labels/v[2]

Support list of labels

When the list of labels is long, it's not very easy to manage them in a single line and comma separation.

Many actions support lists of items like this:

-
        name: Docker meta
        id: meta
        uses: docker/metadata-action@v4
        with:
          # list of Docker images to use as base name for tags
          images: |
            name/app
            ghcr.io/username/app
          # generate Docker tags based on the following events/attributes
          tags: |
            type=schedule
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            type=sha

Adding support for labels like these would be nice. Thanks!

Gets stuck on dismissing own review

Sometimes when dismissing it's own review, it's already dismissed and gets into an irrecoverable state. Could this be patched to ignore that particular error?

errors: [ 'Can not dismiss a dismissed pull request review' ],
  documentation_url: 'https://docs.github.com/rest/reference/pulls#dismiss-a-review-for-a-pull-request'

Check keeps saying "Expected - Waiting for status to be reported"

I keep getting the status below for this check:
image

Code:

name: Labels
on:
  pull_request:
    types: [opened, labeled, unlabeled, synchronize]
jobs:
  do_not_merge:
    name: Disallow Merging When "do not merge" Label Is Present
    runs-on: ubuntu-latest
    steps:
      - uses: mheap/github-action-required-labels@v1
        with:
          mode: exactly
          count: 0
          labels: "do not merge"

Apparently the workaround is to push an empty commit to re-trigger the action, but this is happening on a lot of our PRs, so it's a little annoying. All of the action runs are successful, I guess it's just not getting reported? It's not happening with any of our other actions.

Warning: Unexpected input(s) 'exit_type'

Hi! When I try to use v2 of the action which should support exit_type, I get a warning that exit_type is not a supported input of the action.

Warning: Unexpected input(s) 'exit_type', valid inputs are ['labels', 'mode', 'count']

The sha that the workflow shows for the action points to the latest release too 48a61a5cb9f36755e6bfe778fd517022f048ef8f.

name: Pull Request Labels

on:
  pull_request:
    types: [opened, labeled, unlabeled, synchronize]

jobs:
  label:
    runs-on: ubuntu-latest
    steps:
      - uses: mheap/github-action-required-labels@v2
        with:
          mode: minimum
          count: 1
          labels: "bug, dependencies, docs, feature, refactor, security, testing"
          exit_type: neutral

This is the current workflow setup if that is of any help.

Customizable comments?

This is more of a question/feature request than an issue, but I thought I'd ask.

Recently I transitioned my repos from an old Heroku label enforcer to this very cool GitHub Action. One of the things I loved about it was the fact that it can make a comment when something goes wrong. Nice.

However, I was wondering how hard it would be to make that comment customizable? I ask because in our systems we have two different types of labels. One set are required to merge, but we use a different set of labels to "block" the PR (because someone needs to approve, or the PR in question depends on another PR, etc.). You can see the comments made by both of these here in my test repo.

Now it does work and the comment feature is MUCH nicer than what we had before (which was people asking me "Why is my PR not able to merge?"). But it might be easier for them to understand with a comment like:

This PR is being prevented from merging because you have not added one of our required labels: A, B, C. Please add one of these.

or:

This PR is being prevented from merging because you have added one of our blocking labels: D, E, F. You'll need to remove it before this PR can be merged.

Of course, I don't know how these GitHub Actions even work, so if something like this takes more than like 5 minutes of effort, probably not worth it! πŸ˜„

Labels which is added by action-add-label is not recognized

Thanks for this action. In our project, we have a problem that github-actions-required-labels do not recognize labels labeled with action-add-label.
This is the yaml we are using.
https://github.com/pyvista/pyvista/blob/d3a51becf51cc7348e3c4c11ec6db170c2427f74/.github/workflows/label.yml
And the output is like this.
https://github.com/pyvista/pyvista/runs/7063771018?check_suite_focus=true
@mheap I would appreciate your opinion about this.

Thoughts on supporting case insensitivity?

Thoughts on supporting case insensitivity out of the box OR adding it as an input?

https://github.com/mheap/github-action-required-labels/blob/main/index.js#L93C7-L93C77

- const appliedLabels = labels.map((label) => label.name);
+ const appliedLabels = labels.map((label) => label.name);
+ const lowerCaseAppliedLabels = appliedLabels.map((label) => label.toLowerCase());

- intersection = providedLabels.filter((x) => appliedLabels.includes(x))
+ intersection = providedLabels.filter((x) => lowerCaseAppliedLabels.includes(x.toLowerCase()))

The use case here is that we want to use this in a composite across repos but some repos have a "Do Not Merge" label spelled in different ways. In order to appropriately handle this, we have to do something like:

    - uses: mheap/github-action-required-labels@fab3b73a9443656a796639b75fe08d4eb8c75e75
      with:
        mode: exactly
        count: 0
        labels: "DO NOT MERGE, Do Not Merge, Do not merge, do not merge"
        add_comment: true

But that's obviously got a little bit of a smell to it, and the comment that get's posted isn't ideal.

Need to update v2 tag

Hello,

You pushed a fix for the comment issue as v2.2.3, but the v2 tag is still pointing at v2.2.2, can you update?

Thanks!

Action fails with "Not Found" when run in a merge queue

To reproduce, created a sample project repo at: https://github.com/JuulLabs/merge-queue-test

Without merge queue enabled, github-action-required-labels works (JuulLabs/merge-queue-test#13) as expected:

GitHub Action run w/o merge queue
Run mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 1
    labels: patch, minor, major, maintenance
    token: ***
    message: Label error. Requires {{errorString}} {{count}} of: {{ provided }}. Found: {{ applied }}
    add_comment: false

β€” https://github.com/JuulLabs/merge-queue-test/actions/runs/7154600875/job/19482310003

When merge queue is enabled, and github-action-required-labels runs from the queue, it fails (JuulLabs/merge-queue-test#14) with:

Run mheap/github-action-required-labels@v5
  with:
    mode: exactly
    count: 1
    labels: patch, minor, major, maintenance
    token: ***
    message: Label error. Requires {{errorString}} {{count}} of: {{ provided }}. Found: {{ applied }}
    add_comment: false
Error: Not Found

β€” https://github.com/JuulLabs/merge-queue-test/actions/runs/7154628159/job/19482369364

Attempts to add comment when default is "false"

fatal Error: The GITHUB_TOKEN environment variable must be set to add a comment

We don't have GITHUB_TOKEN env set because we don't want to add a comment

exitWithError should give the error instead is failing

description: "Add a comment to the PR if required labels are missing"
default: "false"
required: false

Expect the default should be false not "false" for boolean test to fail by default to not add the comment
caused by 4ae53dd

github-action-required-labels doesn't detect label changes from previous steps

When mheap/github-action-required-labels@v1 is used in a multi-step workflow, it won't detect label changes from previous steps, causing the condition of having at least 1 label fail.
Steps to replicate the issue:

  1. Setup files in the repo. release-drafter/[email protected] is capable of automatically labeling pull request based on certain criteria, e.g. taking it from the branch prefix, like feature/JIRA-123 -> because of feature prefix, labeling it as enhancement

.github/workflows/pr-label-enforcer.yaml:


on:
  pull_request:
    types: [opened, edited, labeled, unlabeled, synchronize]
jobs:
  pr-label-enforcer:
    runs-on: ubuntu-latest
    steps:
        # Only runs for PR 'opened' trigger. Because job steps run in a sequential order, 'check_label' will use the added label
      - name: Release Drafter - add label for opened PR
        if: github.event.action == 'opened'
        uses: release-drafter/[email protected]
        with:
          disable-autolabeler: false
          disable-releaser: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: sleep 15
        if: github.event.action == 'opened'
        run: sleep 15
      - name: check_label
        uses: mheap/github-action-required-labels@v1
        with:
          mode: minimum
          count: 1
          labels: "feature, enhancement, fix, bugfix, bug, chore, skip-changelog"

.github/release-drafter.yml:

name-template: $NEXT_PATCH_VERSION
tag-template: $NEXT_PATCH_VERSION
categories:
  - title: πŸš€ Features
    labels:
      - 'feature'
      - 'enhancement'
  - title: πŸ› Bug Fixes
    labels:
      - 'fix'
      - 'bugfix'
      - 'bug'
  - title: 🧰 Maintenance
    labels:
      - chore
autolabeler:
  - label: 'enhancement'
    branch:
      - '/feature\/.+/'
  - label: 'bug'
    branch:
      - '/^(bug|fix)+\/.+/'
exclude-labels:
  - 'skip-changelog'
change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
template: |
  ## What’s Changed

  $CHANGES
  

  1. Submit a PR from e.g. feature/JIRA-123 branch. mheap/github-action-required-labels@v1 adds the label enhancement, the second step sleeps for 15 seconds, still, release-drafter/[email protected] fails with an error of not finding any labels.
    Unfortunately, this causes the workflow to fail on every PR open, because the label checker will fail, and then have to be triggered again manually to pass. The use case of this whole automation would be to enforce labels in all PRs, but also automatically tag PRs when possible.

Netural status is no longer supported by Github

Unfortunately it seems like Github dropped the neutral exit code a year or two back and have yet to replace it with anything, which is quite annoying.

actions/runner#662
https://github.community/t/github-actions-neutral-exit-code-is-incorrectly-interpreted-as-failure/16088

It is still in the actions-toolkit because that package hasn't been updated in a couple of years either.

This was a bummer because I was really looking forward to the possibility of having a neutral exit like @moritzjacobs originally suggested. I think I will be able to manage without it though.

Prevent running the check after the PR has been closed?

Is there a way to prevent the check from running after the PR has been closed? I couldn't find any filters on GitHub's docs to control that.

The issue is we're using this with a "Pending Merge" label, and we want to remove the label after the PR has been merged, but then the check runs and it sends an email about the failing check.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.