Version Control Git

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

Developer's Dilemma

Imagine you and your friend are working on a dashboard feature. How would you:

 Find the changes made by your friend?


 Get the changes made by your friend, and add new features to it?
 Undo the changes made by your friend a month ago as they are identified as bugs
now?

If you are wondering, keep reading to know how Git can help you!

Course Overview
In this course, you will learn:

 Distributed Version Control basics


 Basic Git commands
 Core concepts of Git like:
o Creating new features without affecting the current working version
(Branching)
o Collaborating with other developers (Clone, Push, Rebase and Merge
Conflicts)
o Saving new changes temporarily (Stashing)
o Selecting particular changes from others (Cherry-pick)

By the end of this course, you will be able to use Git.


Let's get started!

What is Version Control?


Version Control is a system which records the changes made to a file so that you can
recall a specific version later.

By using Version Control in your project, you can easily find out:

 What are the changes made


 Which files are changed
 When were the changes made
 Who has made the changes

Why Use a Version Control System?


In all software projects, the source code is the crown jewel that has to be protected
A Version Control System (VCS) gives you many super-powers that help you track changes
and secure your crown jewel such as:

 Collaborating with big teams smoothly to develop code


 Reverting the code to the bug-free version in case any minor change in the new
version introduces a bug
 Providing backup when the central server crashes
 Rendering an option to time-travel your project and go to a specific version

Types of Version Control Systems


 Local: It allows you to copy files into another directory and rename it (For example,
project1.1). This method is error-prone and introduces redundancy.
 Centralized: All version files are present in a single central server. For example,
CVS, SVN, and Perforce.
 Distributed: All changes are available in the server as well as in local machines.
For example, Git and Mercurial.

Centralized vs. Distributed Version Control


Systems
Centralized Distributed

You can keep changes only in the server You can keep changes locally (commit) as well

Changes can be merged in the server


Changes can be merged locally as well as remotely
(remote) alone

Work gets interrupted if the server is The project is present with all the team members
down to work locally

Git is the widely popular Distributed Version Control System which you will be learning in
this course.

Are you ready?

Let's Git Set, Go!

Cheat Sheet
 git clone: Get the complete project from remote to your local machine
 git pull origin <branch_name>: Get the new changes from remote branch to
local branch
 git push origin <branch_name>: Send your local branch changes to the remote
branch
 git remote add <name> <url>: Add a new remote repo link to your local repo
 git remote -v: List all the remote repo URLs linked to your local repo

image: git collaboration commands

https://gitforwindows.org/

How to Install Git?


For Windows
Windows Download Link
For Mac
Mac Download Link
For Linux
Type the following commands from the Shell.

$ sudo apt-get update


$ sudo apt-get install git

After successful installation of Git, you can configure your user name and e-mail ID using the
following commands.

$ git config --global user.name "First Last"


$ git config --global user.email "[email protected]"

Git Terminologies
Before starting with the basics, let's explore a few terminologies:

 Git Repository: A directory with .git folder, where all the contents are tracked for
changes.
 Remote: It refers to a server where the project code is present. For example, Github
and Gitlab.
 Commit: It is similar to version. When you make changes in a file, you need
to commit the changes in order to save and create its new version, which will
create a unique commit hash (like version number).
 Origin: It is a variable where Git stores the URL of your remote repository. For
example, origin => www.github.com/username/myrepo

Git Basic Commands


 git init adds .git folder and initializes the current folder to track its changes
 git status displays the current state of the staging area and the working directory,
that is, which files are added/removed/modified
 git diff shows the exact changes with line and column number
 git add adds the changes to the staging area. If you have added a new file, this
command starts tracking the file for modifications.
 git commit will save all the changes with a unique hash number in the local
repository
 git push sends the changes to the remote repository (server)

Stages in Git
The following are the three stages in the Git workflow:

 Working Area: You can edit files using your favorite editor/Integrated Development
