Building the "Is First Commit" GitHub Action
In this post I go through a small GitHub Action I wrote, Is First Commit. It checks whether the current commit is the very first one of a repository.
The project#
An action starts with a package.json, the same as any Node project. It holds the metadata, the dependencies and the scripts.
For Is First Commit it looks like this:
- Name:
first-commit-action - Description: Checks if the current commit is the first ever in a repository.
- Main Script:
index.js - Dependencies:
@actions/core,@actions/githubandaxios, to talk to GitHub and to call its API.
{
"name": "first-commit-action",
"version": "1.0.0",
"description": "Check if the current commit is the first ever commit of the project",
"main": "index.js",
"keywords": ["github", "action"],
"author": "Dennis de Best",
"license": "ISC",
"scripts": {
"lint": "eslint .",
"prepare": "ncc build index.js -o dist --source-map --license licenses.txt",
"test": "jest",
"all": "npm run lint && npm run prepare && npm run test"
},
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/github": "^5.1.1",
"axios": "^1.5.0"
}
}
The action.yaml#
The action.yaml tells GitHub what the action is called, what goes in, what comes out and how to run it:
name: 'Is First Commit'
description: 'Check if the current commit is the first-ever commit of the project'
inputs:
github-token:
description: 'GitHub token (optional)'
required: false
outputs:
isFirstCommit:
description: 'A boolean indicating if the current commit is the first one'
runs:
using: 'node16'
main: 'dist/index.js'
The github-token input is optional, it is only there for authenticated API calls.
The logic#
The check itself is in index.js. The script asks the GitHub API for the commits of the repository and looks if there is only one. If there is, that is the first commit.
Here is a simplified version:
const core = require('@actions/core');
const github = require('@actions/github');
const axios = require('axios');
async function isFirstCommit() {
try {
const { owner, repo } = github.context.repo;
const token = core.getInput('github-token');
const headers = { 'Accept': 'application/vnd.github.v3+json' };
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const url = `https://api.github.com/repos/${owner}/${repo}/commits`;
const response = await axios.get(url, {
headers,
params: { per_page: 2 }
});
const commits = response.data;
const isFirst = commits.length === 1;
core.setOutput('isFirstCommit', isFirst ? 'true' : 'false');
} catch (error) {
core.setFailed(error.message);
}
}
isFirstCommit();
It is not complicated, and it keeps the calls to the API to a minimum.
What it is for#
Knowing it is the first commit lets a workflow run setup tasks only once, like initializing some resources.
It is a small action, which also makes it a good one to start with if you have never written one.
Comments
There are no comments yet. Be the first to write one.
Write a comment