Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically invoke a script before a git add?

Tags:

Here's my use case: I commit PNGs and other stuff in my Git repo. I would like to apply a specific process to every PNGs I would like to commit and this is the result of the process I finally want to commit (the potential modified PNG).

At the beginning I thought about a hook (like a pre-commit) but it's a little weird because the process will change the file so I will need to re-add it! And according to what I read, there is no pre-add hook (or something like that).

May be a solution is to create a git alias ? But I don't want to change - too much - the way people work, I'm searching for a smooth and transparent way.

If you have a clue... even if the clue is to change my process idea.

like image 261
Labynocle Avatar asked Sep 18 '13 16:09

Labynocle


People also ask

How do I run a git script before committing?

Open a terminal window by using option + T in GitKraken Client. Once the terminal windows is open, change directory to . git/hooks . Then use the command chmod +x pre-commit to make the pre-commit file executable.

How do I trigger a pre-commit?

If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook. Note that running a hook for the first time may be slow.

What is pre-commit hook in git?

The pre-commit hook is run first, before you even type in a commit message. It's used to inspect the snapshot that's about to be committed, to see if you've forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code.


2 Answers

You may want to consider a smudge & clean filter, with the clean being applied during the git add, and the smudge during checkout. These can be allocated by file type. Look at the 'git attributes(5)' man page and Git SCM book : Git Attributes.

like image 193
Philip Oakley Avatar answered Sep 19 '22 05:09

Philip Oakley


There may be a good reason to use clean instead, but there's actually nothing preventing you from re-adding the files during the pre-commit hook, which is a bit more intuitive in my opinion.

Your pre-commit would look something like:

*run your PNG processing here* (after processing completes) git add *.png

The commit will then continue as usual. If you want to get fancy you can throw an exit 1 in there when something goes wrong with the compression, and it will stop the commit.

like image 8
dlsso Avatar answered Sep 22 '22 05:09

dlsso