Environment (IDE).
 Staging Area: You have made the changes and added the changes to Git. You
can still make changes here. (From the analogy explained in the next card) It is like
taking an item out of the box, where the box is the staging area. (git add)
 Local Repository: You have finalized the changes and committed them with a new
hash and proper message. (git commit)

Remote Repository: You can now push the changes to online platforms like Github or
Gitlab from where others can collaborate. (git push)

Git Stages: Analogy


Git works in three stages known as The Three Trees: Working Area, Staging Area, and
Local Repository, which means Git maintains three states of a file. To understand this
better, let us take an analogy of a box.
Assume you are packing items in the house in different boxes and labeling them to identify
it later.

 Get a table and keep all the items that you want to pack underneath. (git init)
 Now you might select specific kitchen items, dust them, and club similar items (like
spoons) together. (doing changes - Working area)
 Add the items that are ready to the box. (git add - Staged)
 Seal the box and add a label - 'Kitchen Items'. (git commit - Committed)

After git commit, a unique hash is created and the changes are saved.

https://www.youtube.com/watch?v=eL_0Ok_Gkas&t=241s

Ignore or Keep
If you do not want Git to track any file/directory, you can add the file/directory
to .gitignore file. To track an empty directory, you need to add .gitkeep to that empty
directory, as Git ignores them by default.

This video explains how to do that.

https://www.youtube.com/watch?v=ErJyWO8TGoM
What is .gitkeep in Git? Plus an example. - YouTube

Visualizing Git

To visualize the commands and see how your repository


changes with time, you can try out Git commands
in visualizing-git.

Git History
With multiple developers pushing new commits and changes, you might want to view the
history of everything that happened with the repository.
Git provides the following commands, which allows you to read and review your repo's
history:

 git log
 git show
 git diff
Before learning more about these tools, you must first understand the HEAD and Dot
operators.

What is HEAD in Git?

HEAD is a reference variable that always points to the tip of your current branch, that is,
recent commit of your current branch.

HEAD can be used with the following symbols to refer to other commits:

 Tilde symbol (~): Used to point to the previous commits from base HEAD
 Caret symbol (^): Used to point to the immediate parent commit from the current
referenced commit

Using HEAD wit ~ and ^


You can use both tilde and caret symbols in combination with HEAD to refer specific commit:

 HEAD means (the reference to) the recent commit of current branch -> F
o HEAD^1 means First parent of F -> E
o HEAD^2 means Second parent of F -> error as there is only one
immediate parent commit
 HEAD~1 means (the reference to) one commit before HEAD -> E
o HEAD~1^1 means First parent of E -> C
o HEAD~1^2 means Second parent of E -> D
o HEAD~1^3 means Third parent of E -> error
 HEAD~3 means (the reference to) three commits before HEAD -> B

Dot Operators
Double Dot Operator

 It is the default operator in git diff


 git diff master..feature or git diff master feature command will display all
the differences from G to C (that is, including F and G)

Triple Dot Operator

 It shows the difference between master and feature branch starting at the last common
commit E.
 git diff master...feature command's output would be the difference
in feature branch (that is, only A, B, and C)

Git Commands to View History




Git Log
Git log command shows the list of commits in the current branch. You can use it in the
following ways:

 git log -2 displays the history of last two commits


 git log commit_id shows the history starting from commit_id
 git log filename displays the list of commits for the file

Flags
You can enhance the output of git log command using these optional flags:

 --oneline: Fits the log output to a single line


 --decorate: Adds a symbolic pointer to the output
 --graph: Gives a graphical representation to the log output
 --grep=<pattern>: Filters the log output and displays the output which matches the
specified pattern

For example, git log --oneline

https://www.youtube.com/watch?v=ORwd7rpLlj0

Git Show
git show is a versatile command which is similar to git log, but with few additional
features.
You can pass different arguments like:

 commit_id
 tree

