Modify file before commit with pre-commit hook

Issue

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?

Solution

That could be done with a content filter driver:

  • a clean script which would remove the key on checking,
  • 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?".

Caveat:

As noted by Juan Alonso in the comments:

I’ve had nothing but trouble with the clean/smudge scripts for a similar use-case, depending on the file contents unattended runs of git add -A would or wouldn’t run the filter (as opposed to always working when calling git in attended mode).

So I ended up going with a pre-commit hook.

Answered By – VonC

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published