You are on page 1of 30

https://learngitbranching.js.

org/

1 DevOps and Git in a Nutshell


1.1 Is Git Efficient
 Each commit is a snapshot of the entire projects at a given point in time.
 Behind the scenes, Git is very efficient at storing commits
o Each unique file is stored only once

1.2 Project History


The collection of commits contain the history of the project

 You can review the history


 You can “undo” a change

1.3 Branches
 All commits belong to a branch
o An independent line of development of the project
 By default, there is a single branch and it is called master
1.4 Creating Branches
 How do you maintain a stable project at the same time that you are working on it
o Create a separate branch
 The master branch does not now about feature branch

1.5 Branch Independence

Branches enable independent development of the project.

1.6 Merging
When a branch is ready to become part of the master branch, it can be merged into the master branch.
A merge combines the work of separate branches.
Before the merge, the master branch has no knowledge of the featureX branch. After the merge, there's
a single master branch with the latest commit, including the code that implements featureX.

1.7 Pull Requests


Request to merge your branch into another branch

Before you merge content into the master branch, how do you know that your changes are good? A pull
request is a request to merge your branch into another branch. This request is usually made by
developer of the branch when the feature, bug fix or other change is complete.

During a pull request team members can discuss, review, and approve your changes. You can also
require that automated test pass before the merge is allowed to happen. This helps ensure that the
changes introduced by the merge don't cause problems for the customer. If the pull request is accepted,
your version of the project is merged and becomes the latest commit on the master branch. You can feel
good about the quality because the changes were reviewed and automated tests have passed.
2 Git Overview
2.1 What is Version Control

We can think of version control from the perspectives of content, teams, and agility.

Version control manages a collection of changing and improving files which we can call a project. The
complete history of the project is tracked and available at any time.

Version control also supports teams working on that collection of files. Teams work in many different
ways, and a good version control system will support many of their workflows or ways of getting work
done. Version control helps support collaboration on the project and improves quality through
facilitating team communication and reviews.

Finally, version control enables agility, the ability to adapt quickly and constructively to a changing
environment. It does this by managing small changes to a project and by allowing

2.2 Distributed Version Control System (DVCS)


A DVCS usually have three characteristics:

 . Each user has a local copy of the complete history of the project, which is known as a
repository.
Even though repositories are distributed among team members there's also a single remote
repository that is designated as the source of truth or official state of the project. This repository
is usually hosted in a data center or in the cloud.
 Because each user has a local copy of the complete history of the project, they can continue to
work while offline.
 Content is synchronized between repositories by pulling content from or pushing content to a
remote repository.

2.3 What is Git?


 Git is a distributed version control system.
This means each user has a local copy of the repository and that repositories can easily be
synchronized.
 Open source software
 Adapts to many types of projects and workflows
o Works well for large or small projects

2.4 What is a Git Repository ?

A series of snapshots or commits

A Git repository contains a series of snapshots of the project over time which are known as commits.
Each commit contains all of the directories and files of the project at the time the snapshot was taken.
You can go back and view the project at earlier points by viewing the older commits.

2.5 Review
 Version control enables teams to manage a collection of files in an agile qay
 Git is a distributed version control system
o Each user has a local copy of a Git repository
 A repository contains the project history as commits
o A commit is a snapshot of the entire project
 You have the choice of working with Git using a command line and/or a graphical interface
3 Git Locations

3.1 Working Tree

We know that a commit is a single snapshot of the project. The working tree is the location on your
computer that contains the directories and files of a single commit. This is where you can view and edit
the files of the project, preparing them for the next commit. We will learn later that you check out a
commit to place its directories and files into the working tree.

3.2 Staging Area / Index


The staging area contains a list of files that are planned to be included in the next commit that you
make. You prepare the staging area just the way that you want it, so that the next commit is a
meaningful snapshot of the project. You will learn later that you use the add command to add new or
modified files to the staging area.

The staging area contains a list of files that will be in the next commit.

3.3 Local Repository


The local repository contains all of the commits that have been made for the project. These commits
represent the version history of the project.

3.4 Project Directory

The first three locations that we discussed, the working tree, staging area, and local repository are
commonly all contained in a single directory on your local computer. This is called the project directory.
The project directory contains the working tree. The working tree contains the directories and files of a
single commit or snapshot of your project. You can view and edit these files to prepare them for the
next commit.

