Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify file before commit with pre-commit hook

I am trying to write a pre-commit hook that modify a line in my code but I do not know even from where to start.

The problem is:

I have a KEY

public static final String APP_KEY = ""; //DELETE THE KEY BEFORE COMMIT!!!

In order to avoid publishing the KEY to the repository I've think maybe git hooks are the thing we need instead of delete the key manually. I've take a look at Customizing git hooks but I do not know how to write the hook.

Is there a way to before commit the changes, delete the KEy and after the commit write the key again?

like image 209
Alejandro Alcalde Avatar asked Aug 09 '14 09:08

Alejandro Alcalde


People also ask

How do you bypass a pre-commit hook?

Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.

How do I update pre-commit?

You can update your hooks to the latest version automatically by running pre-commit autoupdate . By default, this will bring the hooks to the latest tag on the default branch.

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.

What does pre-commit hook do?

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.


1 Answers

That would be done with a content filter driver:

  • a clean script which would remove the key on checkin
  • a smudge script which would add it back on checkout.

smudge

(image from "Customizing Git Attributes" from the Git Book)

See an example of how those filters are declared in "Can git automatically switch between spaces and tabs?"

like image 189
VonC Avatar answered Sep 20 '22 18:09

VonC