Changing branches in Git sometimes leaves a mess if the branches have different directory structures. This can be a quite common predicament when switching between–for instance–a v1.0 release branch and your new v2.0 beta branch. How do we go about cleaning that up?
The proper way to clean up the old directories and files is to use git clean. Here are some common flags you’ll probably need to pass to git:
-d : Remove untracked directories in addition to untracked files
-f : Force git to clean the branch. If the git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given -f or -n.
-n : Dry run. Don’t actually remove anything, just show what would be done.
-x : Don’t use the ignore rules. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with git reset) to create a pristine working directory to test a clean build.
Example: dry run and then removal
# git clean -nxd
Would remove unnecessary_file_from_other_branch.txt
Would remove old_directory_from_other_branch/
# git clean -fxd
So, as you can see, using the -n flag shows you what git “would remove”. If you’re happy with what you see, you can go ahead and pass the -f flag to ensure those files are removed for good.