9 Git
9 Git
Version control protects source code from both catastrophe and the casual degradation of human
error and unintended consequences.
Software developers working in teams are continually writing new source code and changing
existing source code. The code for a project, app or software component is typically organized in a
folder structure or "file tree". One developer on the team may be working on a new feature while
another developer fixes an unrelated bug by changing code, each developer may make their changes
in several parts of the file tree.
1. Made a change to code, realised it was a mistake and wanted to revert back?
2. Lost code or had a backup that was too old?
3. Had to maintain multiple versions of a product?
4. Wanted to see the difference between two (or more) versions of your code?
5. Wanted to prove that a particular change broke or fixed a piece of code?
6. Wanted to review the history of some code?
7. Wanted to submit a change to someone else's code?
8. Wanted to share your code, or let other people work on your code?
9. Wanted to see how much work is being done, and where, when and by whom?
10. Wanted to experiment with a new feature without interfering with working code?
In these cases, and no doubt others, a version control system should make your life easier.
Basic Actions
a) Add/Push: Put a file into the repo for the first time, i.e. begin tracking it with
Version Control.
b) Revision: What version a file is on (v1, v2, v3, etc.).
c) Head: The latest revision in the repo.
d) Check out/Pull/Fetch: Download a file from the repo.
e) Check in/Push: Upload a file to the repository (if it has changed). The file gets a
new revision number, and people can “check out” the latest one.
f) Check In Message: A short message describing what was changed.
g) Changelog/History: A list of changes made to a file since it was created.
h) Update/Sync: Synchronize your files with the latest from the repository. This lets
you grab the latest revisions of all files.
i) Revert: Throw away your local changes and reload the latest version from the
repository.
Advanced Actions
❖ Branch: Create a separate copy of a file/folder for private use (bug fixing, testing,
etc). Branch is both a verb (“branch the code”) and a noun (“Which branch is it
in?”).
❖ Diff/Change/Delta: Finding the differences between two files. Useful for seeing
what changed between revisions.
❖ Merge (or patch): Apply the changes from one file to another, to bring it up-to-date.
For example, you can merge features from one branch into another. (At Microsoft,
this was called Reverse Integrate and Forward Integrate)
❖ Conflict: When pending changes to a file contradict each other (both changes cannot
be applied).
❖ Resolve: Fixing the changes that contradict each other and checking in the correct
version.
❖ Locking: Taking control of a file so nobody else can edit it until you unlock it. Some
version control systems use this to avoid conflicts.
1. CVS
CVS may very well be where version control systems started. Released initially in 1986, Google
still hosts the original Usenet post that announced CVS. CVS is basically the standard here, and is
used just about everywhere – however the base for codes is not as feature rich as other solutions
such as SVN.
One good thing about CVS is that it is not too difficult to learn. It comes with a simple system that
ensures revisions and files are kept updated. Given the other options, CVS may be regarded as an
older form of technology, as it has been around for some time, it is still incredibly useful for system
admins who want to backup and share files.
2. SVN
SVN, or Subversion as it is sometimes called, is generally the version control system that has the
widest adoption. Most forms of open-source projects will use Subversion because many other large
products such as Ruby, Python Apache, and more use it too. Google Code even uses SVN as a way
of exclusively distributing code.
Because it is so popular, many different clients for Subversion are available. If you use Windows,
then Tortoisesvn may be a great browser for editing, viewing and modifying Subversion code bases.
If you’re using a MAC, however, then Versions could be your ideal client.
3. GIT
Git is considered to be a newer, and faster emerging star when it comes to version control systems.
First developed by the creator of Linux kernel, Linus Torvalds, Git has begun to take the
community for web development and system administration by storm, offering a largely different
form of control. Here, there is no singular centralized code base that the code can be pulled from,
and different branches are responsible for hosting different areas of the code. Other version control
systems, such as CVS and SVN, use a centralized control, so that only one master copy of software
is used.
As a fast and efficient system, many system administrators and open-source projects use Git to
power their repositories. However, it is worth noting that Git is not as easy to learn as SVN or CVS
is, which means that beginners may need to steer clear if they’re not willing to invest time to learn
the tool.
4. Mercurial
This is yet another form of version control system, similar to Git. It was designed initially as a
source for larger development programs, often outside of the scope of most system admins,
independent web developers and designers. However, this doesn’t mean that smaller teams and
individuals can’t use it. Mercurial is a very fast and efficient application. The creators designed the
software with performance as the core feature.
Aside from being very scalable, and incredibly fast, Mercurial is a far simpler system to use than
things such as Git, which one of the reasons why certain system admins and developers use it.
5. Bazaar
Similar to Git and Mercurial, Bazaar is distributed version control system, which also provides a
great, friendly user experience. Bazaar is unique that it can be deployed either with a central code
base or as a distributed code base. It is the most versatile version control system that supports
various different forms of workflow, from centralized to decentralized, and with a number of
different variations acknowledged throughout. . One of the greatest features of Bazaar is that you
can access a very detailed level of control in its setup. Bazaar can be used to fit in with almost any
scenario and this is incredibly useful for most projects and admins because it is so easy to adapt and
deal with. It can also be easily embedded into projects that already exist. At the same time, Bazaar
boasts a large community that helps with the maintenance of third-party tools and plugins.
In addition to being distributed, Git has been designed with performance, security and flexibility in
mind.
• Everyone’s using it
Linux: -
# sudo apt-get install git (Ubuntu) or
# yum install git (Centos) or
6. Create few directories and files in the Repo directory. (Directories should not be empty)
8. Update the index using the current content found in the working tree.
# git add .
9. Stores the current contents of the index in a new commit along with a log message from the user
describing the changes.
# git commit -m "<Put some message>"
11. Make changes to some files from github UI and pull the changes back to the local repo
12. Create new branch from master branch and pull the changes again to local repo.
# git pull
13. Make some changes to files and push it back to the latest branch
# git add .
# git commit -m "<Some message>"
# git push origin <branchname>
Explore the UI as much as you can, check histories, commits, changes, content of files, edit file
content, create multiple repositories.
Go through the below mentioned git repo and explore it, once you're through with above exercise
https://github.com/wakaleo/gamgit
NOTE
This book was written using Git version 2.0.0. Though most of the commands we use
should work even in ancient versions of Git, some of them might not or might act slightly
differently if you’re using an older version. Since Git is quite excellent at preserving
backwards compatibility, any version after 2.0 should work just fine.
Installing on Linux
If you want to install the basic Git tools on Linux via a binary installer, you can generally do so
through the basic package-management tool that comes with your distribution. If you’re on Fedora
for example, you can use yum:
For more options, there are instructions for installing on several different Unix flavors on the Git
website, at http://git-scm.com/download/linux.
Installing on Mac
There are several ways to install Git on a Mac. The easiest is probably to install the Xcode
Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run git
from the Terminal the very first time. If you don’t have it installed already, it will prompt you to
install it.
If you want a more up to date version, you can also install it via a binary installer. An OSX Git
installer is maintained and available for download at the Git website, at http://git-
scm.com/download/mac.
Another easy way to get Git installed is by installing GitHub for Windows. The installer includes a
command line version of Git as well as the GUI. It also works well with Powershell, and sets up
solid credential caching and sane CRLF settings. We’ll learn more about those things a little later,
but suffice it to say they’re things you want. You can download this from the GitHub for Windows
website, athttp://windows.github.com.
9. Setting up a repository
This tutorial provides a succinct overview of the most important Git commands. First, the Setting
Up a Repository section explains all of the tools you need to start a new version-controlled project.
Then, the remaining sections introduce your everyday Git commands.
By the end of this module, you should be able to create a Git repository, record snapshots of your
project for safekeeping, and view your project’s history.
git init
In git quick start guide we have seen to create git repository on github and then clone/pull that repo
to local computer but git clone command. We will see now how to create repo locally and then later
how to push it to github.
The git init command creates a new Git repository. It can be used to convert an existing,
unversioned project to a Git repository or initialize a new empty repository. Most of the other Git
commands are not available outside of an initialized repository, so this is usually the first command
you’ll run in a new project.
Executing git init creates a .git subdirectory in the project root, which contains all of the necessary
metadata for the repo. Aside from the .git directory, an existing project remains unaltered (unlike
SVN, Git doesn't require a .git folder in every subdirectory).
Usage
$ git init
Transform the current directory into a Git repository. This adds a .gitfolder to the current directory
and makes it possible to start recording revisions of the project.
git clone
The git clone command copies an existing Git repository. This is sort of like svn checkout, except
the “working copy” is a full-fledged Git repository—it has its own history, manages its own files,
and is a completely isolated environment from the original repository.
As a convenience, cloning automatically creates a remote connection called origin pointing back to
the original repository. This makes it very easy to interact with a central repository.
Example
$ git clone https://github.com/wakaleo/game-of-life.git
git config
The git config command lets you configure your Git installation (or an individual repository) from
the command line. This command can define everything from user info to preferences to the
behaviour of a repository. Several common configuration options are listed below.
Usage
$ git config user.name <name>
Define the author name to be used for all commits in the current repository. Typically, you’ll want
to use the --global flag to set configuration options for the current user.
Discussion
All configuration options are stored in plaintext files, so the git config command is really just a
convenient command-line interface. Typically, you’ll only need to configure a Git installation the
first time you start working on a new development machine, and for virtually all cases, you’ll want
to use the --global flag.
Git stores configuration options in three separate files, which lets you scope options to individual
repositories, users, or the entire system:
~/.gitconfig – User-specific settings. This is where options set with the --global flag are stored.
When options in these files conflict, local settings override user settings, which override system-
wide. If you open any of these files, you’ll see something like the following:
[user]
name = John Smith
email = [email protected]
[alias]
st = status
co = checkout
br = branch
up = rebase
ci = commit
[core]
editor = vim
You can manually edit these values to the exact same effect as git config.
Example
The first thing you’ll want to do after installing Git is tell it your name/email and customize some of
the default settings. A typical initial configuration might look something like the following:
git add
The git add command adds a change in the working directory to the staging area. It tells
Git that you want to include updates to a particular file in the next commit. However, git
add doesn't really affect the repository in any significant way—changes are not actually
recorded until you run git commit.
In conjunction with these commands, you'll also need git status to view the state of the
working directory and the staging area.
Usage
$ git add <file>
Stage all changes in <file> for the next commit.
$ git add -p
Begin an interactive staging session that lets you choose portions of a file to add to the
next commit. This will present you with a chunk of changes and prompt you for a
command. Use y to stage the chunk, n to ignore the chunk, s to split it into smaller
chunks, e to manually edit the chunk, and q to exit.
Discussion
The git add and git commit commands compose the fundamental Git workflow. These are
the two commands that every Git user needs to understand, regardless of their team’s
collaboration model. They are the means to record versions of a project into the
repository’s history.
Developing a project revolves around the basic edit/stage/commit pattern. First, you edit
your files in the working directory. When you’re ready to save a copy of the current state
of the project, you stage changes with git add. After you’re happy with the staged
snapshot, you commit it to the project history with git commit.
The git add command should not be confused with svn add, which adds a file to the
repository. Instead, git add works on the more abstract level of changes. This means that
git add needs to be called every time you alter a file, whereas svn add only needs to be
Instead of committing all the changes you've made since the last commit, the stage lets
you group related changes into highly focused snapshots before committing it to the
project history. This means you can make all sorts of edits to unrelated files, then go
back and split them up into logical commits by adding related changes to the stage and
commit them piece-by-piece. As in any revision control system, it’s important to create
atomic commits so that it’s easy to track down bugs and revert changes with minimal
impact on the rest of the project.
Example
When you’re starting a new project, git add serves the same function as svn import. To
create an initial commit of the current directory, use the following two commands:
$ git add .
$ git commit
Once you’ve got your project up-and-running, new files can be added by passing the path
to git add:
git commit
The git commit command commits the staged snapshot to the project history. Committed
snapshots can be thought of as “safe” versions of a project—Git will never change them
unless you explicitly ask it to. Along with git add, this is one of the most important Git
commands.
While they share the same name, this command is nothing like svn commit. Snapshots
are committed to the local repository, and this requires absolutely no interaction with
other Git repositories.
Usage
$ git commit
Commit the staged snapshot. This will launch a text editor prompting you for a commit
message. After you’ve entered a message, save the file and close the editor to create the
actual commit. git commit -m "<message>"
Commit the staged snapshot, but instead of launching a text editor, use <message> as the
commit message.
$ git commit -a
Commit a snapshot of all changes in the working directory. This only includes
modifications to tracked files (those that have been added with git add at some point in
their history).
Example
The following example assumes you’ve edited some content in a file called hello.py and
are ready to commit it to the project history. First, you need to stage the file with git add,
then you can commit the staged snapshot.
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
12. Syncing
SVN uses a single central repository to serve as the communication hub for developers,
and collaboration takes place by passing changesets between the developers’ working
copies and the central repository. This is different from Git’s collaboration model, which
gives every developer their own copy of the repository, complete with its own local
history and branch structure. Users typically need to share a series of commits rather
than a single changeset. Instead of committing a changeset from a working copy to the
central repository, Git lets you share entire branches between repositories.
The commands presented below let you manage connections with other repositories,
publish local history by "pushing" branches to other repositories, and see what others
have contributed by "pulling" branches into your local repository.
git remote
The git remote command lets you create, view, and delete connections to other
repositories. Remote connections are more like bookmarks rather than direct links into
other repositories. Instead of providing real-time access to another repository, they serve
as convenient names that can be used to reference a not-so-convenient URL.
Usage
$ git remote
List the remote connections you must other repositories.
$ git remote -v
Same as the above command, but include the URL of each connection.
Discussion
Git is designed to give each developer an entirely isolated development environment.
This means that information is not automatically passed back and forth between
repositories. Instead, developers need to manually pull upstream commits into their local
repository or manually push their local commits back up to the central repository. The
git remote command is just an easier way to pass URLs to these "sharing" commands.
http://host/path/to/repo.git
But, it’s generally not possible to push commits to an HTTP address (you wouldn’t want
to allow anonymous pushes anyways). For read-write access, you should use SSH
instead:
ssh://user@host/path/to/repo.git
You’ll need a valid SSH account on the host machine, but other than that, Git supports
authenticated access via SSH out of the box.
Examples
In addition to origin, it’s often convenient to have a connection to your teammates’
repositories. For example, if your co-worker, John, maintained a publicly accessible
repository on dev.example.com/john.git, you could add a connection as follows:
Usage
$ git fetch <remote>
Fetch all of the branches from the repository. This also downloads all of the required
commits and files from the other repository.
Discussion
Fetching is what you do when you want to see what everybody else has been working
on. Since fetched content is represented as a remote branch, it has absolutely no effect on
your local development work. This makes fetching a safe way to review commits before
integrating them with your local repository. It’s similar to svn update in that it lets you
see how the central history has progressed, but it doesn’t force you to actually merge the
changes into your repository.
Remote Branches
Remote branches are just like local branches, except they represent commits from
somebody else’s repository. You can check out a remote branch just like a local one, but
this puts you in a detached HEAD state (just like checking out an old commit). You can
think of them as read-only branches. To view your remote branches, simply pass the -r
flag to the git branch command. Remote branches are prefixed by the remote they belong
to so that you don’t mix them up with local branches. For example, the next code snippet
shows the branches you might see after fetching from the origin remote:
git branch -r
# origin/master
# origin/develop
# origin/some-feature
Again, you can inspect these branches with the usual git checkout and git log commands.
If you approve the changes a remote branch contains, you can merge it into a local
branch with a normal git merge. So, unlike SVN, synchronizing your local repository
with a remote repository is actually a two-step process: fetch, then merge. The git pull
command is a convenient shortcut for this process.
Usage
$ git pull <remote>
Fetch the specified remote’s copy of the current branch and immediately merge it into
the local copy. This is the same as git fetch <remote> followed by git merge
origin/<current-branch>.
Discussion
You can think of git pull as Git's version of svn update. It’s an easy way to synchronize
your local repository with upstream changes.
You start out thinking your repository is synchronized, but then git fetch reveals that
origin's version of master has progressed since you last checked it. Then git merge
immediately integrates the remote master into the local one:
In fact, pulling with --rebase is such a common workflow that there is a dedicated
configuration option for it:
Examples
The following example demonstrates how to synchronize with the central repository's
master branch:
Usage
$ git push <remote> <branch>
Push the specified branch to <remote>, along with all of the necessary commits and
internal objects. This creates a local branch in the destination repository. To prevent you
from overwriting commits, Git won’t let you push when it results in a non-fast-forward
merge in the destination repository.
Discussion
The most common use case for git push is to publish your local changes to a central
repository. After you’ve accumulated several local commits and are ready to share them
with the rest of the team, you (optionally) clean them up with an interactive rebase, then
push them to the central repository.
1. Open Terminal.
/home/<USERNAME>/.ssh/id_rsa_github
Note: USERNAME in above path is you Linux system user with which you have logged in.
2. Open or create config file and update it with below mentioned content
# vi config
Host github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa_DO_github
User git
IdentitiesOnly yes
# cat ~/.ssh/id_rsa_DO_github.pub
2. Login to github with the same email id you provided while create ssh keys
Click on settings => SSH and GPG keys => New SSH key => Give a name => Paste the public key
content => Add SSH keys