RBA RBA - 3 months ago 19
Git Question

Git - delete differences between branches locally

I have 2 branches in Git: master and release. They have pretty much the same files, except that release branch has some files which are not used in master. Each time I switch from release to master I need to delete by hand those files before making the checkout.

Is there a way that git can delete those files locally when doing the switch?

LE: print screen with git

enter image description here

Answer

Let's assume file is the file you want only in branch release, but not in master. You have to ensure that

  • file is checked into release and
  • file is not checked into master

MWE

For the reference, my approach works:

$ git init
Initialized empty Git repository in /tmp/testgit/.git/
$ touch a
$ git add a
$ git commit -m "master - a"
[master (root-commit) cf1ffcc] master - a
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a

# Only file a is present now
$ ls
a

# switch to release branch and create file

$ git checkout -b release
Switched to a new branch 'release'
$ touch file
$ git add file
$ git commit -m "release - add file"
[release 57da037] release - add file
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file

# both files are present:

$ ls
a  file

# checking out master again

$ git checkout master
Switched to branch 'master'

# "file" is not present

$ ls
a

Your issue

I suppose your issue is that file actually is in master instead of release (but it should be vice-versa). Confirm this by running git ls-files, it shows you what files git takes care of.

In this case, probably

  • you are in branch release with file being untracked,
  • you want to switch to branch master and
  • in master, file is tracked by git, and thus your currently untracked file would be lost by checkout.

In this case, you can solve your issue by deleting the file from master, and instead add it to release:

git checkout release
git add file && git commit
git checkout master
git rm file # also remove from branch master, not only file system
git commit

The most important thing here is not only to delete the file from the file system, but also delete that file in git from the master branch.