Cheatsheet and best practices for Git

Git-Logo-2Color

Git is distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

Git is a primary tool for both developers and cloud engineers who are moving to infrastructure as code. Git is the core of a modern version control software, which keeps track of every modification to the code in a special kind of database. If (dare I say “when”) a mistake is made, you can turn back the clock and compare earlier versions of the code to help fix the mistake while minimizing disruption to all team members.

You do not need to have your repository set up to get started with Git. Although you will want to set one up to save your changes and to manage your deployments. Learn more about how to set up your repositories in the previous post.

In this article, you will find a list of resources to use to learn how to get started with Git.  The article provides some sample command in a pattern you will use for your code or your infrastructure as a code. There are also references on how to get started learning Git.

Or .. if you prefer you can use the Git Cheatsheet from GitHub. The contribution made in this blog post is to show you common patterns you will use daily.


Let’s start with the workflow, and then review some terms, then walkthrough how to use branches to check your code in and out of the repo.

Prerequisites

  • Git installed on your local development/engineering machine.
  • The URL of the respository set into an environment variable, such as the following:

Git Workflow

Once you have created your repository, you can make changes to the code and send those changes to the repository. Once you have completed your changes, you can do a pull request. The pull request is the collaborative process that lets the rest of the team discuss changes in a branch that is the subject for a later post.

The following summarizes the workflow in Git.

  1. Create a branch for the changes you plan to make and give it a name, such as users/bruce/feature27 or feature27. For more branching guidance, see Adopt a Git branching strategy
  2. Commit changes to your branch. Your team will often have multiple commits for a bug fix or feature.
  3. Push your branch to the remote repository.
  4. Create a pull request so other people can review your changes. To incorporate feedback, you might need to make more commits and push more changes.
  5. Complete your pull request and resolve any merge conflicts from changes other people made after you created your branch.

The following illustration shows which commands interact using Git.
gitworkflow

Git Basics

Once you install Git, here’s are the five main commands you can start with:

  1. git clone
  2. git status
  3. git add
  4. git commit -m ” “
  5. git pull # does a fetch and a merge
  6. git merge
  7. git push

Here’s what it looks like to get an existing repo, add a new file, and push back to the master branch.

mkdir myclonedrepo && cd myclonedrepo
git clone $REPOSITORY_URL
cd $PROJECT_NAME
git status
# create a new file and add
echo "print('new')" > newpythonfile.py
cat newpythonfile.py # displays the new python file
#add the file and commit the change into the feature27 branch
git add newpythonfile.py
# see what has changed
git status
# commit
git commit -m 'added newpythonfile.py'
git push

view raw
basics-with-git.bash
hosted with ❤ by GitHub

But it is a best practice to use branches.

About Git Branching

Git development branches is a great way to work with our development code and infrastructure as a code, while tracking its versions. And it supports members of your team working on the same code for different aspects of your project, such as features and bug fixes.

Underneath the covers, branches in Git are pointers to a specific commit. A commit is a snapshot of your Git repository at one point in time.

The one mantra that you should always be chanting while branching is “branch early, and branch often”.

There are basically two types of branches local branches and remote tracking branches. Local branches work on your local developer computer. Remote tracking branches:

  • Link your work from the local repository to the work on central repository.
  • Automatically detect which remote branches to get changes from, when you use git pull.

Let’s try out branching.

Git Branching Cheatsheet

The following code is a sample branching workflow (adapted from A typical workflow with Git branching). Use git branch without parameters to see the branches that you have and which branch you are in.

There steps to branching are:

  1. git branch newbranchname
  2. git checkout newbranchname
  3. git add #or make changes to existing files
  4. git commit -m “”
  5. git pull # without any options does a fetch of the changes from origin that you might not have in your current branch. Also will merge the changes for your current branch.
  6. git push  # push your local commits, including your new merge commit, to the remote server
  7. git checkout master
  8. git branch # shows you are on master
  9. git merge newbranchname # into master
  10. git push # push to master

