Thursday, April 09, 2015

Push specific local commit to remote

Like what's asked in this Stack Overflow question, sometimes we keep local commits for a while, amending commit message, merging multiple commits into a more meaningful one, trying something in a branch from unpublished commits and so on. And finally, we decide to push some oldest commits to remote. Here are the steps.
  1. Check in all changes locally

  2. Branch it (not only for backup, but also to keep commit history when resetting)
  3. git branch backup

  4. Reset to the oldest unpublished commit
  5. git reset --hard {sha of commit to push}

  6. Push it to remote
  7. git push origin {branch}

  8. Go to step 2 if you have more commit to push

  9. Reset to latest local commit
  10. git reset --hard {sha of latest commit}

  11. Delete backup branch
  12. git branch -d backup

Happy coding!