gitgit-husky

How to prevent direct commits to master branch using husky?


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?


Solution

  • 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 :)