Git Snippets

Undo

If you made a commit and did not push and want to change, use reset it will unstage the commit and your repo will be at the state prior to the commit. You can use reset with a hash or ~ back from head.

git reset HEAD~1

If you want to completely undo the previous commit, backing out the code, use --hard – this is a little more dangerous since you will lose any changes. I find using the soft reset and then checkout -- to revert any individual changes.

git reset --hard HEAD~1

If you made a set of changes, without commiting, that you want to get rid of you a shortcut is use . like so

git checkout -- .

Fix Merge Conflicts

A quick list on how to fix merge conflicts on your branch, more info on preserve-merges flag from here. The process is to update your local master with latest, merge that code onto your branch, update any conflicts and commit those back to your branch.

git checkout master
git pull
git checkout branch
git rebase master --preserve-merges

At this point you will see the conflict, git status will show the file(s) in conflict. Resolve the conflict by editing, adding, and then committing.

You can then continue down the line using git rebase --continue until all conflicts are resolved.

To commit your changes upstream, you will need to force push up: git push origin branch -f

Config Aliases

[alias]
pom = push origin master
fop = fetch origin --prune
pf = push --force-with-lease
purr = pull --rebase
unfuck = reset HEAD --hard

# use to add files that your forgot
ohyeah = git commit --amend -C HEAD

You can view my latest full .gitconfig in my dotfiles repo.

Squash Everything

If you want to rebase and collapse a repository down to a single commit, sometimes this is useful when converting a private repo to a public one and you don't want to leak any intermediary files.

git rebase -i --root master

Split a directory to own repository

You can create a new repository out of a sub-directory that already exists in a repository. First, clone the repository that holds the directory.

git clone git@github.com:username/fullrepo

Switch to the repository directory and filter on the directory you want to create the new repository from. The example uses subdir and master branch, you can specify your branch name.

git filter-branch --prune-empty --subdirectory-filter subdir master

Look at your repository, it should now simply consist of the contents of your directory. You can now switch your remote to be a new repository. So if you created a new repository on github called subdir.

git remote set-url origin git@github.com:username/subdir

Then simply push your changes to your new repository and you're all set.

git push -u origin master

Resources