Venkat Venkat - 2 months ago 7
Git Question

change contents of a file in previous commits to current data

I have ~50 commits in my local Git repository. I have made some changes to a particular file in current HEAD, and i would like to update those file changes to all the previous commits. Is it possible achieve this in git??

Answer Source

It is possible, but there is a cost.

What you are describing is a "history rewrite", which will change the commit ID of every commit. If you alone use this repo, and you haven't been using the commit ID (SHA) values for anything (like documentation, or whatever), then that's probably fine.

If others also use the repo (or if you have multiple clones) you'll need to coordinate a cut-over. Basically my advice would be to arrange for a time when all updates have been pushed to a common repo (probably origin), then discard all the clones, then do the rewrite and replace the origin, then re-clone. Technically you don't have to do it that way, but see "recovering from upstream rebase" in the git rebase documentation (which actually applies to any history rewrite).

So if you decide to go ahead with the rewrite, the simplest way is probably to use git filter-branch. (If certain assumptions about your repo are true, then a rebase-based approach could work; but filter-branch is more generally applicable.)

git filter-branch --index-filter 'git checkout master -- file/to/be/rewritten' -- --all

This creates some "backup" refs which you'll want to remove once you've validated the result.