Giter Club home page Giter Club logo

jira-prepare-commit-msg's Introduction

jira-prepare-commit-msg

Downloads MIT license

The husky command to add JIRA ticket ID into the commit message if it is missing.

The JIRA ticket ID is taken from the current git branch name.

Why?

Installing Jira prepare commit msg hook into your project will mean everyone contributing code to your project will automatically tag each commit with its associated issue key based on the branch name.

So if your branch name is feature/TEST-123-new-feature, then when you commit with a message "initial commit" it will automatically become "TEST-123: initial commit".

Why would you want this? Well, Jira has many hidden goodies, and this is one of them! If you include an issue key in your commit messages AND you have your deployment pipeline connected to Jira this will unlock many bonus features, such as the Deployments view, Cycle time report, Deployment frequency report and I've heard many more features are coming soon!

Installation

Install the package using NPM

npm install husky jira-prepare-commit-msg --save-dev && npx husky install

For Husky 5+

Execute command

npx husky add .husky/prepare-commit-msg 'npx jira-prepare-commit-msg $1'

To quiet the output of the command, you can use the --quiet flag.

npx husky add .husky/prepare-commit-msg 'npx jira-prepare-commit-msg --quiet $1'

For Husky 2-4

Inside your package.json add a standard husky npm script for the git hook

{
  "husky": {
    "hooks": {
      "prepare-commit-msg": "jira-prepare-commit-msg"
    }
  }
}

Configuration

Starting with v1.3 you can now use different ways of configuring it:

  • jira-prepare-commit-msg object in your package.json
  • .jirapreparecommitmsgrc file in JSON or YML format
  • jira-prepare-commit-msg.config.js file in JS format

See cosmiconfig for more details on what formats are supported.

package.json example:

{
  "jira-prepare-commit-msg": {
    "messagePattern": "[$J] $M",
    "jiraTicketPattern": "([A-Z]+-\\d+)",
    "commentChar": "#",
    "isConventionalCommit": false,
    "conventionalCommitPattern": "^([a-z]+)(\\([a-z0-9.,-_ ]+\\))?!?: ([\\w \\S]+)$",
    "allowEmptyCommitMessage": false,
    "gitRoot": "",
    "allowReplaceAllOccurrences": true,
    "ignoredBranchesPattern": "^(master|main|dev|develop|development|release)$",
    "ignoreBranchesMissingTickets": false
  }
}

Supported message pattern

jira-prepare-commit-msg supports special message pattern to configure where JIRA ticket number will be inserted.

  • Symbols $J will be replaced by the JIRA ticket number
  • Symbols $M will be replaced by the commit message.

Pattern [$J]\n$M is currently enabled by default.

{
  "jira-prepare-commit-msg": {
    "messagePattern": "[$J]\n$M"
  }
}
Examples
  • [$J] $M
  • [$J]-$M
  • $J $M

NOTE: the supplied commit message will be cleaned up by strip mode.

Replacing all occurrences

jira-prepare-commit-msg supports by default replacing all occurrences variables in message pattern.

{
  "jira-prepare-commit-msg": {
    "allowReplaceAllOccurrences": true
  }
}
Examples

If set the message pattern to [$J] $M. \n Line for CI ($J): $M, then all occurrences will be replaced:

[JIRA-1234] test message.
Line for CI (JIRA-1234): test message

Supported JIRA ticket pattern

jira-prepare-commit-msg allows using custom regexp string pattern to search JIRA ticket number.

Pattern ([A-Z]+-\\d+) is currently supported by default.

