Skip to content

Commit

Permalink
fixed and refactored the logics
Browse files Browse the repository at this point in the history
  • Loading branch information
srinivas-jay committed Jul 25, 2023
1 parent cc9c12f commit 90848a8
Show file tree
Hide file tree
Showing 5 changed files with 293 additions and 118 deletions.
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# GitHub Lerna Auto-Versioning Action

This GitHub Action automates the process of updating your package version, tagging, and publishing your package. It allows you to streamline the versioning process and ensure that your package is consistently updated and published.

## How it Works

The action is triggered on the merge of a main branch. Upon being triggered, it carries out the following steps:

1. **Create a new branch**: The action checks out a new branch for the version update.

2. **Run version update**: The action runs a specified command to update the version in `package.json`.

3. **Commit and push tags**: The action commits the version update, creates a git tag for the new version, and pushes the tag to the new branch.

4. **Create a pull request**: The action creates a pull request for the version update, allowing for review and merge when ready.

5. **Publish**: Once the version update is merged, the action runs a publish command to publish the updated package to npm, GitHub, or another configured location.

## Special Conditions

1. **Prevent recursion**: The action is designed to not run on the merge of its own commits to the main branch.

2. **Flexible versioning**: The versioning command is provided by the consumer. This allows for flexibility in the versioning process, whether you want to create a pre-release version, a patch, minor, or major version.

## Usage

1. **Specify the versioning command**: Provide the command to update the version in `package.json` according to your needs.

2. **Choose the branch for release**: Run this custom action on the desired branch. This could be the main branch, a release branch, or another branch as fits your workflow.

3. **Review and merge the pull request**: Once the action creates a pull request, review the changes and merge them when ready.

4. **Ensure necessary permissions**: Make sure the action has the necessary permissions to commit and push tags, create pull requests, and publish the package.

## Notes

This action assumes that every merge to the main branch constitutes a release-worthy increment of your software. If this isn't the case, you may want to consider a different approach, such as manually triggering the version update action when you're ready to create a new release.

---

This is a basic example and could be expanded upon based on the specific details of your action. It's important to provide clear and detailed instructions so that consumers of your action understand how to use it and what to expect.
7 changes: 6 additions & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,23 @@ inputs:
commit-msg:
description: "Commit message"
default: "Update package versions"
required: false
commit-title:
description: "Pull request title"
default: "Update package versions"
required: false
branch-name:
description: "Branch name for version updates"
default: "version-update"
required: false
user-name:
description: "Git user name"
default: "GitHub Action"
required: false
user-email:
description: "Git user email"
default: "[email protected]"
default: "[email protected]"
required: false

runs:
using: "node16"
Expand Down
195 changes: 134 additions & 61 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({

/***/ 5241:
/***/ 7351:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {

"use strict";
Expand Down Expand Up @@ -135,7 +135,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
const command_1 = __nccwpck_require__(5241);
const command_1 = __nccwpck_require__(7351);
const file_command_1 = __nccwpck_require__(717);
const utils_1 = __nccwpck_require__(5278);
const os = __importStar(__nccwpck_require__(2037));
Expand Down Expand Up @@ -1143,7 +1143,7 @@ const os = __importStar(__nccwpck_require__(2037));
const events = __importStar(__nccwpck_require__(2361));
const child = __importStar(__nccwpck_require__(2081));
const path = __importStar(__nccwpck_require__(1017));
const io = __importStar(__nccwpck_require__(7351));
const io = __importStar(__nccwpck_require__(7436));
const ioUtil = __importStar(__nccwpck_require__(1962));
const timers_1 = __nccwpck_require__(9512);
/* eslint-disable @typescript-eslint/unbound-method */
Expand Down Expand Up @@ -17918,7 +17918,7 @@ exports.getCmdPath = getCmdPath;

/***/ }),

/***/ 7351:
/***/ 7436:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {

"use strict";
Expand Down Expand Up @@ -44269,6 +44269,95 @@ function wrappy (fn, cb) {
}


/***/ }),

/***/ 1252:
/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {

"use strict";
__nccwpck_require__.r(__webpack_exports__);
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ "checkoutBranch": () => (/* binding */ checkoutBranch),
/* harmony export */ "commitChanges": () => (/* binding */ commitChanges),
/* harmony export */ "createPullRequest": () => (/* binding */ createPullRequest),
/* harmony export */ "isCommitMadeByAction": () => (/* binding */ isCommitMadeByAction),
/* harmony export */ "runCommand": () => (/* binding */ runCommand),
/* harmony export */ "validateInputs": () => (/* binding */ validateInputs)
/* harmony export */ });
const exec = __nccwpck_require__(1514);

