Oh my Git

Git, a newly developer's worst enemy, an experienced developer's best friend. I remember when I first started writing code and my cousin dropped the Git-bomb. After a few agonising weeks trying to understand and use it correctly I started smelling the power has.

What is Git?

Git is a free and open source distributed version-control system for tracking changes in source code during software development. It is designed to keep track of projects and files as they change over time and coordinating work among developers. It stores project deltas called commits that together build a snapshot of the latest source code. Its goals include speed, data integrity and support for distributed, non-linear workflows.

In other words it keeps a history of the steps written to end up with the latest solution.

This was a little introduction about Git. This post is not meant to teach you the ways of Git, - for that I would refer you to the git documentation- but more to show some important commands to ensure a clean git history.

Gitting into business

Basic Commands

  • Check the state of the working directory since previous commit
% git status
  • Add changes in working directory to the staging area
% git add
  • Save your staged changes into your local repository
% git commit
  • Push your saved changes to your remote repository on GitHub, GitLab, ...
% git push
  • Pull changes from your remote repository to your local repo
% git pull
  • List local branches and see highlighted acitve branch
% git branch
  • Switch to a different branch
% git checkout <BRANCH_NAME>
  • Merge multiple branches into the active branch
% git merge
  • Change the base of your branch from one commit to another making it appear as if you'd created your branch from a different commit
% git rebase

Clean workflow

Scenario 1: Let's say you're on branch feat-button which is branched of the master branch. You have commited a new commit, pushed it to the remote repository and you want to create a pull request to merge your lasted changes to the remote master branch. You notice your branch is a few commits behind, because another developer has already merged his changes to master.

From your local branch:

% git checkout master
% git pull
% git checkout -        # will checkout to previous acitve branch
% git rebase -          # will rebase previous active branch
% git push -f           # will force push to remote

Scenario 2: You're on branch feat-button which is branched of the master branch. You have commited a new commit, pushed it to the remote repository and you notice you created a little typo. You want to fix this without adding more commits to the history.

You fix the type and then from your local branch:

% git add ./path-to-file.js
% git commit --amend --no-edit --no-verify
% git push -f