It shows the author's name, timestamp, commit message, and difference from the previous
commit.
For commit range git show --oneline HEAD~2..HEAD, it gets resolved, and each commit
is displayed individually.

Git Diff
git diff function takes two input datasets and outputs the changes between them.
Datasets can be commits, branch, files and more.
git diff HEAD~1 HEAD shows the difference between two commits.
Let us take a sample git diff output as follows.
diff --git a/sample.txt b/sample.txt
index 8d3g6cv..f94e50c 574641
--- a/sample.txt
+++ b/sample.txt
@@ -1 +1 @@
-this is a git diff test example
+this is a diff example

 The linediff --git a/sample.txt b/sample.txt displays the input file for git
diff
 --- a/sample.txt +++ b/sample.txt
The changes from a/sample.txt are marked with --- and changes from b/sample.txt are
marked with +++ symbol.

More on Git Diff


https://learning.oreilly.com/videos/learn-git-in/9781789348231/9781789348231-video2_3/?
sso_link=yes&sso_link_from=TCS

Cheat Sheet
 git log -p: Prints full details of each commit
 git log --grep-reflog=<pattern> : Shows the list of commits when commit
message matches regular expression pattern
 git log --follow ./path/to/filename : Shows the history for the current file
 git show: Outputs content changes of the specified commit
 git diff --color-words: Output has only the color-coded words that have
changed
 git diff –staged: Shows the file differences between staging and the last
committed version
 git diff .path/to/file: Shows changes in a file compared to the previous
commit

Local to Remote
In the previous topic, whatever you have learned was mostly limited to your local
machine. To collaborate with other developers, you need to push your work to the remote
repository, and vice-versa, you need to pull others' work from remote to contribute your
work to the project.
In Git, remote is a repository on a server where all your team members can place the
code to collaborate
Remote URL Types
You can keep your project code in remote servers like GitHub, GitLab or on a self-hosted
server. Git sets a default name for your remote URL as origin
Remote URL can be one of the two types:
 HTTPS URL like https://github.com/user/repo.git: You can clone/push
using your user name and password
 SSH URL, like [email protected]:user/repo.git: You need to configure SSH keys
in Github/Gitlab account and local machine
Keep reading to find out the Git commands used to collaborate with other developers.

Git Clone
To get source code of an already existing project from remote repo (For example,
Github), you can use git clone <url> command.
For example, git clone https://github.com/facebook/react.git
This command downloads the complete project, all branches, commits and logs from the
given remote URL (react repo here) to your local machine.

Git Pull
Your teammate has pushed the changes to the project's remote repo where you are also
working. You can now pull the changes to your local machine using any one of the
following commands.
 git pull is the convenient shortcut key to fetch and merge the content.
o git pull <remote_name> <branch_name>
 git fetch command downloads the remote content to your local repo, without
changing your code changes.
o git fetch <remote_name> <branch_name> fetches the content from that
specific branch in remote to your current working area
 git merge command merges the fetched remote content to the local working tree.
o git merge <remote_name>/<branch_name> merges the content to the
specified branch.

Git Push
To keep your changes and work in remote repo, you need to push the branch using the
command git push <remote_name> <branch_name>
Git push takes two arguments, namely:

 <remote_name>
 <branch_name>
For example, git push origin master, where:

 origin will contain the remote URL


 master is the branch that is pushed (We shall discuss branches later in this course)

Working with Existing Projects


Peter is new to the project. For a particular task, he created ten new files in his local machine.
His technical lead said there is a common repo where all the team members place their code.
He asked Peter to push his files to the same repo. What should Peter do?
In such a scenario, you can connect your local repo with an existing remote
repo using git remote add command.

Git Remote
The syntax to link your local repo with remote repo is:

git remote add <remote_name> <remote_url>

It takes two arguments, namely:

 <remote_name>, let us take default name origin


 <remote_url>, let us take https_url https://github.com/play/repo.git

For example: git remote add origin https://github.com/play/repo.git


Note: Your local repository can be linked to multiple remote repositories as git remote
add origin1 <url>, git remote add origin2 <url>

Emergency Tip

8 of 10

What is Branch in Git?


A Branch is a copy of your complete project, where you can add new changes and develop
new features. Technically, it is a collection of commits.

When you create a new Git project, it has a branch called master by default. Even in the
projects you clone from Github/Gitlab, a master branch is always present. Master branch
usually has the stable and working version of your application, and hence it can be
modified only by a few access-controlled users.


1 of 9

How to Build Features?


To build new features without affecting the current working code, you need to:

 Create new branch from the master git branch <branchname>. Here you will
write code for the new feature.
 Merge the feature branch with the master (or other branch where you want it to be).
You can merge two branches locally or in remote.

Keep reading to learn more about branches in Git.

Branch Operations
You can do the following with branch:

 Creating new branch: git checkout -b <branch-name>


 Pushing branch from local to remote repo: git push origin <branch-name>
 Renaming branch:
o Renaming local branch: git branch -m old-name new-name
o Renaming remote branch: git push origin :old-name new-name
 Deleting branch:
o Deleting local branch: git branch -d <branch-name>
o Deleting remote branch: git push origin -d <branch-name>

New Branches For New Features

In a project, two developers need to build sign-in and sign-up pages at the same time. How
can they do that without affecting the existing application?

They can create new branches for each new feature, such
as signin and signup branches and work on the features parallelly.

Building New Feature: Signin


For a new feature to be built:

 Create a new branch from the master branch: git checkout -b signin
 Add your new code in the new feature branch: git add -A
 Commit your changes once done: git commit -m "add signin page"
 Push your changes to the remote: git push origin signin

As your sign-in feature is ready in a different branch, now you can merge it with the master
branch.
Note: Merging will be discussed in the next topic.

Branching Demo

https://go.oreilly.com/TCS/videos/learn-git-in/9781789348231/9781789348231-video3_2

Tip on Branching

To see the difference between two branches (master


branch and test branch), you can execute the following
command
git diff master test

Cheat Sheet
 git branch -a: Lists all the branches
 git branch -d <branch-name>: Deletes the branch in local repo
 git checkout -b: Creates a branch and switches to it
 git checkout <branch-name>: Switches to the provided branch

Integrating Changes
Once you have developed your feature in a separate branch, you need to integrate the feature
and master branch. You can do that using one of the following two commands:

 merge
 rebase

Merging


What is Git Merge?

Merge is an operation to integrate changes from one branch to another branch


by adding a new commit


3 of 12

https://go.oreilly.com/TCS/videos/learn-git-in/9781789348231/9781789348231-video3_3

Merging Feature Branch: Signin to Master


You can merge the signin branch with the master in two ways:

 In your local and push master: git merge master signin && git push origin master
 In remote server: You need to create a new Pull request(or Merge request)
from signin branch to master branch in Github portal

Note: Even if you merge your feature branch with your local master, you will be unable to push your
code to remote if you do not have appropriate access (like admin access).

Rebase

What is Git Rebase?

Rebase is an operation to integrate changes from one branch to another. It is an alternative to


the Merge command.

If you are re-basing feature branch with master, the command will remove the original
commits on feature, bring all the commits from master to feature and add the original
commits on top of it.
 This changes the commit hashes and re-writes the history (as shown in gif in a
different color).
 This gives linear flow of development when you look at the history of repo.

Rebase: Demo
https://learning.oreilly.com/videos/learn-git-in/9781789348231/9781789348231-video3_6/?
sso_link=yes&sso_link_from=TCS

Merge vs. Rebase


While merge and rebase are both used to integrate changes of two branches, let us see
how they differ and which one you can use.

Merge Rebase

What Does not create any new commit while


Creates new commit while integrating
it integrating changes from one branch to
does? changes from one branch to another
another

It is destructive in nature, meaning, if


