Today’s lesson: pull before you make changes, and what do you when you forget that.
The task started off well enough — branched off of master, made my changes, committed them. Ready to send my content upstream as a new branch to share. But wait — my master branch wasn’t up to date when I branched. I can pull from origin now, after the fact — it’s no big deal in this case, no conflicts, very clean, but now the merge is the latest commit, which is not how I want to push. Much better for my committed changes to be the first in the log.
The first steps in turning that around were fairly normal:
git reset --hard <my original commit>
Ok, that’s just to make sure I’m back with my original changes as the most recent thing. But I still have to get the up-to-date content. Turns out there’s a simple way to undo a commit but keep the changes. So now I run this:
git reset HEAD^
Awesome. Back where I started, just as if I hadn’t made any commits in the first place.
Alright, now I can pull….
git pull origin master
Ahhhh. Much bet–wait, still not quite right. It’s much better to update master and then branch off of that. Ok, here we go.
git checkout master git pull origin master
Now we’re on track here; what’s next?
git branch -d <my new branch>
Ew. Maybe technically unnecessary, but so very clean.
git checkout -b <that same branch>
Hah, bring the branch back, but the right way this time. And my pending changes are still hovering around my branch as I switch around, waiting to be committed! So now I can do that very thing.
git commit -am "All better now, etc, etc."
And now I push.
git push origin <that branch again>
🙂
Note: As I’ve mentioned before, I am far from an expert on Git. I just use my experiences every day, and a healthy dollop of googling and reading, to learn about how things work and how to get stuff done. I share what I learn for fun and to make everyone’s day a bit easier, but I’m sure on this topic in particular there’s likely a better way to solve the same problem. So feel free to come up with a better solution! I’d love to hear about it if you do.