You have a situation where you have incorrect files that conflict with tracked files in another branch. You want to switch to this branch, but checkout
will not allow you.
The "first level" solution in git is to push these raw files to the index:
git add folder
Now you still cannot check the branch. However, you are given a new opportunity: you can git stash save
make changes:
git stash save
Now you can switch to the branch and make git stash pop
. At this point, you can deal with merge conflicts, if any, and then git reset
, and you're done.
[Update: git add
not required because git stash
has the ability to include files without a trace!]
Let's look at a complete example, including one file called topicfile
, which exists only in a branch, and is created as a working file in master
, but with different contents:
~$ mkdir gittest ~$ cd gittest/ ~/gittest$ git init Initialized empty Git repository in /home/kaz/gittest/.git/ ~/gittest$ touch emptyfile ~/gittest$ git add emptyfile ~/gittest$ git commit -m "starting repo" [master (root-commit) 75ea7cd] starting repo 0 files changed create mode 100644 emptyfile ~/gittest$ git branch * master ~/gittest$ git checkout -b topic Switched to a new branch 'topic' ~/gittest$ cat > topicfile a b c d e ~/gittest$ git add topicfile ~/gittest$ git commit -m "topicfile" [topic 875efc5] topicfile 1 file changed, 5 insertions(+) create mode 100644 topicfile ~/gittest$ git checkout master Switched to branch 'master' ~/gittest$ ls emptyfile ~/gittest$ cat > topicfile @ a b c d e f g h ~/gittest$ git add topicfile ~/gittest$ git stash save topicfile Saved working directory and index state On master: topicfile HEAD is now at 75ea7cd starting repo ~/gittest$ git checkout topic Switched to branch 'topic' ~/gittest$ git stash pop Auto-merging topicfile CONFLICT (add/add): Merge conflict in topicfile ~/gittest$ cat topicfile <<<<<<< Updated upstream ======= @ >>>>>>> Stashed changes a b c d e <<<<<<< Updated upstream ======= f g h >>>>>>> Stashed changes ~/gittest$ cat > topicfile
At this point, we can commit our topicfile
changes to topic
branches, and the file is still not tracked by master
.
Since conflicts arose in git stash pop
, a cover still exists. We can clear this with git stash drop
.
An alternative to all of this is not only git add
unused files for the index, but also git commit
to make the correct commit. Then we can cherry pick the fixation in the branch. If we do not want these files to be tracked on master
, this is normal: we can later git reset --hard HEAD^
on the main one to fix this commit.