2 min read

git: revert an updated file

Syed Aslam

This is one hard to find out there so here it is. How to remove an updated file from a pull request whose content is changed but was out of the scope for the work that is currently being done. Here you want to remove the file from the pull request without deleting the file itself, but just revert the inclusion of this file in the pull request. Because, if you delete the file, then that deletion becomes part of your changeset, which is not what you wanted at all.

Let's face it. Some file gets updated unintentionally which is not part of the work that you are doing. One does bundle install or run yarn all the time in the local branch that we're working on that is part of this awesome pull request. Now, some package gets an update and your lock file is changed. Keeping the packages that your code depends on updated is a good thing. But the changes that are not directly related to the focus of the branch you're working on should come from upstream to make sure all contributors are drawing from the same place. That is a general good practice.

Now, how do you remove this file from the pull request? The basic idea is to undo the changes that were made to the file to make the file disappear from the changeset.

There are a couple of ways we can get around this problem, first, by reverting the updates manually.

If you had not yet committed your unwanted changes, then you can simply check out the original file

  $ git checkout filename

This will checkout the file from HEAD, overwriting your change. One thing to note here is that this command is also used to checkout branches, and you could happen to have a file with the same name as a branch. In that case, you could say:

  $ git checkout -- filename

One has to be careful with git reset --hard since this resets all uncommitted changes you've made in your working copy.

Second, if you've committed the unwanted changes to your local repository and you have pushed the updates upstream, then, to retrieve the file's content from the origin repository:

  $ git checkout origin/<branch> -- <filename>
  $ git commit -m "Reverted changes made to the file"

That's all, folks

Atlassian has some nice and comprehensive material learn Git with beginner to advanced Git tutorials on workflows, git commands, git migration and code review. Check them out.