NOTE: to search JIRA ticket pattern flag i is used: new RegExp(pattern, i')

{
  "jira-prepare-commit-msg": {
    "jiraTicketPattern": "([A-Z]+-\\d+)"
  }
}

Git comment char

Git uses # by default to comment lines in the commit message. If default char was changed jira-prepare-commit-msg can allow set it.

{
  "jira-prepare-commit-msg": {
    "commentChar": "#"
  }
}

Allow empty commit message

The commit message might be empty after cleanup or using -m "", jira-prepare-commit-msg might insert the JIRA ticket number anyway if this flag is set.

{
  "jira-prepare-commit-msg": {
    "allowEmptyCommitMessage": true
  }
}

Git root

The git root folder might be set. It is either absolute path or relative path which will be resolved from cwd

{
  "jira-prepare-commit-msg": {
    "gitRoot": "./../../"
  }
}

The package will search commit message so:

const pathToGit = path.resolve(cwd, './../../');
const pathToCommitMessage = path.join(pathToGit, '.git', 'COMMIT_EDITMSG');

Ignoring branches

Branches can be ignored and skipped by regex pattern string

{
  "jira-prepare-commit-msg": {
    "ignoredBranchesPattern": "^main|develop|(maint-.*)$"
  }
}

Moreover, this can be solved by replacing the Husky hook. Put in your prepare-commit-msg file (husky git hook):

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

if [[ "$(git rev-parse --abbrev-ref HEAD)" =~ YOUR_BRANCH_REGEX ]]; then
npx --no-install jira-prepare-commit-msg $1
fi

where YOUR_BRANCH_REGEX e.g. ^(feature|(bug|hot)fix)\/[A-Z]+-[0-9]+$

Silently ignore any branch that does not have a jira ticket in it

Be silent and skip any branch with missing jira ticket

{
  "jira-prepare-commit-msg": {
    "ignoreBranchesMissingTickets": true
  }
}

Conventional commit

jira-prepare-commit-msg supports conventional commit. To insert JIRA ticket number to the description set the following setting:

{
  "jira-prepare-commit-msg": {
    "isConventionalCommit": true
  }
}

NOTE: For description will be applied messagePattern

Examples

If the configuration is:

{
  "jira-prepare-commit-msg": {
    "messagePattern": "[$J] $M",
    "isConventionalCommit": true
  }
}

and commit message is fix(test)!: important changes then at result will be fix(test)!: [JIRA-1234] important changes

Additionally, you can customize the conventional commit format with the following setting:

{
  "jira-prepare-commit-msg": {
    "conventionalCommitPattern": "^([a-z]+)(\\([a-z0-9.,-_ ]+\\))?!?: ([\\w \\S]+)$"
  }
}

The above regular expression is the default conventional commit pattern so, if you don't provide this property, jira-prepare-commit-msg will use this by default.

In the default regular expression, from left to right:

  • ([a-z]+) is the commit type.
  • (\\([a-z0-9.,-_ ]+\\))?!? is the commit scope.
  • And ([\\w \\S]+) is the commit subject.

With this setting you can change how jira-prepare-commit-msg reads your custom conventional commit message and rewrite it adding the Jira ticket id.

Examples

You can allow the scope to have capital letters adding A-Z to the regular expression above. If the configuration is:

{
  "jira-prepare-commit-msg": {
    "messagePattern": "[$J] $M",
    "isConventionalCommit": true,
    "conventionalCommitPattern": "^([a-z]+)(\\([a-zA-Z0-9.,-_ ]+\\))?!?: ([\\w \\S]+)$"
    //                                             ^^^
    //                 Now we can use capital letters in the conventional commit scope
  }
}

and commit message is "test(E2E): some end-to-end testing stuff" then at result will be "test(E2E): [JIRA-1234] some end-to-end testing stuff"

Be aware that if you leave the default conventionalCommitPattern value (that it not allows capital letters in the commit scope), and the same values for messagePattern and isConventionalCommit in the example above, your resulting message will be "[JIRA-1234] test(E2E): some end-to-end testing stuff". Maybe, this is not the result you are expecting and you can have problems using other tools like commitlint.

TODO

  • Support user patterns
  • Support configuration (package.json)
  • Lint
  • Tests
    • Test for configuration
  • Don't clear commit message

License

MIT

jira-prepare-commit-msg's People

Contributors

bk201- avatar cmdlucas avatar demwunz avatar dependabot-preview[bot] avatar dependabot[bot] avatar mattcolman avatar mrrefactoring avatar onkeltem avatar robertmassaioli avatar thomasburguiere avatar webdevnerdstuff avatar xanterx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jira-prepare-commit-msg's Issues

Feature Request: Usage of jira-prepare-commit-msg in a shared husky config

Is there a way that we could support jira-prepare-commit-msg when implemented within a shared husky config package?

From the readme, it seems as every application consuming the shared husky config file would need to define their own jira-prepare-commit-msg configuration file or to inherit/extend a configuration file that the shared config package exports?

conventional commit scope is optional

Hey,

thanks for creating this! I think there is a tiny issue where the conventional commit specification allows scope to be optional. So fix: my message is a valid message. fix(backend): my message is the same but with a (backend) scope. The regex used in the code returns undefined when it can't match scope.

This currently gets written back to the commit message as undefined which is incorrect and break the conventional commit. e.g. fixundefined: JIRA-999 my message.

It's easy to fix though! Line 145 of git.ts you can replace the scope wit an empty string if it's not set.

lines[0] = `${type}${scope || ''}: ${replaceMessageByPattern(jiraTicket, msg, config.messagePattern)}`;

Now we get fix: JIRA-999 my message πŸ‘Sorry, I cant create PRs here.

Error: The JIRA ticket ID not found when branch contains digit

When branch name contains digits like feature/FOFRD36 the following error occurs: Error: The JIRA ticket ID not found.
In the code there is a regex: jiraTicketPattern: '([A-Z]+-\d+)'
with this regex it works: ([A-Z0-9]+-\d+)

Could you make it works with digit?

Do not work for sub folders

I have husky + this in the package file in a sub folder "ui", not in root of the repo. And it fails at the last step:

JIRA prepare commit msg > Error: Unable to read the file ".git/COMMIT_EDITMSG".

What is the issue? You should already know the git root from before? Not always assume that you are located in the root path.

To verify I changed this line quickly and then it works all the way:
const messageFilePath = "../" + getMsgFilePath();

the configuration not working on different machine

I have setup the jira-prepare-commit-msg & huskey on my windows machine and its working fine means whenever I commit it's appending jira-id into my commit msg. I pushed and merged my changes to the master branch and take pull to a different machine(mac)
on mac machine, the Jira id is not appending. do I have to setup as mentioned in the doc on every machine?

Unable to read the file ".git/COMMIT_EDITMSG"

Same as issue #11 which has been closed.

If working in a subdirectory where package.json is not at the root directory, the following error message is outputted:

JIRA prepare commit msg > Error: Unable to read the file ".git/COMMIT_EDITMSG".

Bug: Duplicated ticket injection

Consider using an IDE like vsc.

  1. commit a message - It will inject the ticket successful.
  2. undo the commit
  3. commit again - The suggested message will already include the ticket (as defined .git/COMMIT_EDITMSG). The ticket would be injected a second time

Aborting commit message should abort commit

Expected behaviour: I use Vim for my commit messages, when I type in :qa! to abort the commit message then a commit should not occur.

Actual behaviour: I get a commit message with just the Jira key in the message and my changes are saved.

What would we have to modify such that if the editor aborts the message so too does jira-prepare-commit-msg?

Don't support git directories with "spaces" in their path

Giving me this following error in case there is a space in the path of the git directory

JIRA prepare commit msg > start
JIRA prepare commit msg > Error: Command failed: git --git-dir=/Users/xan/Folder - Name/projectname.git symbolic-ref --short HEAD
unknown option: -
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

JIRA prepare commit msg > done

Seems like need to escape --git-dir with double quotes here

cp.exec(`git --git-dir=${gitRoot} symbolic-ref --short HEAD`, { encoding: 'utf-8' }, (err, stdout, stderr) => {

Commit message contains new line between JIRA issue and message

I understand that this is customizable but just wondering why is the default behavior to include a \n between the JIRA issue and commit message?

This means when creating a PR in BitBucket, the default PR title would only contain the JIRA issue, for example [JIRA-123] rather than infer the PR title from the commit message.

Support punctuation in Conventional Commit Message.

const conventionalCommitRegExp = /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z ]+\)!?)?: ([\w ]+)$/g;

