DEV Community

Cover image for Using Git to track down deleted code in a large project
Possawat Sanorkam
Possawat Sanorkam

Posted on • Edited on

Using Git to track down deleted code in a large project

My code is now deleted in file A around line 800, and I do not know when it was deleted. How to find the person who deleted my code from git?

TLDR;

# Search from line
git blame -L 800,800 A

# Search from text
git log -S "CODE_TO_SEARCH" A
Enter fullscreen mode Exit fullscreen mode

To find out who deleted code from a file using git, you can use the git blame command. This command shows the last commit that modified each line of code in a file, along with the author and date of the commit.

To see the commit that deleted a specific line of code, you can use the git blame command with the -L option, which allows you to specify a range of lines. For example, to see the commit that deleted code around line 800 in file A, you can use the following command:

git blame -L 800,800 A
Enter fullscreen mode Exit fullscreen mode

This will show the commit that modified line 800 in file A, along with the author and date of the commit. If the code was deleted in this commit, it will also show the line of code that was deleted.

@hrnkas Git does not show deleted lines when using blame. It only shows information for remaining lines, and that is the commit information when those line have last been changed.

You can also use the git log command with the -S option to search the commit history for a specific string of code. This can be helpful if you don't know the exact line number where the code was deleted.

For example, to search for the commit that deleted a specific string of code from file A, you can use the following command:

git log -S "CODE_TO_SEARCH" A
Enter fullscreen mode Exit fullscreen mode

@hrnkas Actually, the exact solution would be git log -S "CODE_TO_SEARCH" -c --cc A
You also need -c and --cc flags to show commits where search text has been deleted.

Replace CODE_TO_SEARCH with the string of code you want to search for. This will show a list of commits that include the specified code, along with the commit message and any other information about the commit.

Surprise, this article was generated by ChatGPT!

Top comments (4)

Collapse
 
hrnkas profile image
Bojan Hrnkas

This is wrong! Git does not show deleted lines when using blame. It only shows information for remaining lines, and that is the commit information when those line have last been changed.

Collapse
 
parmcoder profile image
Possawat Sanorkam

Sorry for the mistake. Yes, you are right. (not generated by bot this time :P)

Collapse
 
hrnkas profile image
Bojan Hrnkas

For 'git log -S' solution, you also need -c and --cc flags to show commits where search text has been deleted.
So, complete solution is:
'git log -S "Deleted text" -c --cc A'

Thread Thread
 
parmcoder profile image
Possawat Sanorkam

Nice explanation. I will add your suggested solution to the article too.