Home > Mobile >  Git: How to circumvent deletion of file in one branch when tracking it in another?
Git: How to circumvent deletion of file in one branch when tracking it in another?

Time:05-03

I just encountered the following situation: I have two python files, let's call them A.py and B.py.

I initialize git and create two branches branch-x and branch-y. They don't track any files yet.

I do(branch-x) git add B.py and (branch-x) git commit B.py , but at first I do not track A.py because it's identical in both branches. Later on, I do (branch-y) git add A.py and (branch-y) git commit A.py, because it turns out I also have to do changes in A.py after all. But when I now do git checkout branch-x A.py is gone in that branch!

What I'd actually like is for that file to be tracked in all branches in the state at the time I do git add A.py. How can I circumvent the above behavior? Am I violating some best practices?

CodePudding user response:

You don't need multiple branches to obtain that situation: add and commit a new file, then checkout the previous commit and Git will remove that file from your worktree, even if it existed before as an untracked file.

That is because, well, it was untracked. A git commit represents the whole repository at that specific version: if you choose not to track a file, then it is not considered part of that version.

You cannot easily opt-in to retroactively track a file either, because that would imply rewriting the whole history and that's generally not a good idea. Still, this can be accomplished manually by committing the file addition on its own, then using git rebase -i --rebase-merges to move that commit to a point in the past and rewriting the rest of history on top of it.

The actual solution is simply to track all of your repository's required files from the beginning as Git is designed to do.

CodePudding user response:

This is long, but it's probably a good idea for at least the OP to read it carefully.

Let me repeat TTT's comment, which is itself important so I'll highlight it again here (and add a bit of emphasis):

The misunderstanding comes from this statement, "but at first I do not track A.py because it's identical in both branches". Actually, at that point it's not "in" any branches yet and it's just following you around until you commit it.

Besides this, though, you have another misunderstanding about Git that shows here:

I initialize git and create two branches branch-x and branch-y. They don't track any files yet.

This is literally impossible (but also nonsense, and I'm not sure which of these to give priority

  •  Tags:  
  • git
  • Related