How to write a custom GitHub action- Part 2

We are already familiar with GitHub action, if you are not then Check Part 1

What is custom github action?

Sometimes on the GitHub marketplace, we don't find what we need in that case we want to write a custom GitHub action for the project.

What will we learn?

This blog post will guide you using a concrete example, through the steps to create your actions, and this is just "my version" of the official Creating Actions documentation chapter.

Let's say for example that you want to enforce the fact that your repositories have always a README.md LICENSE and a CONTRIBUTING.mdfile. And when the repository is not compliant with these rules the workflow should fail and provide clear information to the user.

Let's get start

  • First, you need to create a repository

  • clone it to your local computer

  • create a node project npm init -y

  • install npm i @actions/core

  • create an action.yml file

In action.yml file you need to write the following code and you can go with the same or write your own. index.js would be your main file in this case where you will write the logic for creating this action.

name: "Crucial Check Action"
description: "Check README and LICENSE files are exist"
runs:
  using: node16
  main: 'index.js'
  • create an index.js file

In index.js file you need to write the following code to check files are present or not

import core from'@actions/core'
import github from '@actions/github'
import fs from 'fs'

async function checkFileExists(filePath) {
    return fs.promises.access(filePath)
    .then(() => {
        core.info(`File ${filePath} exists`);
        return true;
    })
    .catch(() => {
        core.setFailed(`File ${filePath} is mandatory`);
        return false;
    });
}

(
    async () => {
        try {
            checkFileExists("LICENSE");
            checkFileExists("README.md");
            checkFileExists("CONTRIBUTING.md");

        } catch (error) {
            core.setFailed(error.message);
        }
    }

)();

Next step

you can push your project on GitHub and test It.

Did you find this article valuable?

Support Shivam Sharma by becoming a sponsor. Any amount is appreciated!