7

I am using husky to run git hooks.

"husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }

I want to prevent direct commits to master branch. It should allow the master branch to be updated only by merge requests.

I came across following code from Git: Prevent commits in master branch. I copied this to .git/hooks/pre-commit and it works

#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ]; then
  echo "You can't commit directly to master branch"
  exit 1
fi

But I want to achieve this using husky. How do I do that?

It worked yesterday.
  • 4,507
  • 11
  • 46
  • 81

3 Answers3

13

I created a file with the content provided from OP.

file: hooks/pre-commit

#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ]; then
  echo "You can't commit directly to master branch"
  exit 1
fi

Then I added an entry to husky pre-commit field in package.json

  "husky": {
    "hooks": {
      "pre-commit": "sh hooks/pre-commit",
    }

No more commits to master :)

George Sofianos
  • 1,141
  • 1
  • 13
  • 26
4

With git-branch-is you can block commits with husky in master branch

"pre-commit": "git-branch-is -r \"^((?!master).)*$\""
Gregor Albert
  • 819
  • 1
  • 11
  • 23
4

I don't think that's the right place to make this restriction because it can easily be bypassed. As an alternative, I would recommend you to modify the protection rules of the repository/branch.

Here is how it's done with GitHub and Bitbucket:

I know it's a different approach but I hope it's helpful too.

Jan Fässler
  • 696
  • 8
  • 17