Safe you rebase your feature branch with
It is safe in nature, as it does not re-
or latest changes in master branch, your
not? write the history of your feature branch
feature branch commit hashes are
changes, re-writing history.

When your feature branch is in


When your feature branch is local and
When remote and someone else is creating
changing history will not affect others.
to new branch on top of your feature
use? Use git rebase to get new changes
branch. Use git merge to get the
from master to your feature branch.
changes from master to feature.

You can read more about it in atlassian.com

Cheat Sheet
 git merge <branch>: Merges <branch> to current branch
 git rebase <base>: Rebases the current branch onto the base (branch name,
commit ID, tag)
 git rebase -i <base>: Performs interactive rebase. Launches editor where you can
specify command on each commit to transform it.
 git rebase --abort: Cancels rebasing and goes back to the previous commit
 git rebase --continue: Continues rebasing after resolving the rebase conflicts
 git pull --rebase: Fetches the remote copy and rebases it into the current branch
of the local copy

The Conflict

Suppose you have planned to go for a movie with your family at 8 PM tomorrow. And at the
same time, your best friend has asked you to join for dinner.

What will you do? Confused?

Well, this is what happens to Git, conflict arises when two developers change the same
line of code. Git fails to understand which line to keep and which one to delete. So it asks
you to resolve the conflict.


1 of 4
Resolving Merge Conflicts
https://learning.oreilly.com/videos/learn-git-in/9781789348231/9781789348231-video3_4/?
sso_link=yes&sso_link_from=TCS

Resolving Rebase Conflicts


In this video, you will learn how to resolve to rebase conflicts.

https://www.youtube.com/watch?v=3MauMOo4B1s

Managing Changes
When you make a mistake in Word, what do you do? Ctrl+Z, right?
You cannot undo your mistakes in Git as you do in Word. But don't worry, Git gives you the
following.
Set of commands to undo your changes:

 amend
 checkout
 reset
 revert

Set of commands to undo/remove your files:

 rm
 clean

You will be learning more about each of them in this topic.

Git Amend
git commit --amend command is used to fix your previous commit where you do not
want to add a new commit. You can:

 Correct your typos in commit messages


 Add small changes in the file that you missed adding in the last commit

This command re-writes history by changing the commit-hash and the old commit will no
longer be on the branch. Be cautious and avoid amending on public commits (commits you
have already pushed to remote branch). Amending a public commit might create merge
conflicts for other developers.

Git Checkout
Git Checkout
Checkout is used to switch. You can switch between branches, commits, and files. Here you
will learn how to use this command to undo changes.
You can apply checkout command on:
 Working file
 Commit

Checkout Files

Oh no.. what am I doing? What is happening? I want to delete everything and start anew..

If this is what you feel, you can use checkout command to discard all your changes from
your working area and switch to the last committed version of your file. This command
will help you restart your work as if nothing happened.

Example: git checkout filename

Note: This command will only discard the changes in the working area. If you have
already staged the changes, you need to use reset command (as discussed later).

Checkout Commits
Why is the app behaving like this? Which commit has the bug?

While debugging the application, if this thought crossed your mind, then you can use git
checkout command to switch to a specific commit.

For example: git checkout commitSHA

 commitSHA is the commit hash to identify it uniquely. You can find this using git
log
 This command creates a detached head, meaning, this will give you a temporary
branch to work and debug.
 Avoid creating any new commits here, as this is a temporary branch

Git Reset
Git Reset
Reset, as the name says, is used to re-set your work to a specific point in time (a commit).
It is a powerful and versatile command, using which you can even undo the changes that
you have already committed.
Imagine your Git history as a timeline, then you can quickly jump to a specific time in the
past and reset your work as if nothing happened.
Next, you will learn how to apply reset command on:

 staged files
 commits

Reset Files

If you have staged your changes and forgot to add something, you can reset the file, so
the file is moved from staging to working area where you can make the required changes.

For example: git reset filename


