Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to 'script' a git commit - only accepting some diffs?

Tags:

git

pre-commit

I have applied some static code analysis - and transformed all Java package level fields into protected. This is mostly correct, as I forgot to set the access modifier explicitly, and protected is generally what I was after in those cases.

Unfortunately, the refactoring I applied was the IntelliJ weaken access modifiers on, and it also changes lots of public -> protected, on constructors and so on.

So once I have a diff with statements like this in it:

-int myField;
+protected int myField;

and

-public MyConstructor()
+protected MyConstructor()

Is there a way to write a script, that runs during the commit, and only lets the first example above, but no the second? I can figure out the script, and I am just not sure how to run it - is it a pre-commit hook?

If its a pre-commit hook, how do you examine the diff in such a script and accept/reject it based on greping it for some string?

like image 461
user2800708 Avatar asked Oct 31 '22 14:10

user2800708


1 Answers

Yep you can do it using smudge/filters

There are several ways to do it.

git hooks

git hooks is a script that run in a different phases of the git life-cycle.
In the proper hook file check the for the file/content that you need and do whatever you need with it.

The hook will run on your files and will check the syntax.

Smudge/clean

Basically, smudge is equivalent to run this code whenever you check anything out
and clean is equivalent to run this code whenever you check anything in.


Images are from this url: https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

enter image description here

like image 169
CodeWizard Avatar answered Nov 15 '22 06:11

CodeWizard