The scenario below details where there was a deleted file on a remote git repo mistakenly. If you scroll through the commits below, the problem really came up in COMMIT 4
and actually in terms of whether it was unexpected/expected, I wonder if there is a common way to remedy this. It's best to avoid having unwanted files in a branch altogether obviously, but when run into a situation like in COMMIT 4
, but my question is what should be done?
COMMIT 1 (18 days ago): created on local repo file <code1.java> on branch [code1]
and pushed to remote branch [code1] for initial commit
of the file
COMMIT 2 (14 days ago): changed a variable in the file <code1.java> on branch [code1]
and pushed to remote branch and created PR
COMMIT 3: (7 days ago): created on local repo the file <code2.java> on branch [code2]
and pushed to remote branch [code2] for initial commit
COMMIT 4: (6 days ago): **noticed that on [code2] branch I somehow had checked in
<code1.java> with commit 3** so I deleted the file <code1.java>
from branch [code2] and pushed to remote branch [code2]
and did a PR for [code2]
COMMIT 5: (5 days ago): changed formatting on file <code2.java> on branch [code2]
COMMIT 6: (4 days ago): PR reviewer accepted changes to <code1.java>
and merged branch [code1] to master
COMMIT 7: (3 days ago): PR reviewer accepted changes to <code2.java>
and merged branch [code2] to master
code1.java is gone now :( :( :(
It sounds like you based your code2
branch off of code1
instead of master
. When you did that, you included all the code that was in that branch at that point, including code1.java
.
When you merged code2
, Git considered only three points for the merge: the merge base (commit 2) and the two heads. Since the file was unchanged on one side (commit 6) and there was a modification (the deletion) on the other side, Git applied the modification and deleted the file.
In this case, it was okay that code2
contained code1.java
, because it was based on a branch that contained it: it wasn't an extraneous change that you'd included. By deleting it, you did in fact introduce an extraneous change—the deletion—which was the opposite of what you intended.
The easiest way to avoid this is always to branch off master
when working on a project, which means you won't have extraneous things to remove. If you accidentally based off another branch, you can do git rebase --onto master code1
which will take your branch based off code1
and put it onto master
instead. You can then inspect it to see if you need to add or remove things in the future.