Find deleted line in deleted file Git

372 views Asked by At

How can you search for a certain line of code, in a file that was also (maybe) deleted without knowing the name of the file?

To be more specific, a month ago I was working on a script and got it working to our needs, however a rather special case occured. We are certain that in the past there existed a file that contained the the line/word x-shared-component. This line doesn't seem to exist anymore in the current repository. We're not sure wether that line was removed in the past or if the file (name also not known) was just deleted.

I've tried:

  • To look in the current HEAD if any file contains that line with git grep -i "x-shared-components"
  • git log -p --all | grep -i "x-shared-components"
  • git grep -i "x-shared-components" $(git rev-list --all)

Is there something missing that I'm not taking into consideration? I tried to delete a file and search for its content with git log -p --all | grep -i <regex> and i was able to find lines. If I can't seem to find any results, does that mean such a line actually never existed in the current git repository?

3

There are 3 answers

2
LeGEC On

You are looking for git log -G or git log -S :

git log --name-status -G x-shared-component
git log --name-status -S x-shared-component
0
William Pursell On

It will probably be very slow, but you should be able to find all the blobs in the repo with someting like:

git rev-list HEAD | xargs -n 1 git ls-tree -r | 
    while read a b h path; do 
        git show "$h" | grep -q x-shared-component && echo $h; 
    done

Once you have the blobs, you can view the content with git show.

You can almost certainly reduce the amount of work by 95% with a little bit of thought. Certainly don't run grep over the same blob more than once with something like:

git rev-list HEAD | xargs -n 1 git ls-tree -r | awk '{print $3}' | sort -u | 
    while read  h ; do git show "$h" | grep -q x-shared-component && echo $h; done
0
torek On

It's likely that the line (and possibly entire file) in question was dropped during a merge.

Unfortunately, git log -p, including the variants with automated diff-searching (-S and -G), normally does not look at merge diffs at all.

Fortunately, it's easy to make git log -p look at merge diffs, by adding -m. You may even be able to use -m --first-parent (which will go faster by skipping the remaining parents). I recommend:

git log -m -S x-shared-component

here, since you don't need a regular expression and the number of occurrences will change in the merge in question.

Note that there has been some recent work on Git to improve the diff-ing of merge commits; this -m method works in all versions of Git, not just recent ones.