简体   繁体   中英

Git Diff defining incorrect hunk header for cpp file

I am using git diff to find out which methods have changed. Evidently its defining the hunk header incorrectly (as shown below) due to which I am not able to find a way to get the list of changed methods.


    @@ -22,7 +22,7 @@ void func2(){
     
     void func1(){
         cout<<"Function 1"<<endl;
    -    int i=1000;
    +    int i=100;
         while(i>0){
             func2();
             i--;

Here the change is in func1() but the hunk header is at func2(). I have tried changing some test functions, turns out it always selects the line/function above the required function as the hunk header.

I have tried creating a .gitattributes file in the root directory and placing *.cpp diff=cpp in order to enable cpp for diff, unfortunately that didn't solve the issue.

The issue here is that this diff is in function func2 .

Note that the diff begins with a blank line, followed by the definition of function func1 . This definition is inside the diff-hunk, so the diff-hunk begins before the function. Presumably, above the blank line we'll find more of the code of func2 . That's the context that git diff is telling you about: what comes before the diff.

One can (rather reasonably!) argue that the only change within the diff is within function func2 , but then what should Git do with a diff hunk that reads, eg:

 T f1() {
+    new_call();
     return somevalue;
 }
 T f2() {
-    old_call();
     return somevalue;
 }

Here, the diff affects two functions, f1 and f2 , internally. Git's answer to "how to label this" is to start above the entire text, and search backwards for some regular expression. If that matches f0 , that's the label that goes on the diff.

(Side note: the built in regexps work pretty well, but won't recognize all possible legal function definitions in all languages. Changing the amount of context displayed should help for this particular example, though you would have to shrink it down to at most 1 line.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM