How do I push amended commit to the remote Git repository?

后端 未结 16 1387
深忆病人
深忆病人 2020-11-22 04:42

When I\'ve worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the

16条回答
  •  渐次进展
    2020-11-22 04:50

    I had the same problem.

    • Accidentally amended the last commit that was already pushed
    • Done a lot of changes locally, committed some five times
    • Tried to push, got an error, panicked, merged remote, got a lot of not-my-files, pushed, failed, etc.

    As a Git-newbie, I thought it was complete FUBAR.

    Solution: Somewhat like @bara suggested + created a local backup branch

    # Rewind to commit just before the pushed-and-amended one.
    # Replace  with the needed hash.
    # --soft means: leave all the changes there, so nothing is lost.
    git reset --soft 
    
    # Create new branch, just for a backup, still having all changes in it.
    # The branch was feature/1234, new one - feature/1234-gone-bad
    git checkout -b feature/1234-gone-bad
    
    # Commit all the changes (all the mess) not to lose it & not to carry around
    git commit -a -m "feature/1234 backup"
    
    # Switch back to the original branch
    git checkout feature/1234
    
    # Pull the from remote (named 'origin'), thus 'repairing' our main problem
    git pull origin/feature/1234
    
    # Now you have a clean-and-non-diverged branch and a backup of the local changes.
    # Check the needed files from the backup branch
    git checkout feature/1234-gone-bad -- the/path/to/file.php
    

    Maybe it's not a fast and clean solution, and I lost my history (1 commit instead of 5), but it saved a day's work.

提交回复
热议问题