0

I accidentally committed files that should be in gitignore, and when I pulled the commit my files were overwritten by the ones from the commit.

I reverted the commit to the previous one and replaced the content of the files, but now when I will pull new changes, the content of those files will be overwritten again by the reverted earlier commit.

How can I handle this?

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
user99999
  • 1,994
  • 5
  • 24
  • 45

2 Answers2

2

I accidentally committed files that should be in gitignore

You first have to remove them from the history.
You have few ways for doing it (revert, reset, checkout <commit> etc)


Revert

You can simply revert the code in your commit. This will undo your changes

revert <commit id>

reset

reset HEAD <commit id>

This will "move" your branch to any given desired commit and then checkout branch and you are back with your old codeڄ


Updating remote

Once you have the desired code you want push it to the remote with the -f/--force flag.


How to ignore the desired file(s)

Add the file to the .gitignore so it will be undetectable by git.

If you still want the file in the repository (with default values for example) you should use the assume-unchanged flag on the tracked file.

https://git-scm.com/docs/git-update-index

--[no-]assume-unchanged

When this flag is specified, the object names recorded for the paths are not updated.
Instead, this option sets/unsets the "assume unchanged" bit for the paths.

When the "assume unchanged" bit is on, the user promises not to change the file and allows Git to assume that the working tree file matches what is recorded in the index. If you want to change the working tree file, you need to unset the bit to tell Git. This is sometimes helpful when working with a big project on a filesystem that has very slow lstat(2) system call (e.g. cifs).

Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

enter image description here

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
0

Force push your new changes like this:

git push -f origin <your-branch>
TheGeorgeous
  • 3,927
  • 2
  • 20
  • 33