Skip to content

Commit

Permalink
Bump dependencies + support husky v9 (#73)
Browse files Browse the repository at this point in the history
* Bump dependencies + support husky v9

* Shorter git branch command

* Make HUSKY_GIT_PARAMS optional
  • Loading branch information
jessedobbelaere authored Dec 25, 2024
1 parent f17af8f commit c23e045
Show file tree
Hide file tree
Showing 9 changed files with 1,734 additions and 2,142 deletions.
48 changes: 24 additions & 24 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,29 @@ name: release
# Allow to trigger this workflow manually and enter a release version to release
# See: https://github.blog/changelog/2020-07-06-github-actions-manual-triggers-with-workflow_dispatch/
on:
workflow_dispatch:
inputs:
releaseVersion:
description: "Release tag version"
required: true
workflow_dispatch:
inputs:
releaseVersion:
description: "Release tag version"
required: true

jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@v2
with:
ref: "master"
fetch-depth: 0
- uses: oleksiyrudenko/gha-git-credentials@v1
with:
token: "${{ secrets.GITHUB_TOKEN }}"
- name: Use Node.js
uses: actions/setup-node@v2-beta
with:
node-version: 14
- name: Release version
run: npx -p @release-it/bumper@2.0.0 -p release-it@14.2.1 release-it --verbose --increment ${{ github.event.inputs.releaseVersion }}
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
release:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@v2
with:
ref: "master"
fetch-depth: 0
- uses: oleksiyrudenko/gha-git-credentials@v1
with:
token: "${{ secrets.GITHUB_TOKEN }}"
- name: Use Node.js
uses: actions/setup-node@v2-beta
with:
node-version: 22
- name: Release version
run: npx -p @release-it/bumper@2.0.0 -p release-it@14.2.1 release-it --verbose --increment ${{ github.event.inputs.releaseVersion }}
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
34 changes: 17 additions & 17 deletions .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
name: run-tests

on: [push, pull_request]
on: [push]

jobs:
tests:
strategy:
fail-fast: true
matrix:
node: [ '10', '12', '14', '15' ] # https://nodejs.org/en/about/releases/
name: NPM test - (Node ${{ matrix.node }})
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- uses: actions/setup-node@v2-beta
with:
node-version: ${{ matrix.node }}
- name: install dependencies
run: npm ci
- name: run tests
run: npm test
strategy:
fail-fast: true
matrix:
node: ["18", "20", "22"] # https://nodejs.org/en/about/releases/
name: NPM test - (Node ${{ matrix.node }})
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- uses: actions/setup-node@v2-beta
with:
node-version: ${{ matrix.node }}
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": false,
"tabWidth": 4,
"printWidth": 120,
"trailingComma": "all"
}
24 changes: 11 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

