AlexTes AlexTes - 1 month ago 12
Git Question

How to create a proper patch when removing a function and its docblock with git

When you have docblocks above multiple functions removing a function creates a sub-optimal patch.

index.js:

/**
* Function foo description.
*/
function foo() {}

/**
* Function bar description.
*/
function bar() {}


Removing function foo with its docblock generates the following patch:

diff --git a/index.js b/index.js
index f4e18ef..933004f 100644
--- a/index.js
+++ b/index.js
@@ -1,9 +1,4 @@
/**
- * Function foo description.
- */
-function foo() {}
-
-/**
* Function bar description.
*/
function bar() {}


This means that any merge that brings with it commits that touch the space between function foo and function bar now result in a conflict.
For example imagine we created a branch
feature-1
before removing foo, and in
index.js
added a function
foobar
between the two. The conflict would look as follows:

/**
<<<<<<< HEAD
=======
* Function foo description.
*/
function foo() {}

/**
* Function foobar description.
*/
function foobar() {}

/**
>>>>>>> feature-1
* Function bar description.
*/
function bar() {}


I imagine there would be no issue if the
/**
was grabbed from the top instead. I'm sure there's a good reason for git to prefer removing from the end but I'd like to force it to grab it from the start. Is there a way to easily do this? Or is manual patch editing the only way?

Answer

It's far from perfect, but the new --compaction-heuristic in Git 2.9 often does what you want. See this blog post for details. You can configure it to be on by default, but given that it sometimes makes things worse, I have not done so:

git config --global diff.compactionHeuristic true

Your Git version must be at least 2.9 for this to have any effect.