10

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?

Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79

1 Answers1

2

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Um, Thanks I will try to write a simple script. – Alejandro Alcalde Aug 09 '14 at 10:13
  • @algui91 yes, the idea is to be able to associate that script to a single file, or type of files, through the `.gitattributes` `filter` command. – VonC Aug 09 '14 at 10:16
  • this is lame. It's great to show a diagram but all this does is leave us with more questions than answers. Why not extend this with example code. – John Riselvato May 15 '18 at 03:27
  • @JohnRiselvato https://stackoverflow.com/a/2316728/6309 is (mentioned in the answer) suppose to illustrate an example of a clean/smudge script declared as content filter driver. don't hesitate to ask a new question (with a link back to this answer) in order to get additional information. – VonC May 15 '18 at 06:04
  • 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. – Juan Alonso Apr 23 '22 at 20:38
  • @JuanAlonso good point. That might be more reliable indeed. – VonC Apr 23 '22 at 21:04