should change to:

const conventionalCommitRegExp = /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z ]+\)!?)?: ([\w \S]+)$/g;

Issue:
When using Conventional Commits and you type a message like:

chore(deps): Finally solved that problem!

the regex fails to identify the message part, resulting in the jira ticket number being added in the wrong place.

add support for husky 9

Unusable with husky v9

When using husky 9, the command fails with husky install is deprecated and husky add is deprecated:

~/temp_repositories/deletemerepo on main ?1 ........................................................................................................................................ took 9s at 20:15:40
> npm install husky jira-prepare-commit-msg --save-dev && npx husky install

added 27 packages, and audited 28 packages in 1s

4 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
install command is deprecated
~/temp_repositories/deletemerepo on main ?3 ................................................................................................................................................ at 20:16:08
> npx husky add .husky/prepare-commit-msg 'npx jira-prepare-commit-msg $1'
add command is deprecated

Workaround

Use husky v8 instead for now until husky 9 support is added

npm install [email protected] jira-prepare-commit-msg --save-dev && npx husky install

Mandatory jira ID

I can't find a way to add the ID as mandatory for all commits messages even when users are committed from master or develop brances

Git rebase throws error when applying rebase

When I use git rebase -i `git merge-base HEAD master` --rebase-merges and apply the rebase I get this error message repeated for each commit, even though it doesn't block the rebase:

JIRA prepare commit msg > done
JIRA prepare commit msg > start
JIRA prepare commit msg > Error: Command failed: git --git-dir="/Volumes/SourceCode/myrepo/.git" symbolic-ref --short HEAD
fatal: ref HEAD is not a symbolic ref

Running this in terminal succeeds:

$ git --git-dir="/Volumes/SourceCode/myrepo/.git" symbolic-ref --short HEAD
develop

Can't write numbers in conventional commit scope.

Hi! Thank you for your work creating this tool, it is very useful.

In the specification of conventional commits it is not specified whether the scope can contain numbers or not, but if you now have the isConventionalCommit property set to true and the scope field contains some number in the commit message, then the resulting message is not as expected (as stated in the README documentation).

For example:

With the following configuration:

{
  "jira-prepare-commit-msg": {
    "messagePattern": "[$J] $M",
    "isConventionalCommit": true
  }
}

If the commit message is:

test(e2e): add Cypress to project

The resulting message is:

[JIRA-4321] test(e2e): add Cypress to project (BAD)

But the expected result message is:

test(e2e): [JIRA-4321] add Cypress to project (EXPECTED)

However, if the commit message is:

test: add Cypress to project

or

test(integration): add Cypress to project

Then, the result message is:

test: [JIRA-4321] add Cypress to project (GOOD)

or

test(integration): [JIRA-4321] add Cypress to project (GOOD)

Is this a bug or is it working this way on purpose? Thank you

"prepare-commit-msg" hook does not work for "git commit" without "-m <msg>"

It seems prepare-commit-msg hook does not work with git commit via editor.

Dependencies

git version 2.25.0

"husky": "~4.2.5",
"jira-prepare-commit-msg": "~1.4.1"

Failure

JIRA prepare commit msg > TypeError: Cannot read property 'replace' of undefined

Solution

Simply switch from prepare-commit-message -> commit-msg hook.

"husky": {
    "hooks": {
      "commit-msg": "jira-prepare-commit-msg"
    }
  }

It does not work with multiple scopes