![tests](https://github.com/jessedobbelaere/jira-smart-commit/workflows/run-tests/badge.svg)
[![GitHub release](https://img.shields.io/github/release/jessedobbelaere/jira-smart-commit.svg)](https://github.com/jessedobbelaere/jira-smart-commit/releases/latest)
[![Dependabot Status](https://api.dependabot.com/badges/status?host=github&repo=jessedobbelaere/fork-cms-webpack-boilerplate)](https://dependabot.com)
[![Dependabot](https://img.shields.io/badge/dependabot-active-brightgreen?style=flat-square&logo=dependabot)](https://dependabot.com)
[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)
[![Downloads](https://img.shields.io/npm/dt/jira-smart-commit.svg)](https://www.npmjs.com/package/jira-smart-commit)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)](http://makeapullrequest.com)
Expand All @@ -17,6 +17,7 @@ A Node.js git hook script to prefix commits automatically with the JIRA ticket,

```bash
npm install --save-dev husky
npx husky init
```

2. Install this package in your project:
Expand All @@ -27,27 +28,24 @@ npm install --save-dev jira-smart-commit

3. Configure scripts in `package.json`. The script expects his first argument to be the JIRA tag of the project.

```json
"husky": {
"hooks": {
"commit-msg": "jira-smart-commit YOUR_JIRA_ISSUE_KEY",
"pre-commit": "lint-staged"
}
},
```bash
# .husky/commit-msg
npx jira-smart-commit YOUR_JIRA_ISSUE_KEY
```

Alternatively: use a regex to detect the Jira `ISSUE_KEY` in your branch.

- `TAG_MATCHER` - regular expression
- `TAG_MATCH_INDEX` - match index
- `TAG_MATCHER` - regular expression
- `TAG_MATCH_INDEX` - match index

Example: if your branch names looke like `feature/JRA-1234/some-description` template

```
"commit-msg": "TAG_MATCHER=\"^[^/]+/(JRA-[0-9]+)\" TAG_MATCH_INDEX=1 jira-smart-commit"
```bash
# .husky/commit-msg
TAG_MATCHER=\"^[^/]+/(JRA-[0-9]+)\" TAG_MATCH_INDEX=1 npx jira-smart-commit
```

4. Do your git commits like usual. If the branch was prefixed with a JIRA tag, your commit message will get prefixed with
4. Commit with git like usual. If the branch was prefixed with a JIRA tag, your commit message will get a Jira prefix added with
the same tag.

```
Expand Down
39 changes: 16 additions & 23 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node

const fs = require("fs");
import fs from "fs";
import childProcess from "child_process";

/**
* If commit message title:
Expand All @@ -11,11 +12,12 @@ const fs = require("fs");
* then prepend the JIRA issue tag to the commit message.
* E.g My awesome commit -> TAG-123 My awesome commit
*/

if (!process.argv[2] && !process.env.TAG_MATCHER ) {
console.error("Please run this script with the JIRA ticket prefix as CLI argument " +
"(e.g. node smart-commit-msg.js SPAN) or pass regular expression as envirement variable " +
"(e.g. TAG_MATCHER=\\\"SPAN-[0-9]+\\\" node smart-commit-msg.js)");
if (!process.argv[2] && !process.env.TAG_MATCHER) {
console.error(
"Please run this script with the JIRA ticket prefix as CLI argument " +
"(e.g. node smart-commit-msg.js SPAN) or pass regular expression as envirement variable " +
'(e.g. TAG_MATCHER=\\"SPAN-[0-9]+\\" node smart-commit-msg.js)',
);
process.exit(1);
}

Expand All @@ -29,22 +31,11 @@ const isInvalidMessage = (commitMessage) => {
return !startsWithMergeBranch(commitMessage) && !startsWithMergePR(commitMessage);
};

/**
* @returns {string}
*/
const getBranchName = () => {
const branchName = fetchBranchNameFromGit();
if (["master", "main", "develop"].includes(branchName)) {
console.warn(`WARNING: Committing directly to ${branchName} is probably not a good idea. Consider making a PR.`);
}
return branchName;
};

/**
* @returns {String}
*/
const fetchBranchNameFromGit = () => {
return require("child_process").execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf-8" }).split("\n")[0]
return childProcess.execSync("git branch --show-current", { encoding: "utf-8" }).split("\n")[0];
};

/**
Expand All @@ -54,17 +45,19 @@ const fetchBranchNameFromGit = () => {
const getIssueTagFromBranchName = (branchName) => {
const matched = branchName.match(tagMatcher);
const index = process.env.TAG_MATCH_INDEX ? Number(process.env.TAG_MATCH_INDEX) : 0;
if (process.env.DEBUG === 'true') {
console.log({branchName, tagMatcher, index, matched});
if (process.env.DEBUG === "true") {
console.log({ branchName, tagMatcher, index, matched });
}
return matched && matched[index];
};

const jiraTag = process.argv[2];
const tagMatcher = process.env.TAG_MATCHER ? new RegExp(process.env.TAG_MATCHER, "i") : new RegExp(`^${jiraTag}-\\d+`, "i");
const commitMsgFile = process.env.GIT_PARAMS || process.env.HUSKY_GIT_PARAMS;
const tagMatcher = process.env.TAG_MATCHER
? new RegExp(process.env.TAG_MATCHER, "i")
: new RegExp(`^${jiraTag}-\\d+`, "i");
const commitMsgFile = process.env.GIT_PARAMS || process.env.HUSKY_GIT_PARAMS || ".git/COMMIT_EDITMSG";
const commitMsg = fs.readFileSync(commitMsgFile, { encoding: "utf-8" });
const branchName = getBranchName();
const branchName = fetchBranchNameFromGit();
const issueTag = getIssueTagFromBranchName(branchName);
const rawCommitMsgTitle = commitMsg.split("\n")[0];

Expand Down
60 changes: 0 additions & 60 deletions index.spec.js

This file was deleted.

89 changes: 89 additions & 0 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { expect, describe, it, beforeEach, afterEach, vi } from "vitest";
import fs from "fs";
import childProcess from "child_process";

vi.mock("fs");
vi.mock("child_process");

describe("index.js", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetModules();

// Reset process env and args
process.env.HUSKY_GIT_PARAMS = "COMMIT_EDITMSG";
delete process.argv[2];
});

afterEach(() => {
vi.restoreAllMocks();
vi.resetAllMocks();
vi.resetModules();
});

it.each([
["SPAN", "SPAN-1-proof-of-concept", "Initial commit✨", "SPAN-1 Initial commit✨"],
["PROJECT", "PROJECT-3-githook-test", "Add support for githooks", "PROJECT-3 Add support for githooks"],
["TAG", "TAG-5032-add-readme", "Add readme to project", "TAG-5032 Add readme to project"],
])(
"should add a prefix to my unprefixed commit message",
async (jiraPrefix, branchName, commitMessage, expected) => {
await expect(executeScript(jiraPrefix, branchName, commitMessage)).resolves.to.equal(expected);
},
);

it("should add a prefix to my unprefixed commit message by detecting the tag using regex", async () => {
process.env.TAG_MATCHER = "^[^/]+/(SPAN-[0-9]+)";
process.env.TAG_MATCH_INDEX = "1";
await expect(executeScript(undefined, "FEAT/SPAN-1234/init", "Initial commit")).resolves.to.equal(
"SPAN-1234 Initial commit",
);
delete process.env.TAG_MATCHER;
delete process.env.TAG_MATCH_INDEX;
});

it.each([
["SPAN", "SPAN-1-proof-of-concept", "SPAN-1 Initial commit✨", "SPAN-1 Initial commit✨"],
[
"PROJECT",
"PROJECT-3-githook-test",
"PROJECT-3 Add support for githooks",
"PROJECT-3 Add support for githooks",
],
["TAG", "TAG-5032-add-readme", "TAG-5032 Add readme to project", "TAG-5032 Add readme to project"],
])(
"should not add a prefix again to my already prefixed commit message",
async (jiraPrefix, branchName, commitMessage, expected) => {
await expect(executeScript(jiraPrefix, branchName, commitMessage)).resolves.to.equal(expected);
},
);

it("should not add a prefix in merge pull requests", async () => {
const commitMergeMessage =
"Merge branch 'develop' of github.com:jessedobbelaere/jira-smart-commit into bugfixes";
await expect(executeScript("SPAN", "SPAN-1-proof-of-concept", commitMergeMessage)).resolves.to.equal(
commitMergeMessage,
);
});

it("should not add a prefix if a branch was not prefixed", async () => {
await expect(executeScript("TAG", "conquer-the-world-PoC", "Initial commit")).resolves.to.equal(
"Initial commit",
);
});

const executeScript = async (jiraPrefix, branchName, commitMessage) => {
// Mock execution environment
process.env.HUSKY_GIT_PARAMS = "COMMIT_EDITMSG";
process.argv[2] = jiraPrefix; // Set CLI argument for JIRA prefix
vi.mocked(childProcess.execSync).mockReturnValue(branchName);
vi.mocked(fs.readFileSync).mockReturnValueOnce(commitMessage);
const writeFileMock = vi.mocked(fs.writeFileSync);

// Run script
const modulePath = require.resolve("./index.js");
await import(modulePath);

return writeFileMock.mock.calls[0][1];
};
});
Loading

0 comments on commit c23e045

Please sign in to comment.