Skip to content

Instantly share code, notes, and snippets.

@bonniesimon
Last active September 25, 2022 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonniesimon/85df846e221d0e0a9b4c7263f59c269f to your computer and use it in GitHub Desktop.
Save bonniesimon/85df846e221d0e0a9b4c7263f59c269f to your computer and use it in GitHub Desktop.
Added the necessary hooks to prevent push to master.

Create a file .husky/helpers/prevent_pushing_to_master.sh and add the following contents:

  #!/bin/sh
  
  prevent_pushing_to_master() {
    current_branch=`git symbolic-ref HEAD`
    current_origin=`git remote`
    if [ current_origin = "origin" -o "$current_branch" = "refs/heads/master" -o "$current_branch" = "refs/heads/master" ]
    then
    cat <<EOT
  ======================================================================================
  You are not authorized to push/commit directly to master/main branch in origin remote.
  Push from a new branch and make the PR.
  
  Or if you are 100% sure you want to push/commit to master/main branch,
  then pass in the optional --no-verify option with the git command.
  
  Example:
  # Warning: pushing to master is not recommended
  git push origin master --no-verify
  ======================================================================================
  EOT
      echo "";
      exit 1;
    fi
  }
  

Then head over and create a file .husky/pre-push and add the following:

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

Then go over to .husky/pre-commit and update the file as so (Updated lines are marked with #(+) at the end)

  #!/bin/sh
  . "$(dirname "$0")/_/husky.sh"
  . "$(dirname "$0")/helpers/lint_staged.sh"
  . "$(dirname "$0")/helpers/prevent_pushing_to_master.sh" #(+)
  
  prevent_pushing_to_master #(+)
  lint_staged_files
  

Now we need to make the .husky/pre-push file an executable else husky will throw the followign error

  hint: The '.husky/pre-push' hook was ignored because it's not set as executable.
  hint: You can disable this warning with `git config advice.ignoredHook false`.

Run the following command to make .husky/pre-push an executable

chmod +x .husky/pre-push 

We're done. Now you won't be able to make commits on the master branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment