Git is an amazing tool that does a lot of incredible things. It's also a tool that is easy to screw up. Here is a list of tips I've found useful for when working with git.
Git Up
So when you run git pull
chances are what you actually want to do is rebase over them. You also are probably working in a "dirty workspace" which means you want to pull the stuff ahead of you and rebase over it but until you are ready to commit, you don't want your work to be reflected. (I'm saying all this like its a certainty, I'm sure for a lot of people it's not. However I work in an extremely busy repo all day).
We're gonna set a new git alias for us that will do what we actually want to do with git.git config --global alias.up 'pull --rebase --autostash'
Autostash basically makes a temporary stash before you run the rest of the rebase and then applies it back after the operation ends. This lets you work out of a dirty directory. Make sure you sanity check your changes though since the final stash application has the potential to do some weird things.
Approving Stuff As You Git Add
Been working for awhile and ready to add stuff to a commit but maybe don't remember all the changes you've made? Not a problem.
git add -p
lets you step through your changes one by one and only add the ones to this commit you need. I use this as a final sanity check to ensure some fix I didn't mean to go out with this deploy doesn't sneak out.
Go Back In Commit History
git reflog
will show you a list of everything done across all branches along with the index HEAD@{index}
git reset HEAD@{index}
will let you fix it
Commited to the wrong branch
Go to the branch you want: git checkout right-branch
Grab your commit: git cherry-pick
SHA of commit (get this from git log
) or if its the last commit on a branch just the name of the branch
If needed, delete the commit from the wrong branch: git checkout wrong-branch
then git reset HEAD~ --hard
to knock out the last commit
You can pass an argument to HEAD to undo multiple commits if needed, knucklehead: git reset HEAD~3
to undo three
Squash Commits Down
First just do a soft reset passing HEAD the argument for how many commits you want to go back: git reset --soft HEAD~3
Then take your previous commit messages and make them your new unified commit: git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"
Fix Messed Up Commit Message
git commit --amend
and then just follow the prompts