Once you are satisified with the merge, you can use git push to the repo.

The following code shows a walkthough.

mkdir myclonedrepo && cd myclonedrepo
git clone $REPOSITORY_URL
# create a branch named 'feature27'
git branch feature27
git branch
#displays the current branches that you have locally, * shows current branch
# switch to the 'feature27' branch
git checkout feature27
git branch
#displays the current branches that you have locally, * shows current branch
# create a file. used your edtior. but for the demo do something simple
echo "print('new')" > newpythonfile.py
cat newpythonfile.py # displays the new python file
#add the file and commit the change into the feature27 branch
git add newpythonfile.py
git status
git commit -m 'added newpythonfile.py'
# make additional changes
echo "print('new with changes')" > newpythonfile.py
git commit -m 'updated newpythonfile.py'
# Then when you are happy, merge with the master branch
#pull any updates that have been made from the master
git pull origin master
git commit -m 'merged newpythonfile.py'
# resolve merge commits and push your feature branch to the respository
git push
# should do a pull request here
# ready to update master banch
git checkout master
ls
#the new file is not there, so let's merge feature27 branch with the master branch
git merge feature27
# check to see if the file is there
ls
#the newpythonfile.py file is in the master branch
# push to the master branch
git push

Git Undo

One of the most important points of branching and commits is to undo a mistake.

If you have not yet committed the changes, the best practice is for you to stash the changes in case you were mistaken and later decide that you really wanted them after all. git stash save "description of changes".

IF you want to undo the last commit, you can simply run git reset --hard HEAD^. If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.

For more complex scenarios, see On undoing, fixing, or removing commits in git.

Git Push

A special note about git push. There are many options on git push. But the most important ones are:

  • repository. The “remote” repository that is destination of a push operation. This parameter can be either a URL or the name of a remote, such as origin.
  • refspec tells git how to map references from a remote to the local repo. The refspec refers in this case as master.
git push origin master

view raw
git-push-sample.bash
hosted with ❤ by GitHub

The previous command finds a ref (which we initially think of as a branch) that matches master in the source repository (most likely, it would find refs/heads/master), and update the same ref (e.g. refs/heads/master) in origin repository with it. If master did not exist remotely, it would be created.

Best practices

Seth Robertson has provided a post Commit Often, Perfect Later, Publish Once: Git Best Practices.

Here’s a quick summary of the headlines:

  • Do commit early and often. Having periodic checkpoints means that you can understand how you broke something.
  • Don’t panic. You can undo it.
  • Do backups. Traditional backups are still appropriate, and clones do not save git configurations, the working directory and index, non-standard refs, or dangling objects anyway.
  • Don’t change published history. Once you git push your changes to the authoritative upstream repository or otherwise make the commits or tags publicly visible, you should ideally consider those commits etched in diamond for all eternity.
  • Do choose a workflow. It can also lead to a market advantage since you can deploy a differentiating feature which your competitors cannot in a short timeframe. Seth offers several approaches to workflow for your team. See Pro Git branching models.
  • Do divide work into repositories. One conceptual group per repository. Read access control is at the repo level. Separate repositories for files that might be needed by multiple projects. Separate repositories for large binary files. And more.
  • Do keep up to date. Recommdends git pull --rebase
  • Do periodic maintenance. Validate your repo is sane, compact your repo, prune your remote tracking branches, check your stash for forgotten work.
  • Do enforce standards. Checks could involve regression tests, compilation tests, syntax/lint checkers, commit message analysis, etc.
  • Do use useful tools; integrate with external tools.

The article is worth the read. Shared under Creative Commons Attribution-ShareAlike 3.0 Generic (CC BY-SA 3.0) http://creativecommons.org/licenses/by-sa/3.0/

Resources to get started in Git


One thought on “Cheatsheet and best practices for Git

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s