3

I accidentally saved a file on the wrong branch. Then I did git reset --soft HEAD^ and now git status says I'm behind by 14 commits and lists a bunch of modified files in red. Including some untracked files.

I have no idea what to do. I tried to go to the latest commit from the remote repo but it says my local changes would be overwritten after I do git pull.

Help. I don't wanna mess up my local repo even more. I just want to get back to the state I was in, save the edited file in the correct branch, and commit.

fent
  • 17,861
  • 15
  • 87
  • 91

2 Answers2

3

If you have changed your local branch, and do not want to lose any change, you can use git-stash. Before any attempt, I recommend you to backup your local repository. Try the following steps:

  1. git stash save 'local changes'. This will save your local changes in a temporary place, and let you work on the current branch without any of these previous changes.

  2. git pull <remote-name> <branch-name>. As you already know, it will retrieve newer commits from the remote branch, and apply to your local branch.

  3. git stash pop. This will revert what you did in step 1. It will apply your previous changes (those you saved) against the local branch. You are responsible for resolving any conflicts, if any occur. Once done, you may want to commit, and push - it's up to you.

jweyrich
  • 31,198
  • 5
  • 66
  • 97
1

Don't panic

  1. Backup your repository.

  2. Stash your changes with git stash save. This will put your changes in the stash.

  3. Then, pull from the remote branch: git pull <remote> <wrong-branch>. This will return your working copy to the pristine branch HEAD. This is what your branch looked like before you started working on the changeset.

  4. Now, apply the stashed changes to your working copy: git stash apply. Git will be smart enough to ignore stashed changes that match existing commits, so you will be left with your working copy in the same state as before you made the commit to the wrong branch.

  5. Now checkout the right branch, and commit as usual:

    git checkout <right-branch>
    git add [...]
    git commit -m "blah blah blah"
    

    You may have to wrangle your changes when checking out the correct branch if your change set is incompatible with the correct branch, but once done, Your changes will now be committed on the right branch.

brice
  • 24,329
  • 7
  • 79
  • 95