The project directory also contains a hidden directory named.git. This is where the staging area and local
repository are located. Notice that if you delete your project directory, you are also deleting your local
repository and staging area, because they are in the.git directory.
3.5 Remote Repository

We have seen that the working tree, staging area, and local repository are all located in the project
directory on your local machine. The remote repository is usually located in a data center or in the
cloud. The remote repository contains the commits of the project, and is often considered the source of
truth or official state of the project. When the local and remote repositories are synchronized, they
contain exactly the same commits.

4 Create a Local Repository


git init - create (initialize) local repository.

5 Commit to a Local Repository


git status – view status of files in the working tree and staging area

git add <file-or-directory> - add content to the staging area

git add . – add all untracked or modified files

git commit – adds staged content to the local repository as a commit.

 Previously committed files are also included


 Creates a snapshot of the entire project
 -m for add commit message
o git commit -m “initial commit”

git log – view the commit history


git log --oneline - a consice version of the history is displayed

6 Create a Remote Repository


7 Push to a Remote Repository

7.1 Cloning a remote Bitbucket repository


Clone is a local copy of a remote repository
Git remote --verbose - can be used to obtain remote information using a command line

Clone in SourceTree from URL

You can clone any repository into Sourcetree if you have the URL

Copy the URL from Bitbucket or from any other source


Open Sourcetree and click “New”

7.2 Add a remote repository to a local repository

git remote add can be used to add a remote repository using a command line
7.3 Push commits to remote repository
All commits belong to a branch

By default, there is a single branch and it is called master

A push add commits for a branch to a remote repository

git push can be used to push commits to a remote repository using a command line

git clone <url/to/projectname.git> [localprojectname] is used to create a local copy of a remote


repository.

git remote –verbose Displays information about remote repositories associated with the local repository

git remote add <name> <url> Adds a remote repository