Branch: feature/TEST-1
Example commit message:
feat(scope1,scope2.scope3): new feature

It changes commit message to:
[TEST-1] feat(scope1,scope2.scope3): new feature
which causes that commitlint throws errors:

βœ–   subject may not be empty [subject-empty]
βœ–   type may not be empty [type-empty]

Expected commit message:
feat(scope1,scope2.scope3): [TEST-1] new feature

Makes nothing

After installation, I cannot trigger its activity: I make commits, but jira-repare-commit-msg does nothing.
How it should look, when it's installed and working? Which files, where?
In my .husky/ directory there is only one file: the default sample pre-commit.

node 16
npm 8
kubuntu 22.04

Add support for .cjs config file

Hey,

I was configuring a new project today and I decided to consolidate all the configuration files, using a .cjs extension. While using your package I noticed I could not get the config file running as a .cjs file.

But this was easily fixed by adding one line in the src/config.ts file.

Today I used patch-package to patch [email protected] so it's doable on my personal project.

Here is the difference that solved my problem:

diff --git a/node_modules/jira-prepare-commit-msg/bin/config.js b/node_modules/jira-prepare-commit-msg/bin/config.js
index b51d947..b268a2a 100644
--- a/node_modules/jira-prepare-commit-msg/bin/config.js
+++ b/node_modules/jira-prepare-commit-msg/bin/config.js
@@ -33,6 +33,7 @@ async function loadConfig(configPath) {
                 '.jirapreparecommitmsgrc.yaml',
                 '.jirapreparecommitmsgrc.yml',
                 'jira-prepare-commit-msg.config.js',
+                'jira-prepare-commit-msg.config.cjs',
             ],
         });
         const config = configPath ? await explorer.load(resolveConfig(configPath)) : await explorer.search();

For context, if somebody else wants to use this as well:

This is my working jira-prepare-commit-msg.config.cjs file:

const config = {
  messagePattern: '[$J] $M',
  jiraTicketPattern: '([A-Z]+-\\d+)',
  isConventionalCommit: true,
  conventionalCommitPattern: '^([a-z]+)(\\([a-z0-9.,-_ ]+\\))?!?: ([\\w \\S]+)$',
  allowEmptyCommitMessage: false,
  allowReplaceAllOccurrences: true,
  ignoredBranchesPattern: '^(master|main|dev|develop|development|release)$',
  ignoreBranchesMissingTickets: false,
}

module.exports = config

I went into the node_modules folder and edited the node_modules\jira-prepare-commit-msg\bin\config.js file with the code listed above. After that, I ran yarn patch-package jira-prepare-commit-msg. (Please note, you will have to install patch-package and postinstall -> yarn add -D patch-package postinstall)

I also added "postinstall": "patch-package" to scripts in my package.json file so the patch is applied every time somebody installs the project on their own environment.

Config for branches to ignore

Can we have a config for a list of branches to ignore?

Either a pattern, or an array. For example, I don't want this script to run when I'm on either of these branches - master develop.

Basically, I don't want an error to display like below when I'm on a branch without a JIRA ticket ID like develop.

JIRA prepare commit msg > start
JIRA prepare commit msg > Error: The JIRA ticket ID not found
JIRA prepare commit msg > done
✨  Done in 0.12s.

Issues with `git commit -v`

Hello @bk201-

We just noticed that using this package with the "prepare-commit-msg" hook, will wipe out the comments you get whenever you do git commit -v.

In this image, you'll see what I'd expect to see on the left vs what's actually happening on the right.

Version

"jira-prepare-commit-msg": "1.4.2",

Steps to reproduce

  1. Make one change
  2. Type git commit -v

Expected result

I should see the diff from git commit -v, plus, the Jira ticket message that we have in this package config

Actual result

We get the Jira ticket message that we have in this package config.


Are we missing something in our configuration? or maybe, we're using the wrong commit hook?

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.