Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out all GIT changes in a certain line in a file

Tags:

git

I have a line of code that was changed recently into a non-working state.

How can I find out who and in which commit changed this particular line?

I tried

git log -some_distinct_string_from_that_line --pretty=format:'%h %an -- %s -- %ad'

Which shows all commits with comments and authors that changed anything where a line contained "one_distinct_string_from_that_line", but how can I see the actual changes they made?

EDIT:
I also installed git-gui and looked at the line with git gui blame filename but there is only one commit change for that line shown, although there definitely have been more changes.

I checked with the graphical gui smartgit to look through all changes made on that file by hand and I found 3 commits, where that line was definitely edited (a # was first removed and then in another commit added again)

Is there another way that doesn't relay on the git blame functionality, and doesn't relay on the assumption, that the line is in the commit-diff?

like image 868
rubo77 Avatar asked Sep 14 '25 08:09

rubo77


2 Answers

git blame. The -L option takes a range of lines and you can select a file as for git log. So git blame -L 10,20 -- my/file.txt will show the most recent git commit that touched each of the lines in that file. git gui blame my/file.txt does the same job but with a UI to let you browse back in time.

like image 52
patthoyts Avatar answered Sep 17 '25 04:09

patthoyts


You can add the following line into your .git/config file in the [alias] section:

findchange = !sh -c \"git log --pretty=format:'COMMIT %C(yellow)%h %an -- %s -- %ad%C(reset)' -G'$1' -p --word-diff-regex='[A-Za-z0-9]+|[^A-Za-z0-9]|$1' --color=always ${@:2} | egrep '$1|^COMMIT|-{3} a\\/|\\+{3} b\\/' \"

Then, just execute the following command at the command line:

git findchange 'yourText'

Explanation:

  • I modified your pretty format slightly so that you will be able to spot the beginning of each commit.
  • Using the -p options for log, which displays a patch, hence the p, for each commit.
  • Using the --word-diff-regex option to define a word. This will display changes inline grouped by whole words or single non-word characters.
    • Included the search text itself as part of the regex; otherwise, it does not catch cases where the change spans words
  • --color=always preserves the coloring even when piping to egrep.
  • egrep finds all lines that are one of the following:
    • the commit message
    • the text you are searching for (either deleted or added)
    • the original name of the changed file
    • the new name of the changed file
like image 44
Joseph K. Strauss Avatar answered Sep 17 '25 04:09

Joseph K. Strauss