Skip to content

mheap/action-guard

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 

Action Guard

Make sure that your GitHub Actions are only running on events that you're expecting.

Replaces:

const event = process.env.GITHUB_EVENT_NAME;
const payload = require(process.env.GITHUB_EVENT_PATH);

if (event != "pull_request" || payload.action != "closed") {
  console.log(`
    This action only runs on pull_request.closed
    Found: ${event}.${payload.action}
  `);
  return;
}

With:

require("action-guard")("pull_request.closed");

If you're looking for a way to handle multiple events + actions, you might find @mheap/action-router useful

Installation

npm install action-guard

Usage

Action Guard will throw if the GITHUB_EVENT_NAME does not match what is expected

If you're happy to leave it uncaught (leading to a process.exit(1)) you can add it as one line:

require("action-guard")("pull_request.closed");

Alternatively, you can wrap it in a try/catch

const guard = require("action-guard");

try {
  guard("pull_request.closed");
} catch (e) {
  // It didn't match. Let's do something else
}

Matching arbitrary payloads

In addition to checking the event, you can also check for entries in the provided GITHUB_EVENT.

Here's an example that will throw if the pull request was not opened by mheap:

guard({
  event: "pull_request.opened",
  payload: { user: { login: "mheap" } },
});

See https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads for sample payloads

Matching multiple conditions

You can provide multiple conditions to validate. If all fail, an Error will be thrown.

Here's an example that allows an action to run when closing an issue or pull_request:

guard(["issue.closed", "pull_request.closed"]);