How to prevent direct commits to master branch using husky?
Asked Answered
G

3

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?

Gamut answered 11/7, 2019 at 10:54 Comment(0)
B
14

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

Bentley answered 25/9, 2020 at 8:59 Comment(0)
E
3

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

"pre-commit": "git-branch-is -r \"^((?!master).)*$\""
Ekaterinodar answered 21/8, 2019 at 8:31 Comment(1)
there is a --not since github.com/kevinoid/git-branch-is/pull/29Yann
T
3

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.

Trippet answered 11/12, 2019 at 16:22 Comment(1)
As a side note, It can't prevent pushing from adminPentode

© 2022 - 2024 — McMap. All rights reserved.