git push [-u] [<repository>] [<branch>]

 <repository> can be a name(shortcut> or URL


 -u track this branch(--set-upstream)

8 Git's Graph Model

Git’s Directed Acyclic Graph

Git models the relationship of commits with a Directed Acyclic Graph

The arrows point at a commit’s parent(s). The entire graph contains a project's history. Each node in Git
represents a commit. The arrows point at a commit's parents.

In this example, you can see that commit D has two parents, commit B and commit C. The commits and
the relationship between them is what forms the project's history.

A branch occurs if a commit has more than one child.

This graph contains a branch because commit A has two children, commit B and commit C.

A merge occurs when a commit has more than one parent.


In this example, commit D is a merge of branch one and branch two.

git log command with the graph option shows commit diagram

git log--online --graph

Git uses a directed acyclic graph (DAG) to represent commit history.

Commits point to their parent commits

9  Git IDs

Internally, Git uses objects to store four types of things.

1. Commit object - A simple text file that contains information such as the commit user
information, commit message, a reference to the commits parent or parents and a reference to
the root tree of the project. That information is all that Git needs to rebuild the full contents of a
commit.
2. An annotated tag - A reference to a specific commit.
3. Tree - An object that contains a list of the file names and directories inside of a directory.
4. A blob - An object that stores the content of a file that is being managed by Git.

A typical Git user may only interact with commit objects and tags, letting Git worry about the details
related to trees and blobs. Git keeps these objects internally in something called the object store but
you typically don't directly interact with the object store.

Git ID

Git ID is the name of a Git object. All of the objects stored by Git are named with a 40-character
hexadecimal string. These strings are commonly known as Git IDs, but they are also known as object IDs,
SHA-1, hashes and checksums.
git hash-object <file> - Can be used to create SHA-1 values from file contents.

10 Git References

Commits can be associated with references. A reference is a user-friendly name that points to either
a commit's SHA-1 value or to another reference. If a reference points to another reference, it's called
a symbolic reference.

Here, the latest commit has two references associated with it, HEAD and master. Master is the default
name of the main branch in the repository. A branch is an independent path for a set of commits. If we
never create a branch in a repository, then by default, all commits are part of the master branch.

Branch label point s to the most recent commit in the branch. That commit is commonly
called the tip of the branch. Branch labels are implemented as references.

HEAD is a reference to the current commit. It usually points to the branch label of the current branch.
Because it only points to the current commit, and there can only be one current commit, there is only
one HEAD reference in your local repository.

In this example, we have three commits on the master branch. The master branch label reference points
to the most recent commit. The HEAD reference points to the master branch label.

A tag is a reference attached to a specific commit. It acts as a user-friendly label for the commit. These
are different from branch labels, which move along with each new commit. Tags are used to mark
important commits, like version 1.0.

Normally, SourceTree will create what is called an annotated tag. An annotated tag is one of the four
types of Git objects. However, if you check the lightweight tag box, you will create a simpler tag with less
features than an annotated tag. That is one of the reasons why this option is not recommended.

11 Git Checkout
In Git terms, a "checkout" is the act of switching between different versions of a target entity. The git
checkout command operates upon three distinct entities: files, commits, and branches. In addition
to the definition of "checkout" the phrase "checking out" is commonly used to imply the act of executing
the git checkout command. 
11.1 Checking out branches
The git checkout command lets you navigate between the branches created
by git branch. Checking out a branch updates the files in the working directory
to match the version stored in that branch, and it tells Git to record all new
commits on that branch. Think of it as a way to select which line of
development you’re working on.

12 Merging vs. Rebasing
12.1 The Merge Option
The easiest option is to merge the master branch into the feature branch using
something like the following:

git checkout feature


git merge master
Or, you can condense this to a one-liner:

git merge master feature


This creates a new “merge commit” in the feature branch that ties together the
histories of both branches, giving you a branch structure that looks like this:

Merging is nice because it’s a non-destructive operation. The existing branches


are not changed in any way. This avoids all of the potential pitfalls of rebasing

On the other hand, this also means that the feature branch will have an
extraneous merge commit every time you need to incorporate upstream
changes. If master is very active, this can pollute your feature branch’s history
quite a bit. While it’s possible to mitigate this issue with advanced git
log options, it can make it hard for other developers to understand the history
of the project.
12.2 The Rebase Option
As an alternative to merging, you can rebase the feature branch
onto master branch using the following commands:

git checkout feature


git rebase master
This moves the entire feature branch to begin on the tip of
the master branch, effectively incorporating all of the new commits in master.
But, instead of using a merge commit, rebasing re-writesthe project history by
creating brand new commits for each commit in the original branch.

The major benefit of rebasing is that you get a much cleaner project history.
First, it eliminates the unnecessary merge commits required by git merge.
Second, as you can see in the above diagram, rebasing also results in a
perfectly linear project history—you can follow the tip of feature all the way
to the beginning of the project without any forks. This makes it easier to
navigate your project with commands like git log, git bisect, and gitk.

But, there are two trade-offs for this pristine commit history: safety and
traceability. If you don’t follow the Golden Rule of Rebasing, re-writing project
history can be potentially catastrophic for your collaboration workflow. And,
less importantly, rebasing loses the context provided by a merge commit—
you can’t see when upstream changes were incorporated into the feature.
12.3 Interactive Rebasing
Interactive rebasing gives you the opportunity to alter commits as they are
moved to the new branch. This is even more powerful than an automated
rebase, since it offers complete control over the branch’s commit history.
Typically, this is used to clean up a messy history before merging a feature
branch into master.

To begin an interactive rebasing session, pass the i option to the git


rebase command:

git checkout feature


git rebase -i master
This will open a text editor listing all of the commits that are about to be
moved:

pick 33d5b7a Message for commit #1


pick 9480b3d Message for commit #2
pick 5c67e61 Message for commit #3
This listing defines exactly what the branch will look like after the rebase is
performed. By changing the pick command and/or re-ordering the entries, you
can make the branch’s history look like whatever you want. For example, if the
2nd commit fixes a small problem in the 1st commit, you can condense them
into a single commit with the fixup command:

pick 33d5b7a Message for commit #1


fixup 9480b3d Message for commit #2
pick 5c67e61 Message for commit #3
When you save and close the file, Git will perform the rebase according to
your instructions, resulting in project history that looks like the following:

13 Git stash
14 git stash temporarily shelves (or stashes) changes you've made to your
working copy so you can work on something else, and then come back
and re-apply them later on. Stashing is handy if you need to quickly switch
context and work on something else, but you're mid-way through a code
change and aren't quite ready to commit.

14.1 Stashing your work


The git stash command takes your uncommitted changes (both staged and
unstaged), saves them away for later use, and then reverts them from your
working copy. For example:

$ git status
On branch master
Changes to be committed:
new file: style.css
Changes not staged for commit:
modified: index.html
$ git stash
Saved working directory and index state WIP on master: 5002d47 our new homepage
HEAD is now at 5002d47 our new homepage
$ git status
On branch master
nothing to commit, working tree clean
At this point you're free to make changes, create new commits, switch
branches, and perform any other Git operations; then come back and re-apply
your stash when you're ready.

Note that the stash is local to your Git repository; stashes are not transferred
to the server when you push.

14.2 Re-applying your stashed


changes
You can reapply previously stashed changes with git stash pop:
$ git status
On branch master
nothing to commit, working tree clean
$ git stash pop
On branch master
Changes to be committed:
new file: style.css
Changes not staged for commit:
modified: index.html
Dropped refs/stash@{0} (32b3aa1d185dfe6d57b3c3cc3b32cbf3e380cc6a)
Popping your stash removes the changes from your stash and reapplies them
to your working copy.

Alternatively, you can reapply the changes to your working copy and keep


them in your stash with git stash apply:

$ git stash apply


On branch master
Changes to be committed:
new file: style.css
Changes not staged for commit:
modified: index.html
This is useful if you want to apply the same stashed changes to multiple
branches.

Now that you know the basics of stashing, there is one caveat with git
stash you need to be aware of: by default Git won'tstash changes made to
untracked or ignored files.

15 10 Git Commands You Should Know


https://towardsdatascience.com/10-git-commands-you-should-know-df54bea1595c

15.1 Inspecting Things

 git diff— See all file changes locally. A file name can be appended
to show changes for only one file. 📂
 git log — See all commit history. Can also be used for a file with git
log -p my_file. Enter q to exit. 📓
 git blame my_file— See who changed what and when in my_file. 👉
 git reflog — Show a log of changes to the local repository’s HEAD.
Good for finding lost work. 🔎

Inspecting things with Git isn’t terribly confusing. In contrast, Git


provides a plethora of options for removing and undoing commits
and file changes.
15.2 Undoing Things
git reset, git checkout, and git revert are used to undo the effects of changes
to your repository. These commands can be tricky to keep
straight.
git reset and git checkout can be used on both commits and individual
files.git revert is used only at the commit level.

If you are just dealing with your own local commits that haven’t
been merged into collaborative remote work, you can use any of
these commands.
If you are working collaboratively and need to neutralize a commit
in the remote branch, git revert is your tool.

Each of these commands can take a variety of options. Here are


common uses:

 git reset --hard HEAD— Discard staged and unstaged changes since
the most recent commit.
Specify a different commit instead of HEAD to discard changes
since that commit. --hard specifies that both the staged and
unstaged changes are discarded.

Make sure you don’t discard a commit from a remote branch that
your collaborators are depending upon!

 git checkout my_commit— Discard unstaged changes since


my_commit.
HEAD is often used for my_commit to discard changes to your local
working directory since the most recent commit.
checkout is best used for local-only undos. It doesn’t mess up the
commit history from a remote branch that your collaborators are
depending upon!
If you use checkout with a branch instead of a commit, HEAD is
switched to the specified branch and the working directory is
updated to match. This is the more common use of the checkout
command.

 git revert my_commit —Undo the effects of changes in my_commit.


revert makes a new commit when it undoes the changes.
revert is safe for collaborative projects because it doesn’t overwrite
history that other users’ branches might depend upon.

Sometimes you just want to delete untracked files in your local


directory. For example, maybe you ran some code that created
lots of different types of files that you don’t want in your repo.
Oops. 😏 You can clean them in a flash!

 git clean -n —Delete untracked files in the local working directory.


The -n flag is for a dry run where nothing is deleted.
Use the -f flag to actually remove the files.
Use the -d flag to remove untracked directories.

By default files untracked by .gitignore will not be deleted, but


this behavior can be altered.

15.3 Tidying Things

 git commit --amend — Add your staged changes to the most recent


commit.

If nothing is staged, this command just allows you to edit the most
recent commit message. Only use this command if the commit has
not been integrated into the remote master branch!

 git push my_remote --tags —Send all local tags to the remote repo.
Good for versioning changes.
15.4 Change Default Editor

To avoid Vim altogether, you can change your default editor in


Git. Here are docs with the commands for common editors. Here’s
the command to change the default for the editor I use, Atom:
git config --global core.editor "atom --wait"
Assuming you have Atom installed, you can now resolve your Git
issues inside it. Yeah! 👍

15.5 Make Shortcuts for Git Commands

Add shortcuts for Git commands by adding the following aliases


to your .bash_profile.
alias gs='git status '
alias ga='git add '
alias gaa='git add -A '
alias gb='git branch '
alias gc='git commit '
alias gcm='git commit -m '
alias go='git checkout '

You might also like