Reset on Commits: Types

You tracked a bug in your project which is due to a rogue commit (commit 3 in the gif).

You can move to the previous commit where the app is working fine (commit 2 in the gif).
Did you wonder what will happen to the changes in those two commits that you are skipping?
You can use one of the following three flags, which decides in which stage the changes
should move:

 --soft: This moves your commit changes into staging area and does not affect
your current working area.
 --hard: This deletes all the commit changes. Be cautious with this flag. You might
lose your changes as this flag resets both staging area and working directory to match
the <commit>.
 --mixed: This is the default operating mode, where your commit changes are moved
to working area.
Reseting Branch Commits: Example
Example: git reset commitSHA

 This executes git reset --mixed commitSHA by default, moving all the changes to
the working directory
 You can find SHA code of your commit (where you want to move) using git log
 reset command adds a new commit, re-writing your history
 Avoid reset command, if the branch you want to reset is public (in remote), and
somebody else is building a new feature on top of yours. Instead, you can use revert.

Git Revert
Git Revert

You tracked a bug in your project which was due to a rogue commit.
git revert is another command to undo changes from an old commit, similar to reset.
However, git revert inverses the changes from that old commit and creates a new
revert commit, instead of deleting the old commit.

This helps prevent Git from losing history.

Revert vs. Reset Commits

While both reset and revert can undo your commit changes, the following are a few
differences.

Revert Reset

Deletes commit and


Does not delete commits and preserves history
changes history
Revert Reset

If other developers are using your branch to build new features,


Prefer reset if the
prefer revert to undo changes on that branch as it might prevent
branch is only in local
any conflicts

Managing Changes - Demo


This video explains how to use git checkout, git revert, and git reset

https://www.youtube.com/watch?v=3dk3s4LK-Wg

Delete Files
Just like changes (in a file), you might also want to undo/remove files. Depending on its
status, whether Git is tracking the file or not, you can use the following commands to remove
them:

 git rm
 git clean

Git Rm
git rm is used to delete any tracked file from your repository. Files from both the staging
area and the working directory can be removed using the same.
These changes will not persist until a new commit is added, which in turn creates a new
commit history.
You can get back your deleted files using git reset and git checkout.

Restore Deleted Files


How to restore a deleted file ?

 First, find the commit ID where the file was deleted: git rev-list -n 1 HEAD --
filename
 Then checkout to that commit ID to get back the file git checkout
deletingcommitid^ -- filename

Git Clean
git clean command undoes files from your repo. However, it stands unique from other
undo operations like checkout, reset and revert, as it primarily focuses on untracked files.
 git clean is undoable
 Git clean makes hard file deletion possible, similar to the Unix rm command.
 It is good to execute git clean -n command to perform a dry run, which helps to
know the list of files to be removed.

Cheat Sheet
 git revert <commit>: Creates a new commit that undoes all changes made in the
commit and applies it to the current branch
 git reset <file>: Moves file changes from staging area to working directory.
 git reset <commit>: Moves current branch's HEAD tip to the old <commit>. All
the changes in the commits (that you skipped to move to the old commit) are moved
to the working area.
 git commit --amend: Adds staged changes to the last commit and allows for editing
the old commit message
 git rm --cached(file_name): Untracks the current file
 git checkout <commit>: Switches the HEAD to the provided commit

Golden Rules of Git


 Create a new repository for every new project
 Create a new branch for every new feature
 Let branches be temporary, that is, delete the merged branch
 Write a good descriptive commit message, where:
o The first line should not be more than 75 characters
o Fix, Feature, or Update is present at the start of your commit message
 Use Pull Request (PR) to merge your code with master.

Course Summary
In this course, we have learned about Git. We have understood the following concepts

 Basic commands to add and commit files


 Pushing and Pulling from Remote Repo
 Fixing merge conflicts
 Creating Branches
 Concept of Rebase
 Viewing commit history and making changes to the previous commits

You might also like