# Precommit Hook

## Automatically prefix JIRA issue numbers to Git commit messages <a href="#id-00e1" id="id-00e1"></a>

When we are lazy, you know it can get a little annoying having to type the issue number in every commit message. We can easily automate this using the [git prepare-commit-message hoo](https://git-scm.com/docs/githooks)k which can prepend commit messages with JIRA issue number to the commit message extracted from the git branch name ([and get the benefits of Smart Commits](https://confluence.atlassian.com/bitbucket/processing-jira-software-issues-with-smart-commit-messages-298979931.html#ProcessingJIRASoftwareissueswithSmartCommitmessages-SmartCommitcommands)). You can use this trick for any issue tracker you might use. Read more to know how to do this.

> TICKET-123 — a useful commit message

## Naming your git branches <a href="#id-67a4" id="id-67a4"></a>

For this technique to work, you need to make sure that you include the issue number in the name of the git branch. You can use the [git flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow#:~:text=Gitflow%20Workflow%20is%20a%20Git,designed%20around%20the%20project%20release.\&text=In%20addition%20to%20feature%20branches,%2C%20maintaining%2C%20and%20recording%20releases.) naming convention as long as the ticket number is in the branch name. Here are some examples:

* AWESOME-1234
* THING-4456
* feature/PANTS-1234
* fix/LOL-1567

<details>

<summary>Linux/macOS</summary>

We can create a `prepare-commit-message` git hook script to automatically extract ticket number from git branch name and prepend it to the commit message.

### Step 1: Create the git hook file <a href="#id-5e17" id="id-5e17"></a>

* Open the `.git/hooks` directory in your project's root
* Open `prepare-commit-message.sample` file with vscode (or your favourite code editor)
* Remove the sample boilerplate code

### Step 2: Add script to be run on commit <a href="#id-7f50" id="id-7f50"></a>

* Copy and paste the following script into the file
* Rename and save the file as `prepare-commit-message` (remove the \`.sample\`)
* Go through the comments in the script and modify the variables as you deem appropriate
* Commit a test commit message

That’s it 🎉🎉🎉 You should see your commit being prepended with the issue number extracted from your branch name

</details>

<details>

<summary>Windows</summary>

On Unix-like operating systems, the `#!` (she-bang) is called the interpreter directive. This tells the operating system to execute the current file using the path to the interpreter’s executable that follows it. `/bin/bash` is the path to the interpreter you want to use. In this case, we’re using bash.

This will be meaningless in windows as it is not Unix like. [Git for Windows](https://git-scm.com/download/win) can run Bash commands and shell scripts via [Cygwin](https://www.cygwin.com/). We just need to change the interpreter path to make this work.

```
#!C:/Program\ Files/Git/usr/bin/sh.exe
```

*Note: You need to escape spaces with `\` in windows paths*

That’s it and your hook should now work on windows too!

</details>

## JavaScript Projects (Cross Platform) <a href="#id-6460" id="id-6460"></a>

The bash script solution will still work for JavaScript projects. But if you want to stay away from bash scripts there is an alternative solution we can use.

We will use `husky` and `jira-prepare-commit-msg` as dev dependencies to help us achieve our goal.

* [husky](https://www.npmjs.com/package/husky) is a handy tool to manage git hooks for JavaScript projects from package.json file (or a config file)
* [jira-prepare-commit-msg](https://www.npmjs.com/package/jira-prepare-commit-msg) is an npm CLI module which does exactly what we want

### Step1: Install the dependencies <a href="#b724" id="b724"></a>

```
npm install husky jira-prepare-commit-msg --save-dev
```

or

```
yarn add --dev husky jira-prepare-commit-msg
```

### Step 2: Prepare Commit Message hook <a href="#id-659b" id="id-659b"></a>

Add the following configuration to your `package.json` file to invoke `jira-prepare-commit-msg` when the prepare-commit-message is triggered

```
// package.json
{...
  "husky": {
    "hooks": {
      "prepare-commit-msg": "jira-prepare-commit-msg"
    }
  }
...
}
```

### Configuration <a href="#c61f" id="c61f"></a>

You can configure `jira-prepare-commit-message` to use custom message pattern or ticket number pattern. You can also set a comment character and specify if you use conventional commit (which you should!).\
You can also see package’s readme [here](https://www.npmjs.com/package/jira-prepare-commit-msg) to know more configuration details.

```
// package.json
{
  ...    "jira-prepare-commit-msg": {        "messagePattern": "[$J]\n$M",        "jiraTicketPattern": "([A-Z]+-\\d+)",        "commentChar": "#",        "isConventionalCommit": false    }
  ...
}
```

### NVM Users Please Note <a href="#efb7" id="efb7"></a>

If you use [Node Version Manager (NVM)](https://github.com/nvm-sh/nvm), husky will automatically use the node version that is set by nvm on your shell. If you use a git GUI client like GitKraken or Source Tree, they may fall back to using the default node version. So, you may have to set your default node version to your most used project’s node version. If you know any other solution, I would love to know it in the comments below. Also, if you’re tired of typing `nvm use` each time you open a terminal in a JavaScript project, [this article](https://medium.com/javascript-in-plain-english/nvm-on-steroids-auto-switch-nodejs-version-in-your-terminal-without-typing-the-nvm-use-command-3a49c4b5c6e0) will show you how to never have to do this again!

## Conclusion <a href="#id-58bf" id="id-58bf"></a>

Having issue numbers in commit messages can be very useful for tracking commits in your issue tracker. However, manually adding the issue number takes time and is easy to forget. In this article, we learnt how to automate this using prepare-commit-message git hooks.

Many issue trackers like [JIRA](https://confluence.atlassian.com/fisheye/using-smart-commits-960155400.html), [GitHub](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue), [Azure DevOps](https://devblogs.microsoft.com/devops/linking-work-items-to-git-branches-commits-and-pull-requests/) support smart commits which automatically associate commit messages or Pull Requests with issue numbers to the appropriate issue. If you want to learn and understand git better, check this book out

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://devops.kaleyra.io/gitops/precommit-hook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
