DEV Community

Cover image for Git Doesn't Forget! A Short Story
Lorenzo Zarantonello
Lorenzo Zarantonello

Posted on

Git Doesn't Forget! A Short Story

If you are a web developer, you should be familiar with Git.

Git is useful even if you are working on your own.
It allows you to track files and changes in your project.
You can see it as a diary of whatever happened to your project.

The Story

I started to work on a project created by other developers.

Just think of a React or Angular application.
However, for some reasons, package-lock.json was included in .gitignore.

As a consequence, Git would forget about package-lock.json whenever I would commit.
All in all, this is not a big deal, even though it is a good practice to let Git tracks changes to package-lock.json.

Changes in CI/CD

Someone decided that package-lock.json should be included and used for some CI/CD purpose. I won't dive on those reasons, but I had to add package-lock.json to the repo.

Not So Simple

The first thing I tried was to remove package-lock.json from .gitignore. Simple right? But it doesn't work.

My next commits would not include package-lock.json/

Solution

Thanks to this answer on SO, I understood that Git will continue to track any files that are already being tracked.

So, first of all, we need to remove all items from the Git index. This is not affecting files in your directory or repository. It just cleans the Git index.

git rm -r --cached .
Enter fullscreen mode Exit fullscreen mode

Second, we need to add them back. The following command update the Git index as we would expect.

git add .
Enter fullscreen mode Exit fullscreen mode

The two commands above remove and update the entire index.
A more elegant solution could just touch the file we are interested in.

git rm --cached <file>
// or
git rm -r --cached <folder>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)