Creating a Custom GitHub Action to Check PR Content
Image created by the author

Creating a Custom GitHub Action to Check PR Content

Hey there, GitHub enthusiast! ?? Are you eager to automate the way you review PRs? Do you want to add a touch of magic to your PR process with GitHub Actions? You're in the right place. Today, we'll walk through crafting a super useful GitHub Action from scratch. Let's dive in! ??




Step 1: Setting the Stage ??

To begin with, you'll need a new GitHub repository. This will be the home for our awesome action. Give it a catchy name – perhaps "pr-content-checker"?


Step 2: Lay Down the Foundation ??

Within your new repository, create a dedicated directory called ./action/. This will house our main star: the Node.js script.


Step 3: The Director's Script ??

Inside the ./action/ directory, craft a Node.js script named processPRText.js. This little gem will read the PR text, send it to a user-defined endpoint, and post the results back as a PR comment.

Here's a starter for your script:

const fetch = require('node-fetch');

const GITHUB_TOKEN = process.env.INPUT_TOKEN;
const GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY;
const PR_NUMBER = process.env.INPUT_PRNUMBER;
const ENDPOINT = process.env.INPUT_ENDPOINT;

// More magic will happen here soon...        


Step 4: The Action's Blueprint ???

Every great GitHub Action needs a guiding map. Create an action.yml file in the root directory. This will tell GitHub about our action, what it needs, and how it operates.

Here's a blueprint to start with:

name: "PR Content Checker"
description: "A magical tool that checks PR content and comments with flair!"
author: "Your Name"
inputs: 
  token:
    description: 'GitHub token'
    required: true
  prNumber:
    description: 'Number of the PR being analyzed'
    required: true
  endpoint:
    description: 'Your chosen endpoint to process the PR text'
    required: true
runs:
  using: "node12"
  main: "action/processPRText.js"        


Step 5: The Magic Potion ??

Back to our Node.js script! We need to add the code that communicates with the endpoint and posts comments on PRs.

Update the processPRText.js script (inside the ./action/ directory):

// ... (previous script content)

async function getPRText() {
    const response = await fetch(`https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}`, {
        headers: {
            'Authorization': `token ${GITHUB_TOKEN}`,
            'User-Agent': 'GitHub-Action-PR-Checker'
        }
    });

    if (!response.ok) {
        throw new Error(`Failed to fetch PR text. HTTP Status Code: ${response.status}`);
    }

    const prData = await response.json();
    return prData.body;
}

async function sendTextToEndpoint(prText) {
    const response = await fetch(ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: prText })
    });

    if (!response.ok) {
        throw new Error(`Oh no! Something went wrong. HTTP Status Code: ${response.status}`);
    }

    const responseData = await response.json();
    return responseData.comment;
}

// Now, let's post the comment back to the PR!
async function postCommentToPR(comment) {
    const url = `https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments`;

    await fetch(url, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${GITHUB_TOKEN}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ body: comment })
    });
}

// Time to put it all together!
async function main() {
    const prText = await getPRText();
    const comment = await sendTextToEndpoint(prText);
    await postCommentToPR(comment);
}

main().catch(error => {
    console.error("Uh-oh! An error occurred:", error);
    process.exit(1);
});        


Step 6: Sprinkles and Toppings ??

We need to manage our Node.js dependencies. Inside the ./action/ directory, create a package.json:

{
  "name": "pr-content-checker",
  "version": "1.0.0",
  "description": "A delightful GitHub Action to check PR content",
  "main": "processPRText.js",
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    "node-fetch": "^2.6.1"
  }
}        


Step 7: Lights, Camera, Action! ??

Push your masterpiece to GitHub. And for the grand finale, tag a release. This way, others can use your action easily.

Go to "Releases" → "Draft a new release" → Tag (e.g., v1.0.0) → "Publish release".


Step 8: Your Action's Debut ??

Use your shiny new action in another repo:

name: Magical PR Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review-pr:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Review PR Content
        uses: YOUR_GITHUB_USERNAME/[email protected]
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          prNumber: ${{ github.event.pull_request.number }}
          endpoint: 'https://example.com/magic-endpoint'
        


Replace placeholders with actual values and watch the magic unfold!


Image created by the author



Wrapping Up Our GitHub Action Adventure ??

And there you have it, trailblazers! Together, we've embarked on a delightful journey into the world of GitHub Actions, mastering the art of automating PR reviews. By crafting our own tools, we've added a touch of efficiency and magic to our development process.

But remember, our coding expedition doesn't end here. The digital realm of development is vast, and there's always more to discover. The tutorial we've just completed is but a single page in the grand book of code. As you move forward, let curiosity be your compass. Dive deeper into GitHub Actions, experiment with different workflows, and push the boundaries of what you think is possible.

Every challenge you tackle, every line of code you pen, adds to your story as a developer. So, I urge you to keep writing that story. And when you stumble upon a new, exciting chapter, remember the joy and satisfaction you felt today.

Thank you for joining me on this adventure! Keep that coding spark alive, be endlessly curious, and never stop exploring the vast universe of possibilities. Until next time, happy coding, and may your repositories always be conflict-free! ??????


#GithubActions #DevAutomation #CodingTutorials


要查看或添加评论,请登录

Pablo Schaffner Bofill的更多文章

社区洞察

其他会员也浏览了