The Walrus
The Walrus

Reputation: 1208

Run a validation script before allowing any commit in a given repo

I want to run a script locally whenever someone in RepoA, makes a commit on a branch

currentBranch=$(git rev-parse --abbrev-ref HEAD)

if [[ $currentBranch = *"my-"* ]]; then
  echo "contains my"
else
  echo "Hold on there! you need to rename your branch before you commit!
  "
fi

I have this running so far which works, whenever I run npm run test:script it runs > "test:script": "./branchname.sh"

however, I have some issues. one how can I run this every time someone commits?

I have tried putting it in my package.json

  "pre-commit": [
    "lint",
    "test:script"
  ],

but it doesn't run on every commit

also, how can I get the commit itself to abort if the script fails, i.e. jump into the else block

Upvotes: 5

Views: 5920

Answers (1)

xyzale
xyzale

Reputation: 795

You can take advantage of git hooks. There is a bunch of files you can find in your .git/hooks folder whitin your project folder.

Here the full documentation: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks (updated in 2024)

Note that you need to give exec permissions to hook files.

Hooks can be basically bash files, so you can abort the commit exiting with a value != 0.

Here an example: https://github.com/xyzale/my-stuff/blob/master/git/hooks/pre-commit

In order to share the hooks with your collaborators you can add a hooks/ folder to your repository and either symlinking it to .git/hooks or editing the git config about the hooks location through the command

git config core.hooksPath hooks

Upvotes: 5

Related Questions