Git HowTo

A bunch of useful commands and tips for using git.

It is recommended to use git via ssh instead of https. To save yourself the trouble of entering your password everytime, copy your ssh public key into your git account. This must be done by logging into your git account in your browser and going to the settings page.

Some rules to follow

  1. Do not commit trivial changes like adding extra blank line or blank space.
  2. Before a commit or when creating a pull request, check every changed line and ensure that you made the change and that you would like to check it in.
  3. Make sure that files you add don't have execute permission.

Adding files

To add all modified files which are already tracked

git add -u

Cleaning up

To remove all untracked files in the current directory

git clean . -f -x

To remove all untracked files and directories in the current directory

git clean . -f -x -d

Checkout old version

If you want to use an old version of the code, then find the SHA checksum of the commit using git log and then do

git checkout <checksum>

The HEAD is now set to the selected commit and you can see this by doing git branch. If you now want to go back to master, do

git checkout master

Making a branch

Create a new branch

git branch my_branch

Make your changes, add files and commit them to your branch. Then push them to remote

git push origin my_branch

To merge your branch into master

git checkout master
git merge my_branch

You can now push master to your origin and then create a pull request.

Make your fork track original upstream repo

git checkout master
git remote add upstream git@github.com:upstreamname/projectname.git

Now you can get updates from upstream

git fetch upstream
git merge upstream/master

To send these changes to your own remote

git push origin master

Rebase branch to master

git checkout master 
git pull origin master
git pull upstream master
git checkout my_branch
git rebase master

The last step might indicate some conflicts which have to be resolved.

Squash commits

You may want to squash several commits into one before creating a pull request.

  1. git rebase -i yourbranchname
  2. A file in an editor program will be automatically open.
  3. Change all commits from "pick" to "fixup" but one commit must have "pick"!
  4. Save the file and close the editor.
  5. git push -f origin yourbranchname

Delete branch which is not merged

git branch -D my_branch
git push origin :my_branch

Accepting and merging a pull request

git checkout master
git remote add contributor git://github.com/contributor/projectname
git fetch contributor
git merge contributor/newfeature
git push origin master