Any way to avoid git checkout -f "warning directory is not empty"?

734 views Asked by At

I have a git repository that contains multiple branch that diverged a lot. When I say diverged it means that each branch can contain new folder or submodule and a lot of diffs between files.

When you checkout a branch that doesn't have the same submodule you initiated with git submodule update --init in your current branch you can fall into this kind of issue:

 error: The following untracked working tree files would be overwritten by checkout
     path_to_submodule/my_file.txt
     path_to_submodule/second_file.txt
     ...

To overcome this issue I'm using:

git checkout -f my_branch

This way "git proceed even if the index or the working tree differs from HEAD, and even if there are untracked files in the way" (from the doc)

But when I do this I have a lot of warning saying that git cannot remove not empty directory..

warning: cannot remove my_directory. Directory not empty

As it's a warning we can ignore it but then when you do a git status you have all those directories that are untracked. So to clean them I use:

git clean -xdff

My goal is to have a clean environment switching between two branches. That is why I'm using git clean. I know all the consequences using this command.

When you have a lot of submodules the logs can be quite messy with all those warnings when you force switch a branch. So I was wondering if there is a better way of doing that ? I have not seen any options in git checkout to automatically remove the untracked files/submodules when --force is used.

1

There are 1 answers

2
VonC On BEST ANSWER

So I was wondering if there is a better way of doing that ?

This is where I consider git worktree (that I present here)

Having two different folders, representing each two different checked out branches, avoids all this "overwritten/clean" messy business when trying to switch from one branch to another.

And you only clone the repository once.