function validateInputs(inputs) {
const { githubToken, branchName, userName, userEmail } = inputs;
if (!githubToken) {
throw new Error('Github token is required');
}
if (!branchName) {
throw new Error('Branch name is required');
}
if (!userName) {
throw new Error('User name is required');
}
if (!userEmail) {
throw new Error('User email is required');
}
}

async function isCommitMadeByAction(gitClient, userName, userEmail) {
const latestCommit = await gitClient.log({ maxCount: 1 });
if (
latestCommit &&
latestCommit.latest &&
latestCommit.latest.author_email === userEmail &&
latestCommit.latest.author_name === userName
) {
return true;
}
return false;
}

async function checkoutBranch(gitClient, branchName) {
await gitClient.checkoutLocalBranch(branchName);
}

async function runCommand(command) {
try {
const cmd = command.split(' ');
await exec.exec(cmd[0], cmd.slice(1));
} catch (error) {
throw new Error(`Error running command "${command}": ${error.message}`);
}
}

async function commitChanges(gitClient, commitMsg, branchName) {
try {
await gitClient.add('./*');
await gitClient.commit(commitMsg);
await gitClient.push('origin', branchName);
} catch (error) {
throw new Error(`Error committing changes: ${error.message}`);
}
}

async function createPullRequest(
octokit,
context,
commitTitle,
branchName
) {
try {
await octokit.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: commitTitle,
head: branchName,
base: 'main'
});
} catch (error) {
throw new Error(`Error creating pull request: ${error.message}`);
}
}


/***/ }),

/***/ 2877:
Expand Down Expand Up @@ -47353,84 +47442,68 @@ var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
const { Octokit } = __nccwpck_require__(5375);
const exec = __nccwpck_require__(1514);
const git = __nccwpck_require__(9103);
const core = __nccwpck_require__(2186);
const github = __nccwpck_require__(5438);
const fetch = (__nccwpck_require__(4429)/* ["default"] */ .ZP);

async function checkoutBranch(gitClient, branchName) {
await gitClient.checkoutLocalBranch(branchName);
}

async function runCommand(command) {
const cmd = command.split(' ');
await exec.exec(cmd[0], cmd.slice(1));
}

async function commitChanges(gitClient, commitMsg, branchName) {
await gitClient.add('./*');
await gitClient.commit(commitMsg);
await gitClient.push('origin', branchName);
}

async function createPullRequest(octokit, context, commitTitle, branchName) {
await octokit.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: commitTitle,
head: branchName,
base: 'main'
});
}
const {
validateInputs,
isCommitMadeByAction,
checkoutBranch,
commitChanges,
runCommand,
createPullRequest
} = __nccwpck_require__(1252);

async function run() {
try {
// Get inputs
const githubToken = core.getInput('github-token');
const inputs = {
githubToken: core.getInput('github-token'),
branchName: core.getInput('branch-name'),
userName: core.getInput('user-name'),
userEmail: core.getInput('user-email')
};

validateInputs(inputs);

const versionCommand = core.getInput('version-command');
const publishCommand = core.getInput('publish-command');
const commitMsg = core.getInput('commit-msg');
const commitTitle = core.getInput('commit-title');
const branchName = core.getInput('branch-name');
const userName = core.getInput('user-name');
const userEmail = core.getInput('user-email');

// Get the event that triggered the action
const { context } = github;
const event = context.eventName;

// Set up Git
const gitClient = git();
await gitClient.addConfig('user.name', userName);
await gitClient.addConfig('user.email', userEmail);

if (event === 'push') {
const pushedBranch = context.payload.ref.split('/').pop();
if (pushedBranch === branchName) {
console.log(
`This is a push from the ${branchName} branch, running the publish process...`
);
await runCommand(publishCommand);
} else {
await checkoutBranch(gitClient, branchName);
await runCommand(versionCommand);
await commitChanges(gitClient, commitMsg, branchName);

const octokit = new Octokit({
auth: githubToken,
request: {
fetch: fetch
}
});
await createPullRequest(
octokit,
context,
commitTitle,
branchName
);
}
// Check if the commit is made by this action
const isActionCommit = await isCommitMadeByAction(
gitClient,
userName,
userEmail
);

// if so run the only publish command and exit
if (isActionCommit) {
await runCommand(publishCommand);
return;
}

// Run the version command on new branch
await checkoutBranch(gitClient, branchName);
await runCommand(versionCommand);
await commitChanges(gitClient, commitMsg, branchName);

const octokit = new Octokit({
auth: githubToken,
request: {
fetch: fetch
}
});
await createPullRequest(octokit, context, commitTitle, branchName);
} catch (error) {
core.setFailed(error.message);
}
Expand Down
Loading

0 comments on commit 90848a8

Please sign in to comment.