Version Control Git
Version Control Git
Version Control Git
Imagine you and your friend are working on a dashboard feature. How would you:
If you are wondering, keep reading to know how Git can help you!
Course Overview
In this course, you will learn:
By using Version Control in your project, you can easily find out:
You can keep changes only in the server You can keep changes locally (commit) as well
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.
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
https://gitforwindows.org/
After successful installation of Git, you can configure your user name and e-mail ID using the
following commands.
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
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)
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.
https://www.youtube.com/watch?v=ErJyWO8TGoM
What is .gitkeep in Git? Plus an example. - YouTube
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.
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
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 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)
Flags
You can enhance the output of git log command using these optional flags:
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.
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:
Git Remote
The syntax to link your local repo with remote repo is:
Emergency Tip
8 of 10
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
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.
Branch Operations
You can do the following with branch:
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.
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
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?
3 of 12
https://go.oreilly.com/TCS/videos/learn-git-in/9781789348231/9781789348231-video3_3
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
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 Rebase
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.
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
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
rm
clean
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:
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.
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.
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.
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.
While both reset and revert can undo your commit changes, the following are a few
differences.
Revert 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.
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
Course Summary
In this course, we have learned about Git. We have understood the following concepts