Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to commit the pre-commit hooks?

Tags:

git

We set up a pre-commit hook for our Python project. The pre-commit sits in the .git folder which is untracked (for good reason).

But it's quite common for someone new to clone a repo and forget to get up the commit hook. Is it possible to automate this? E.g. by having the commit hook tracked by git? Or via some other mechanism e.g. when git clone is called the hook is automatically set up.

For example, adding the !.git/hooks/pre-commmit to .gitignore doesn't do the trick.

like image 360
xiaodai Avatar asked Oct 18 '25 03:10

xiaodai


2 Answers

It's possible but not recommended.

When a repository is initialized, it copies hooks from git template. We can create a post-checkout in the template. Here's a sample:

#!/bin/bash

gitworktree=$(git rev-parse --show-toplevel)
if [[ -f ${gitworktree}/pre-commit ]];then
    echo deploy pre-commit
    cp -v ${gitworktree}/pre-commit ${gitworktree}/.git/hooks/pre-commit
    chmod a+x ${gitworktree}/.git/hooks/pre-commit
fi

After git clone without -n, the post-checkout is copied to the new repository's .git/hooks automatically. And then the code is checked out and it invokes post-checkout. If pre-commit exists in the new repository, it's copied to .git/hooks. This is just a draft plan. There might be some issues in a real case. For example, how can we deal with the pre-commit which already exists in the template? Is it necessary to check if the pre-commit is a committed one? What if there are vicious codes in pre-commit?

As other answers say, it's not a good idea. Don't do it in production envirionment.

like image 200
ElpieKay Avatar answered Oct 21 '25 01:10

ElpieKay


Have a look at https://pre-commit.com/

You can create a separate repository with your hooks and use it in your projects. Usage is configured via YAML-files.

like image 36
BernarditoLuis Avatar answered Oct 21 '25 02:10

BernarditoLuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!