How to stash my previous commit?

前端 未结 5 1716
感动是毒
感动是毒 2021-01-30 08:29

I\'ve got the following situation on my git log:

commit 111  <-- need to push it to the repository

commit 222  <-- need to stash this one

..         


        
5条回答
  •  [愿得一人]
    2021-01-30 08:45

    If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.

    Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:

    git rebase -i HEAD~2
    

    This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example

    pick 222 commit to be stashed
    pick 111 commit to be pushed to remote
    
    # Rebase 111..222 onto 333
    #
    # Commands:
    #  p, pick = use commit
    #  r, reword = use commit, but edit the commit message
    #  e, edit = use commit, but stop for amending
    #  s, squash = use commit, but meld into previous commit
    #  f, fixup = like "squash", but discard this commit's log message
    #  x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
    

    Reorder the two commits (they are listed oldest => newest) like this:

    pick 111 commit to be pushed to remote
    pick 222 commit to be stashed
    

    Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first.

    At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:

    git reset --soft HEAD~1
    git stash
    

    It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.

提交回复
热议问题