Search code examples
pythongitgit-diff

git diff custom hunk header not showing correct function


I am trying to customize the git diff hunk header for Python. I am currently using the "python" regex pattern as defined here: https://github.com/git/git/blob/6d2f208c3dd39493f4d45ea67c55a1b7fe06626a/userdiff.c

The hunk header seems to be able to correctly display the class or function in which the changes occurred for the most part. However, the issue comes when I make a change in the couple of lines right after the function definition, as shown below in func2.

def func1():
   print('hello')

def func2():
   #some change here
   print('bye')

For this change, my hunk header would look something like

@@ -k,l +m,n @@ def func1():

so even though the change occurred within func2, the hunk header incorrectly indicates that it is occurring in func1. Is there any way to change the regex pattern so that the hunk header displays the correct function? I think it may have something to do with the length of the git diff context. Right now for a change to a single line, the spaces indicated by the letters "l" and "n" in the header display 7, meaning that the git diff shows 7 lines. How do I change the letters k,l,m,n in the hunk header and customize the length of the git diff context?


Solution

  • This is not defined as a bug by the Git folks. (Not everyone agrees on this...)

    If you examine the diff hunk, you'll see that the context lines extend backwards into func1. The context is therefore that of func1(), not of func2. The changed lines are exclusive to func2(), but the context is that of func1.

    I think it may have something to do with the length of the git diff context. Right now for a change to a single line, the spaces indicated by the letters "l" and "n" in the header display 7, meaning that the git diff shows 7 lines. How do I change the letters k,l,m,n in the hunk header and customize the length of the git diff context?

    That's correct. The amount of context shown is determined by the -U argument to git diff. The default value, if you don't supply -U (or --unified, the long name version of the same option) is 3.

    Note that there are numerous additional controls for the diff.