Mastering GIT A Beginner's Guide
Mastering GIT A Beginner's Guide
DOI: 10.1201/9781003229100
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
v
vi ◾ Contents
Sharing Tags 83
Deleting Tags 83
Check Out the Tags 84
Retagging or Replacing Old Tags 85
APPRAISAL, 223
INDEX, 231
About the Editor
xiii
CHAPTER 1
Getting Started
IN THIS CHAPTER
DOI: 10.1201/9781003229100-1 1
2 ◾ Mastering Git
WHAT IS GIT?
Git is a version control software meant for tracking changes
in a given set of files, for ensuring coordinated work among
programmers who are collaboratively developing a source
code for software development. Its proposed goals are
speed, support for distributed, non-linear workflows, as
well as data integrity. To quote its original author, Linus
Torvalds, “You can do a lot of things with Git, and many of
the rules of what you *should* do are not so much techni-
cal limitations but are about what works well when work-
ing together with other people. So Git is a very powerful set
of tools” (Torvalds, 2015).
Git is a free plus open-source software distributed
under the GNU General Public License version 2. Apart
from version control, Git is also used for other applications
including content management as well as configuration
management. The creator of the operating system Linux,
Linus Torvalds, developed and launched Git in 2005. He
took up this project because all the open-source VCSs
available at that time were failing to match the require-
ments of the Linux kernel development. Basically, the rela-
tionship between the VCS BitKeeper and the Linux team
had broken. Some kernel developers also made significant
contributions to Git’s early development. Junio Hamano
10 ◾ Mastering Git
This means that you can work in isolation, but also syn-
chronize the data easily with the rest of your team. Push
and Pull features are exceptions to all the other operations
on Git that are carried out locally. Not only that, the cen-
tralized approach of systems like SVN too can be replicated
on Git using platforms like GitHub, GitLab, Bitbucket, etc.
Git just adds data. Any action you do on Git basically
only adds more data to the Git repository. The system
ensures you cannot erase data or do anything that can-
not be undone. You will of course lose changes if you do
not commit them properly, but once you have commit-
ted data into a snapshot in Git, it is unlikely that you will
lose it, particularly if you continue pushing your database
into another repository. So, Git offers you a safe space to
experiment without the fear of screwing up things too
dramatically.
Git offers a few basic tools to undo the changes you have
made. However, be mindful that you cannot undo some of
the undos themselves. This is a space where you may end
up losing work if you mismanage. A common undo that is
used often is if you mess up your commit message or com-
mit too early, without adding the necessary files. To redo
that particular commit, make the additional changes you
forgot about, stage them, and recommit using the amend
option. From Git version 2.23.0, the command git restore,
an alternative to git reset, can also be used for purposes of
undoing changes.
Git is not a SCM tool, as per its initial design approach.
Nevertheless, its features being created as needed, Git has
now developed a set of characteristics that can be expected
out of a traditional SCM system. Git utilizes two data
Getting Started ◾ 13
ADVANTAGES OF GIT
Moving from a centralized VCS to Git will fundamentally
change the way your coders create software. If your orga-
nization is heavily reliant on software for critical applica-
tions, the altered workflow is bound to impact the entire
business. Hopefully, Git should benefit each and every
aspect of your organization, whether it is marketing or
development. Some of the benefits that Git provides to cod-
ers are speed, simplicity, proper distribution, a conducive
16 ◾ Mastering Git
For Development
Git’s branching capabilities happen to be one of its most
advantageous features. Unlike the branches of centralized
VCSs, Git branches are cheap and easier to merge. This
provides the facility of feature branch workflow, which
can significantly benefit an organization. Every change to
the code base is provided in an isolated environment. The
main branch contains the production quality code, and
any change, big or small, consequently has to be commit-
ted to a new branch. Your development work is thus repre-
sented with as much focus as your backlog. A Jira ticket, for
example, can be addressed using its own feature branch.
Being a DVCS, Git provides better speed. Everyone
can work on their own changes separately in their local
repositories without any threat of blocking and intermit-
tent interruptions. If a developer accidentally eliminates
her/his own repository, they can simply clone someone
else’s and start anew. This makes sure that Git is resilient to
crashes since each node (a system on which a single devel-
oper works) has a copy of the source tree. Apart from this,
the issues of security are effectively handled by Git with the
cryptographic method SHA-1, an algorithm responsible
for managing your versions, directory, and files, to make
sure that your work is not corrupted.
SCM tools like Bitbucket further enhance Git’s core
functionality with facilities like pull requests. A developer
Getting Started ◾ 17
With Git, you can push out a solution for your customers as
soon as your developers have resolved the issue with code
changes. If your priorities change and you have to wait
before introducing a new feature, that particular branch can
sit in waiting till your engineers come around to it.
Git for HR
Using Git will encourage developers to join your organiza-
tion, since employees are drawn to companies providing
healthy opportunities for career growth and development,
and leveraging Git is an advantage that any developer
would like to have, whether your organization happens to
be big or small.
DISADVANTAGES OF GIT
Some of the disadvantages of making use of GIT are:
HISTORY OF GIT
The development of Git began due to a creative conflict.
It was during the early years of Linux kernel mainte-
nance, i.e. from 1991 to 2002 that the software changes
were passed around as archived files as well as patches.
Eventually, in 2002, the Linux kernel project started using
a proprietary DVCS which was called BitKeeper. BitKeeper
was a proprietary, paid-for tool even at that point of time,
but the Linux development community was allowed to use
it free of cost. However, in 2005, the relationship between
the Linux kernel community and the commercial com-
pany responsible for the development and maintenance
of BitKeeper went sour, and the tool’s free-of-cost status,
subsequently was revoked. The man who was the copy-
right holder of BitKeeper, Larry McVoy, withdrew the free
use of the product after his claim that Andrew Tridgell
had created SourcePuller by making use of reverse engi-
neering processes on the BitKeeper’s protocols. This same
incident was also responsible for spurring the creation
of another VCS, Mercurial. McVoy’s accusations led the
Linux development community, particularly Linux creator
Linus Torvalds, to build a tool of their own, utilizing their
learnings and experiences with BitKeeper. Torvalds called
the system “Git” because he liked the word, when he came
across it in a Beatles song I’m So Tired (verse two). He says,
Getting Started ◾ 27
REFERENCES
Favell, A. (2020, February 4). The history of git: The road to
domination. The History of Git: The Road to Domination.
https://w w w.welcometot hejungle.com/en/ar ticles/
btc-history-git.
34 ◾ Mastering Git
The Basics
IN THIS CHAPTER
➢ Installing Git
➢ First Time Git Setup
➢ Tips and Troubleshooting
INSTALLING GIT
Git can be easily installed on most of the operating systems
like Linux, Mac, Windows, etc. Mostly, Git comes prein-
stalled on the Linux and Mac Machines. So you best first
DOI: 10.1201/9781003229100-2 35
36 ◾ Mastering Git
Editing
After setting up your identity, you need to now go into the
configuration details of the text editor that will be utilized
whenever Git needs you to type up a message. Without
your intervention, Git will end up using the default editor
of your system. If you need to use a different text editor, say
Emacs, do the following:
Git Clone
This will help in creating clones of an existing repository. If
a particular project has already been set up in the Git cen-
tral repository, the clone command should help the users in
creating the local development clones for conducting their
edits and commits. Cloning is a one-time operation, just
like git init. Once a coder obtains her/his working copy,
all the version control operations will subsequently be con-
ducted locally. git clone creates copies of remote reposito-
ries. You give git clone a repository URL to work with. Git
supports quite a few different network protocols as well as
The Basics ◾ 45
Saving Changes
With the repository cloned, you can now begin committing
the file version changes to it. After executing this action,
your repo will have CommitTest.txt added to the history
and will be tracking all the future updates to the file to
maintain a proper record of the version history. Executing
the git add—all command should also be able to take any
changed or untracked files in the repo and subsequently
add them for the purposes of updating the repo’s working
tree.
Git Push
Git Push plays an important role in ensuring Repo-to-
repo collaboration. Git’s understanding of a “working
copy” is different from that of Subversion (SVN) wherein
you checkout the code from a repository. Git does not
discriminate between the working copies and the central
repository, they are all to be considered full-fledged Git
Repositories in and of themselves. So while the function-
ing of SVN is predicated on the relationship between the
central repository and the working copies, the operations
on Git, conversely, rely on how the repositories interact
with each other. In Git, commits are to be pushed up and
pulled down from one repository to other. Of course, you
are allowed to give specific repositories special meaning.
46 ◾ Mastering Git
Reverting Changes
To do away with the local changes made to specific files in
the working tree as well as replacing the same files with the
ones in the Index, do the following:
The IDE should now replace the selected files with the ones
you have specified.
ZPVSCSBODI'PSFYBNQMF JGZPVXBOUUPHPUISPVHI
UIFDPOUFOUTPGUIFЋMFYZ[POUIFNBJOCSBODI FYF
DVUFUIFDPNNBOE
/PX Z PVX PVMEC FB CMFU PW JFXU IFD POUFOUTP GU IFЋ MF
GSPNZPVSPXOUFSNJOBM
t $POEVDUJOHTFBSDIFT:PVDBODPOEVDUTFBSDIFTPO
(JUF WFOJ GZ PVB SFV OTVSFB CPVUX IJDID PNNJU PS
CSBODI ZPVNBEFZPVSDIBOHFTUP. ThJTTIPVMETBWF
ZPVQMFOUZPGUJNFBTXFMMBTCPPTUZPVSQSPEVDUJWJUZ
#FDBVTF(JUJTWFSZFffiDJFOUBUIFMQJOHTNBMMUFBNTJONBO
BHJOHU IFJST PftXBSFE FWFMPQNFOU L FFQJOHT PNFU JQTJ O
NJOED BONB LFD PMMBCPSBUJWFX PSLF WFON PSFF ffFDUJWF
5PNBLF(JUXPSLXFMMXJUIEJWFSTFUFBNT XJUINFNCFST
IBWJOHWBSZJOHMFWFMTPGFYQFSUJTF LFFQUIFGPMMPXJOHUJQT
JONJOE
t 'PSNBMJ[FZ PVS( JUD POWFOUJPOT.B LFT VSFU IBU
ZPVSUFBNIBTBTUBOEBSETFUPGDPOWFOUJPOTGPSDPE
JOH UBHHJOH CSBODIOBNJOH FUD&WFSZPSHBOJ[BUJPO
IBTJUTPXOTFUPGHPPEQSBDUJDFT BOEZPVTIPVMEBMTP
CFBCMFUPЋOESFDPNNFOEBUJPOTGSPNDPEFSTXPSL
JOHJ OU FBNTP OMJOF8 IBUJ TD SVDJBMJ TU IBUBT UBO
EBSEJ[FET FUP GS VMFTJ TF TUBCMJTIFES JHIUG SPNU IF
TUBSUBOEGPMMPXFEUISPVHICZUIFFOUJSFUFBN. ThJTJT
BMTPJ NQPSUBOUCFDBVTFUFBNNFNCFSTV TVBMMZIBWF
BWBSZJOHTFUPGDBQBDJUJFT TPNBJOUBJOJOHBCBTJDTFU
The Basics ◾ 51
Working with
Repositories
IN THIS CHAPTER
DOI: 10.1201/9781003229100-3 57
58 ◾ Mastering Git
do this, first add your changes to the Index, i.e. the stag-
ing area, followed by committing those indexed changes
to your local repository. You can add your changes to the
index by making use of the git add command. The com-
mitting process, on the other hand, is done through the use
of the git commit command. In addition to this, Git makes
use of the push and pull commands in order to allow the
user to synchronize their local repositories with reposito-
ries on remote servers, i.e. the nodes of other developers.
Once you have created your first commit, you should also
be able to see some output that the commit gives regard-
ing itself, what the SHA-1 checksum of the commit is, how
many files underwent a change, the lines that were added or
removed from the commit, etc. A commit will also record
a snapshot of the setup of your staging area. Anything that
you did not stage lies modified, and you will have to make
another commit, so as to make that change a part of your his-
tory. Every commit is necessarily accompanied by a snapshot
of that particular stage, which can be recreated/revisited by
the user later. Moreover, if the staging area is proving to be too
complex for your workflow in the project, it can be skipped
through a simple shortcut. Add the “-a” option to your git
commit command, and Git should automatically be able to
stage every file that was being tracked before the commit,
thereby allowing you to skip the git add part. While this is a
very convenient option, bear in mind that sometimes, it might
cause you to include unnecessary and unwanted changes.
In order to remove a file from Git, make sure that you
remove it from your tracked files, i.e. your staging area,
and then commit. The git rm command should be able to
do that, removing the file from your working directory
lest it shows up as untracked the next time around. On the
other hand, if you simply remove that file from your work-
ing directory, it will show up as unstaged in your git status
output, i.e. a change that is yet to be staged for a commit.
Further, if you had modified a particular file or sent it to
the staging area, you can remove it using the -f option. This
option acts as a safety feature, preventing the accidental
elimination of data that is yet to be recorded using a snap-
shot or that otherwise cannot be recovered.
66 ◾ Mastering Git
You might also want to try keeping the file in your work-
ing tree, while removing it from your staging area. So, store
the file at a place where Git cannot track it anymore. This
can be remarkably useful if you did not add something
with the .gitignore file, and subsequently staged it, say a set
of .a compiled files, or a huge log file, etc. and can be con-
ducted using the—cached option. You should also be able
to pass directories, file-glob patterns, files, etc. through the
git rm command.
Unlike other VCSs, Git does not track file movement.
When you rename a file in Git, it shall not store metadata
to let you know that you renamed that file, though the sys-
tem itself is smart about realizing that later on, after the
action has been conducted.
Lastly, a couple of tips and tricks to help you conduct
your work smoothly while recording changes to your
repositories:
There are different sets of changes you will have to make
as part of your development work. So, you should separate
your bug fixes, improvements, new features, etc. into dif-
ferent, well-annotated commits for your team members to
understand the purpose and the reasoning behind your
work when it is being reviewed. This work will also prove
significant while conducting merges.
To make your commits easily comprehensible for other
team members, use the following structure:
them, and for you, they will either be read-only files or the
read/write kind of files. Collaboration with multiple devel-
opers will involve your abilities at managing these many
remote repositories, as well as pushing and pulling the data
to and from them, as and when you are required to share
work. You must be able to remove repositories that are not
relevant to your work, add other remote repositories, man-
age the remote branches, see if they are tracked or not, etc.
We should be able to learn some remote management tips
in this section:
GIT ALIASES
One of the features that will undoubtedly make your Git
experience easier: aliases. If you plan to work on Git con-
sistently, aliases are something that you ought to famil-
iarize yourself with. If you have only typed out your text
partially, there is no way for Git to automatically compre-
hend your command. If you do not wish to type the whole
text while using the many commands that you will have to
on Git, you can always use the git config command so that
you can set up an alias for those commands that you tend
to use frequently.
Although the Graphical User Interface (GUI) of Git
is very useful when it comes to ensuring an integrated
development environment (IDE), like Visual Studio (VS)
Code, Intelli, etc. at other times, you will have to resort to
command-line interface (CLI) for better work and higher
productivity. A CLI is usually defined as a user interface
of an application, which accepts a line at a time typed in
commands. The program that handles such an interface is
known as a command-line processor or a command-line
interpreter. Today, most users tend to rely on GUIs as well
as menu-driven interactions. But, some maintenance and
programming jobs might not have a GUI at all, preferring
Working with Repositories ◾ 73
that, you should begin your command with the “!” charac-
ter. This will be particularly useful for the developers who
write their own tools to work with a proper Git repository.
For the git search commit, Git alias allows you to define
many complex aliases, like executing the external shell
commands, executing custom scripts as well as more lay-
ered commands, like those for shell pipes, etc. For exam-
ple, you could define these alias to conduct searches within
your commits, as well as to search for particular strings, as
per your wants and needs.
It is crucial to remember that there is no specific com-
mand for git aliases. Aliases are to be created via the use of
the git config command as well as Git’s configuration files.
The git config command is a very useful command that
helps in the quick creation of aliases. It is a helper com-
mand so that we can write to the local as well as the global
Git config files. Here, the values in a local file shall apply
only to a single repository, while the configuration values
of a global file apply to a single user. Git utilizes a hierar-
chical approach toward configuration, wherein the settings
of a broader scope are to be inherited, if not straight-up
overridden. At the top level is the system config, for all
users, that is stored in/etc/git. This is followed by the global
config that can override the system defaults with the per-
sonal ones, and is located inside the home directory of the
user, for example, $HOME/.config/git/config or $HOME/.
gitconfig. Lastly, there is the local config for a particular
repository, located at .git/config in the repository root, i.e.
the repo’s .git directory, which should be able to override
the other aforementioned configs, to be able to set specific
options for the repositories. The local configuration applies
Working with Repositories ◾ 75
[alias]
co = checkout
Co here is a shortcut for the word
"checkout".
$ git st
## master
$ git st
## master
M test2
?? test3
TAGGING
Let’s begin by defining tagging, and how it involves the use
of the git tag command. Tags are references that point to
some specific points that are contained in the git history.
Tagging is utilized to capture a particular point in history,
and made use of for a marked version release. A tag, then,
is a branch that is immune to any kind of change. Tags,
unlike branches, will not have a history of commits after
being created. The Git software allows you to create tags,
delete them, list them all, share them, etc.
Like the other VCSs, Git can tag specific points in a
repository’s history as being significant. People usually
make use of this functionality provided by the software
to mark out the release points (v1.0, v2.0, etc.). By the end
of this section, you should be able to have an elementary
understanding of how you can create as well as delete tags,
how you can list existing tags, what those various kinds of
tags are, etc.
How to List Your Tags?
In Git, listing the tags constitutes a fairly straightforward
process. Type “git tag” (with either -l or -list):
$ git tag
v1.0
v2.0
Working with Repositories ◾ 81
Creating Tags
There are two kinds of tags that Git offers—lightweight and
annotated. A lightweight tag is like a branch that doesn’t
change much; it is only a pointer to a particular command.
The annotated tags, however, are stored in the Git database
as complete objects. They contain a lot of extra metadata like
the tagger name, email, as well as date, are checksummed,
contain a tagging message, and are to be signed as well as
verified using GNU Privacy Guard, abbreviated as GPG.
Like commits as well as commit messages, the annotated
tags are accompanied by a tagging message. It is further
recommended that you should be able to create annotated
tags in order to acquire all this information; nevertheless,
lightweight tags are also available to be worked with in case
you only want a temporary tag, and do not want to retain
other information.
82 ◾ Mastering Git
Annotated Tags
The process of creating an annotated tag in Git is fairly
simple. You just have to specify “-a” when you have to run
the tag command. “-m” stands for tagging message, which
is to be stored with the tag. Git also tends to launch your
editor if you fail to specify a message to go along with your
annotated tag, so that you are able to type it in. By using
the git show command, you should also be able to see the
tag data alongside the commit which has been tagged. This
should also show you the date the commit was tagged on,
the tagger information, as well as the annotation message
available.
Lightweight Tags
Commits can also be tagged by utilizing lightweight tags.
This includes the commit checksum which is stored in a
file, and where no other information is to be kept. In order
to create a lightweight tag, you just need to provide a tag
name, rather than supplying options like -a, -s, -m, etc. For
lightweight tags, the git show command will just show you
the commit, and not the extra tag information that comes
with it, which was visible in the case of annotated tags.
Tagging Later
You can tag commits even after you have moved away from
them. Let’s say you forgot to tag a project, of a specific com-
mit. You need not worry because this issue can be resolved
after the fact. To tag your commit now, make sure that you
specify the commit checksum, or at least a part of it, at the
end of your command. Post this, you should be able to see
that your commit has now been tagged.
Working with Repositories ◾ 83
Sharing Tags
The git push command cannot transfer tags to remote serv-
ers on its own. You shall have to explicitly push your tags to
a shared server after you create them. This process is akin to
sharing remote branches; you should be able to carry it out
by running the command git push origin <tagname>. If you
have many tags, and you wish to push them all at once, you
are recommended to use the—tags option for the git push
command. This will ensure the transfer of all your tags to the
remote server, that aren’t already there. So, now if someone
will pull from your repository, or simply clone it, they should
be able to acquire all of your tags simultaneously. However,
do keep in mind that the git push command will push both
annotated as well as lightweight tags. This is because cur-
rently, the Git software does not offer us any option of being
able to push only the lightweight tags. However, if you intend
to push only the annotated tags to your remote repositories,
you should use the git push <remote> -follow-tags.
Deleting Tags
In order to delete a tag from your local repository, you
would have to use the command git tag -d <tagname>.
84 ◾ Mastering Git
Working with
Branches
IN THIS CHAPTER
Working
A branch is supposed to represent an independent line of
development. Branches are an abstract form of the editing-
staging-committing process. Branches give you a com-
pletely fresh staging area, project history, as well as working
directory. Any new commit created is to be recorded in the
history of the current branch, resulting in a fork in the work-
ing history of the project. The git branch commands allow
you to create, rename, list, as well as delete the branches.
However, the commands available on the software cannot
allow you to switch between multiple branches, or combine
a forked history that had been divided earlier. This is the
Working with Branches ◾ 91
Common Commands
Creation of Branches
It is desirable and imperative for us to restate that branches are
just supposed to be pointers for the commits. Whenever you
92 ◾ Mastering Git
will create a new Git branch, Git will simply just add a new
pointer. There is no need to change the history of the repos-
itory in any manner whatsoever. After creating a branch,
you are expected to follow it up with the creation of com-
mits, using the commands git checkout, the standard git
add, as well as the git commit commands.
Deleting Branches
Once you have completed your work on a branch, and have
merged it to the main codebase as well, you will be well-
advised to delete the branch without having to lose any his-
tory. However, you will end up receiving an error message
if you attempt to delete a branch without having merged
it. This should protect you from losing access to a whole
line of development that you might have worked very hard
on. If you must delete the branch anyhow, you could, as
mentioned previously as well, use the command git branch
-D <branch>, which will force delete the branch whether it
has been merged or not. Because it will eliminate a branch
irrespective of its status, and without giving you a second
warning, make sure you are careful with it and use it with
good jurisprudence. The previously mentioned commands
Working with Branches ◾ 93
)BTI"MHPSJUIN JTBLJOEPGDSZQUPHSBQIJDIBTIGVODUJPO
XIJDIUBLFTJOBOJOQVUBOEGPMMPXTVQCZQSPEVDJOHB
CJU PSCZUF IBTIWBMVFUIBUJTLOPXOBTBNFTTBHFEJHFTU
ThJTNFTTBHFJTVTVBMMZSFOEFSFEBTBIFYBEFDJNBMOVNCFS
XIJDIJTEJHJUTMPOH3FWJTJPO$POUSPM4ZTUFNTMJLF(JU
.POPUPOF .FSDVSJBM FUDNBLFVTFPG4)" OPUGPSTFDV
SJUZD SVDJBMMZ C VUJ OP SEFSU PC FB CMFU PJ EFOUJGZN VMUJQMF
SFWJTJPOT B TXFMMB TFOTVSFU IBUU IFE BUBIB TOPUDIBOHFE
JOB OZX BZ E VFU PB DDJEFOUBMMZD BVTFED PSSVQUJPO- JOVT
5PSWBMET UIFDSFBUPSPG(JU IBTTBJEUIJTBCPVU4)"
*G ZPV IBWF EJTL DPSSVQUJPO JG ZPV IBWF %3".
DPSSVQUJPO JGZPVIBWFBOZLJOEPGQSPCMFNTBUBMM
(JUXJMMOPUJDFUIFN*UTOPUBR VFTUJPOPGif JUTB
HVBSBOUFF:PVDBOIBWFQFPQMFXIPUSZUPCFNBMJ
DJPVT. ThFZX POUT VDDFFEy/ PCPEZIB TC FFO
BCMF UP CSFBL 4)" CVU UIF QPJOU JT UIF 4)"
BTGBSBT(JUJTDPODFSOFE JTOUFWFOBTFDVSJUZGFB
UVSF*UTQVSFMZBD POTJTUFODZD IFDL. ThFT FDVSJUZ
QBSUTBSFFMTFXIFSF TPBMPUPGQFPQMFBTTVNFUIBU
TJODF(JUVTFT4)"BOE4)"JTVTFEGPSDSZQUP
HSBQIJDBMMZTFDVSFTUVff UIFZUIJOLUIBU 0LBZ JUT
BIVHFTFDVSJUZGFBUVSF*UIBTOPUIJOHBUBMMUPEP
XJUITFDVSJUZ JUTKVTUUIFCFTUIBTIZPVDBOHFUy
*HVBSBOUFFZPV JGZPVQVUZPVSEBUBJO(JU ZPV
DBOUSVTUU IFGBDUU IBt fiWFZFBSTMBUFS B ftFSJUXBT
DPOWFSUFEG SPNZ PVSIB SEE JTLU P%7%U PX IBU
FWFSOFXUFDIOPMPHZBOEZPVDPQJFEJUBMPOH, fiWF
ZFBSTMBUFSZPVDBOWFSJGZUIBUUIFEBUBZPVHFUCBDL
PVUJTUIFFYBDUTBNFEBUBZPVQVUJOy
IUUQTXXXZPVUVCFDPNXBUDI W9QO,)+"PLUTBOEIUUQTFO
XJLJQFEJBPSHXJLJ4)"%BUB@JOUFHSJUZ MBTUFEJUFE+BO
Working with Branches ◾ 95
Branch Naming
You can name branches anything you like. However, your
organization or the project you are currently working on,
96 ◾ Mastering Git
BRANCH WORKFLOWS
The core principle behind the feature branch workflow
is that the code development for one particular feature
should be conducted on a separate branch rather than the
main branch. This structure allows for multiple developers
to be able to work on feature, without having to disturb
the well-established main code. This, additionally ensures
that the main branch shall never contain broken or bad
code, which is a great advantage for the environments built
for the sake of carrying out continuous integration. The
encapsulation of feature development also allows for the
developers to leverage pull requests, and allows for the ini-
tiation of discussions and deliberations around particular
branch developments. They also allow the developers the
ability to sign off from a feature before it gets integrated
with the rest of the project. Additionally, if you find your-
self stuck while working on a particular feature, you have
the facility of opening a pull request to ask your colleagues
for feedback as well as suggestions. The pull requests basi-
cally make it remarkably easy for the team members to
provide comments on each other’s work, fostering a spirit
of cooperation as well as collaboration.
The Git Feature Branch Workflow then is a composable
workflow that can also be leveraged by the other high-level
Git workflows. It is branching model-focused, making it
an important inspiration for the creation as well as the
100 ◾ Mastering Git
How It Works
The Git Feature Branch Workflow assumes the presence
of a central repository, with “main” representing the offi-
cial history of the project at hand. Instead of making their
commits directly on the local main branch, the developers
have to create a new branch every time they must begin
work on a new feature. Feature branches must ideally be
given descriptive names like “Bug-Fix-603”. The chief idea
is to render a clear and focused purpose to every branch.
Git has not established any technical distinctions between
the main branch and the feature branches, so the develop-
ers should be able to easily edit, stage, as well as commit
changes to a feature branch.
Additionally, you can and should push your feature
branches to the central repository. This will make it pos-
sible for you to be able to share a feature with your devel-
opment team members without tampering with the official
code in any manner whatsoever. Since the main happens
to be the only “special” branch, storing multiple feature
branches on your central repository should hopefully not
pose any problems. It also happens to be an easy and con-
venient method of ensuring a backup for the local commits
of all the developers working on the team. Let us now go
through the lifecycle of a feature branch:
Working with Branches ◾ 101
Subsequent Tasks
Update, add, commit, and follow it up with pushing the
changes. On your branch, make the edits, stage, as well as
commit those changes in the regular fashion, developing
your feature with as many commits as you deem neces-
sary. When done, push your commits, updating your fea-
ture branch to Bitbucket, which is a Git-based source code
repository hosting service that was launched in 2008.
Resolve Feedback
Teammates can comment, provide feedback, and eventu-
ally approve of the pushed commits. You must resolve the
comments locally, commit, and then push the suggested
changes to Bitbucket. Your updates should appear in the
pull request.
Pull Requests
Apart from separating the feature development, branches
allow the developers to discuss changes through pull
requests. Once you have completed your work on a feature,
you do not have to immediately merge it into the main.
Working with Branches ◾ 103
Instead, you need to push the feature branch into the cen-
tral server, and file a pull request that asks to merge their
additions into the main. This will give the other developers
an opportunity to review your work before it becomes part
of the primary codebase.
Code review is considered to be a significant advan-
tage of pull requests, but its design is actually supposed to
facilitate a general way to talk and discuss about the code
at hand. So pull requests can be understood as discussions
pertaining to a specific branch. So, they can also be uti-
lized quite early in the development process. For example,
if you need help in the development of a particular feature,
all you need to do is file a pull request. The interested par-
ties, including hopefully your seniors, more experienced
programmers, etc. will be notified automatically, and they
should be able to see your question right next to the asso-
ciated commits. Once a pull request has been accepted,
the act of publishing the feature is pretty much the same
as it is in the Centralized Workflow. First, make sure that
you synchronize the local main with the upstream main.
Then, merge the feature branch into the main, and subse-
quently, push back the updated main to the central reposi-
tory. Pull requests should also be facilitated by product
repository management solutions like Bitbucket Server, or
Bitbucket Cloud.
Now, to better understand the workflow, let’s take an
example. Three coders A, B, and C, are working on a proj-
ect together. The project involves a code review of a new
feature pull request. Before developing the feature, A needs
a separate branch to work on. He can request for the new
branch through either checking out a branch based on
104 ◾ Mastering Git
You can also make use of git rebase during review and
merge stages to create and enforce a cohesive Git history of
your feature merges.
REMOTE BRANCHES
Remote references are the references or pointers in your
remote repositories, and include branches, tags, etc. You
should also be able to get a full list of the remote references
directly with the command “git ls-remote <remote>” or
even “git remote show <remote>” for the remote branches
as well as additional information. Nevertheless, the more
common way used is through taking advantage of the
remote-tracking branches.
Remote-tracking branches happen to be references to
the state of your remote branches. They are local refer-
ences that cannot be moved. Git moves them around for
Working with Branches ◾ 107
Pushing
When you have to share a branch with the other coders,
you must push it up to a remote that you have access to.
Working with Branches ◾ 109
Tracking Branches
To checkout a local branch from a remote-tracking branch
should automatically create what is known as a “tracking
110 ◾ Mastering Git
Pulling
While the git fetch command should fetch all the changes
on the server that you might not have yet, it shall not be
able to modify your working directory in any way what-
soever. It will simply acquire the data for you, and allow
you to merge it yourself. However, in most cases, post git
merge, a command called git pull, which is basically the
same as git fetch, is carried out. If you have a set up track-
ing branch, either through explicitly setting it, or via hav-
ing it created for yourself through the clone or checkout
commands, git pull should be able to look up what server
and branch are currently being tracked by your branch,
fetch from the said server, and then attempt to merge in
that remote branch. Generally speaking, it is better to use
fetch and merge commands directly and explicitly, as the
git pull can sometimes be confusing.
Working with
Servers
IN THIS CHAPTER
Small Setups
If you are a start-up, a small company, or are simply trying
out Git in your organizational space, with only a few devel-
opers, things should hopefully be fairly simple for you. One
of the most complex aspects of setting up a Git server tends
to be user management. If you need some repositories to be
read-only for certain users, and want read as well as write
116 ◾ Mastering Git
SSH Access
If you have a server setup, to which all your developers
already have the SSH access, it is usually the easiest to set
up your first repository there, since it requires almost no
work. If you want a more complex system of access control
type permissions on your repositories, you should be able
to handle them using the regular filesystem permissions of
the OS of your server.
If you need to place your repositories in a server that
does not have accounts for everyone on your team for
whom you wish to grant the write access and whatever
related permissions are needed, then you have to set up an
SSH access for them. We will assume that if you happen
to have a server with which this function can be achieved,
then you already have an SSH server installed, and that is
how you are accessing the server in the first place.
There are a few ways, with which you could give access
to everyone on your team. The first is to make sure that you
set up accounts for everybody, which is a fairly straight-
forward task, but can actually turn out to be a pretty cum-
bersome process. You might not want to run adduser (or
its alternative useradd), and then have to set temporary
passwords for every new user. Another method that can
be used is the creation of a single Git user account on your
machine, asking every user who will be having write access
to send you an SSH public key, and subsequently add that
key to a proper, specific file in the new Git account. This will
not be affecting your commit data in any way whatsoever,
Working with Servers ◾ 117
the SSH user you will be connecting as will not affect the
commits that have been recorded. Lastly, you can also try
having your SSH server authenticated from a Lightweight
Directory Access Protocol (LDAP) server or some other
legitimate, centralized authentication source that you
might already have set up. As long as every user is able to
get their shell access to the machine, any SSH authentica-
tion mechanism or methodology that you can come up
with should hopefully work and serve the purpose at hand.
SERVER SETUP
Let us now walk through the setup of the SSH access from
the server-side. This example will have us making use of
the authorized_keys method so that we are able to get our
users authenticated. We will also have to assume that we
are working on a standard Linux distribution like Ubuntu.
A significant amount of what has been described here can be
automated via the use of the ssh-copy-id command, instead
of having to manually copy or install the public keys.
First, you will have to create a Git user account as well as
a .ssh directory for that particular user. Next, you will have
to add the developer SSH public keys into the file autho-
rized_keys for the availability of the Git user. Let us pre-
sume that you happen to have access to some of the trusted
public keys, and have also saved them to temporary files.
You will now have to append them to the Git user’s file
authorized_keys located in the .ssh directory. Following
this, you should be able to set up an empty repository
by running the command git init along with the -- bare
option, which should be able to initialize your repository
without really needing a working directory. This should
118 ◾ Mastering Git
Distributed Workflow
Unlike the Centralized Version Control Systems (VCS), the
distributed system of Git allows us to be way more flexible
in how our coders and developers interact as well as collabo-
rate with each other on specific tasks that are essential for the
project. In the centralized system, every developer is consid-
ered to be a node working nearly equally with a central hub.
In Git, though, every developer is a potential node as well as
a hub; that is to say, every developer makes code contribu-
tions to other repositories, as well as helps in maintaining the
public repository from which others can base their work, and
to which they can contribute. This gives us a variety of work-
flow opportunities for our projects as well as our teams, so we
shall be delving into a few common paradigms which allow
us to take advantage of the flexibility the software renders us.
We will also be looking into the merits as well as the demer-
its of every single design; which should help you to choose
which one you deem the most suitable for your purposes, or
the features you could mix and match from each one.
Centralized Workflow
The centralized systems usually offer us a single kind of
collaboration model, the centralized workflow. The central
hub, or the repository, accepts the code, and everybody else
has to synchronize their work with it. Several developers
are nodes, i.e. the consumers of that hub, and are expected
to synchronize with that centralized location. This means
that if there are two developers both cloning from the
hub as well as making changes as they deem fit, the first
developer who will push their changes back will manage to
do so without facing any problem. The second developer,
Working with Servers ◾ 121
however, will have to merge the first one’s work before push-
ing the changes up, so that he does not overwrite the changes
incorporated by the first developer. This concept holds true
for Git, for Subversion, or for any other Centralized VCS,
and this model works perfectly well in Git, even though it is
not a Centralized VCS as such. If you happen to be used to
and comfortable with a centralized workflow in your orga-
nization or as part of your team, you should easily be able
to continue using that kind of a workflow, with the software
of Git. Just set up a single repository, and give push access to
all the members of your team; Git will make sure that your
users are unable to overwrite each other.
Let’s take an example to understand this concept better.
Two developers, A and B, started working on a project at the
same time. A was able to finish his changes first, and subse-
quently pushed them to the server. This was followed by B
trying to push her changes, but the server ended up reject-
ing them. B is informed that she is trying to push the non-
fast-forward changes, so she will not be able to do so until
she completes her fetches, and follows it up by merging.
Many developers find this kind of a workflow very attrac-
tive, because it happens to be a paradigm that many seem
to be familiar and comfortable with. Additionally, this kind
of workflow is not merely limited to small teams. Through
Git’s branching model, it should be possible for hundreds
of developers to be able to successfully work on one project
via the use of dozens of branches simultaneously.
Integrator-Manager Workflow
Since Git allows you to have several remote repositories, it
is also possible to have a kind of a workflow where each and
122 ◾ Mastering Git
Contributing to Projects
It is difficult to wax eloquent on how you could be able to
contribute to a particular project, since there are numer-
ous variations on how one could go about achieving their
objectives. Since Git is highly flexible, people tend to work
together in a variety of ways, and it can be highly prob-
lematic to opine upon how one should contribute, since
every project is a bit different. Some of the variables that
are involved in project development are the active con-
tributor count, commit access, chosen workflow, as well as
the external contribution method. Let’s delve into each of
these factors for our better understanding.
Working with Servers ◾ 125
Commit Guidelines
First and foremost, a quick note about commit messages: if
you have a good guideline for creating commits, then stick
to it, as it makes working with Git as well as collaborating
with other developers a significantly better experience. The
Git project also provides a document laying down a num-
ber of effective tips for creating commits from which you
could send out patches.
First and foremost, your submissions must not contain
any whitespace errors. Git gives you a fairly easy way to
check for this issue. Before you commit, you will have to run
the command git diff --check, which will be able to identify
the possible whitespace errors and list them out for you as
well. If you will run this command before doing your com-
mits, you will be able to tell if there are whitespace issues in
your code that are bound to annoy your fellow developers.
Next, you should try to make each commit a logi-
cally separated changeset. Additionally, try to make your
changes brief as well as digestible. Do not code for a couple
of days on five separate issues, and then submit it all as one
huge commit. Even if you do not wish to commit imme-
diately, make sure that you utilize the staging area mean-
ingfully, splitting your work into at least one commit per
issue, with every commit made accompanied by a useful
Working with Servers ◾ 127
GitHub
IN THIS CHAPTER
➢ What is GitHub
➢ History of GitHub
➢ How to use GitHub
➢ Different types of Accounts
WHAT IS GITHUB?
• Protected Branches.
• Ability to draft pull requests.
GitHub ◾ 133
• Premium Support.
• Token, secret, as well as code scanning.
SSH Access
As of now, you can absolutely connect with the Git
repositories, using the https://protocol. You will have to
authenticate with your username and password that you
just used for the setup process. However, in order to sim-
ply clone public projects, you will not even have to sign
up, the account comes into play only if we want to fork
projects or push toward our forks. If you want to use the
Secure Shell (SSH) Remotes, you might need to configure
a public key. If you happen to not have one, you might
want to get it generated. The process to get this done is
similar across all Operating Systems. First, make sure
that you already do not have one. Usually, by default, a
user’s SSH keys are stored in that user’s ~/ .ssh directory.
You should also be able to see if you have a key already
by going to that directory and asking for its contents to
be listed. If you do not find your private key, as well as
an associated public key, or if you do not even have a. ssh
directory, you should be able to create them by running
a program known as ssh-keygen, provided by the SSH
package on Linux/macOS systems and coming with Git
for the Windows.
GitHub ◾ 135
Your Avatar
Next, if you wish to do so, you should replace the avatar that
has been generated for you with an image of your choice.
First, go to the tab “Profile” (it is located above the SSH keys
tab) and press on “Upload new picture”. Crop the image as
you deem fit, and click on the button “Set new profile pic-
ture”. Now, wherever you will interact on the site, people
will be able to see your avatar as well as your username. If
you had earlier uploaded an avatar to the highly popular
Gravatar service (usually used for WordPress accounts),
that avatar shall be used by default, and you will not have
to perform this step at all.
Email Addresses
Your email address is of particular importance on GitHub.
This is because GitHub maps your Git commits to your
user through the use of your email ID. If you happen to
use multiple email addresses while doing your commits
and you want to ensure that GitHub links them up prop-
erly, you will have to add all the email addresses you have
136 ◾ Mastering Git
Two-Factor Authentication
Lastly, for additional security, you should certainly set up
your Two-Factor Authentication (2FA). 2FA is a kind of an
authentication mechanism that has been becoming more
and more popular recently in order to mitigate the risk of
your account becoming compromised if your password is
somehow stolen. Turn it on and GitHub will ask you for
two separate methods of authentication, so that if one of
them happens to get compromised, some attacker will not
be able to gain access to your account.
You should be able to find the 2FA set-up under the
“Security” Tab of your account settings. First, click on the
“Set up two-factor authentication” button. This should
be able to take you to a configuration page where you
should choose to use a phone app in order to generate your
GitHub ◾ 137
HISTORY OF GITHUB
The development of GitHub.com platform started on
October 19, 2007. The official website was launched in the
April 2008 by Chris Wanstrath, Tom Preseten-Werner, P.J.
Hyett, as well as Scott Chacon after it had been available
for a few months as a beta release. GitHub, Inc. was ini-
tially supposed to be a flat organization, with no middle
managers whatsoever. The company adopted the prin-
ciple of self-management, wherein every worker had to
play a part of the manager for her/himself. Additionally,
GitHub’s employees could choose to work on the projects
that they were interested in (open allocation), even though
the salaries were determined by the chief executive. In 2014
eventually, the organization introduced a layer of middle-
management for better efficiency in handling its affairs.
GitHub started out as a bootstrapped start-up business,
which in its early years managed to generate sufficient rev-
enue in order to be funded solely by the three co-founders,
who were also able to take on employees. Four years after
the company began, Andreessen Horowitz gave it an
investment of hundred million dollars in venture capital.
138 ◾ Mastering Git
Acquired by Microsoft
From 2012 onward, Microsoft became a crucial customer
as well as a significant user of GitHub, utilizing its services
to be able to host open-source projects as well as devel-
opment tools like Chakra Core, .NET Core, PowerShell,
MS Build, Visual Studio Code, Power Toys, Windows
Terminal, Windows Calculator, as well as a bulk of its
product documentation (now found on Microsoft Docs).
On June 4, 2018, Microsoft expressed its intent to acquire
140 ◾ Mastering Git
GitHub for $7.5 billion. The deal was closed on October 26,
2018. GitHub, nevertheless, still continues to operate inde-
pendently as a platform, community, as well as a business.
Under Microsoft, the service came under the leadership
of Xamarin’s Nat Friedman, reporting to the Executive
Vice-President of Microsoft Cloud & AI, Scott Guthrie.
The GitHub CEO Chris Wanstrath was kept as a “technical
fellow,” with him reporting to Guthrie as well. However,
this acquisition too had its fair share of controversies.
Developers like Kyle Simpson, author as well as JavaScript
trainer, and Rafael Laguna, CEO, Open-Xchange (a web-
oriented communication, collaboration, as well as office
productivity software suite) expressed their concerns and
uneasiness over Microsoft’s purchase, citing Microsoft’s
handling, or mishandling of previous purchases, like
Nokia’s mobile business, Skype, etc.
This acquisition was in line with the business strategy
of the corporation under CEO Satya Nadella, which saw a
greater emphasis being put on the cloud computing services,
as well as the contributions to and the development of open-
source software. In 2016, Microsoft was on the top of the
list of ten different organizations with the most open-source
contributors on GitHub. Harvard Business Review asserted
that Microsoft intending to acquire GitHub was merely to
get access to its user base, which it could use as a loss leader,
in order to encourage the use of its other development ser-
vices and products. The concerns expressed over GitHub’s
sale seemed to benefit its competitors, at least for a while.
GitLab, a commercial open-source software that runs a
hosted service version control system, Bitbucket (owned by
Atlassian), as well as SourceForge (owned by BizX) reported
GitHub ◾ 141
Mascot
GitHub’s mascot is an “octocat,” an anthropomorphized
creature with five octopus-like arms. This character was
the brainchild of graphic designer Simon Oxley as clip
art that he intended to sell on iStock, an online royalty-
free, international microstock photography provider based
in Canada. GitHub was interested in Oxley’s work after
Twitter chose a bird that he designed for their own logo.
The illustration that GitHub eventually chose was a char-
acter that Oxley had named “Octopuss”. Since GitHub
wanted Octopuss as their logo (a use that the iStock license
does not permit), they negotiated with Oxley in order to
be able to buy the exclusive rights of the image. GitHub
rechristened Octopuss to Octocat, and trademarked the
character along with this new name. Later, GitHub hired
an illustrator named Cameron McEfee to adapt Octocat
for different purposes on the website as well as the promo-
tional materials; McEfee and various other GitHub users
have since created hundreds and hundreds of variations of
the character, which are available on the GitHub Octodex.
142 ◾ Mastering Git
Create Branches
Branches will help you in working on multiple versions
of a repository at a particular time. You might want to
add a new feature (still in the development phase), but are
unsure if whether making changes to the main codeline
will be worth it. Git Branching to the rescue! Branches
should allow you to move back and forth between dif-
ferent versions of your project. In the aforementioned
scenario, you will be well-advised to fork out a branch
and test the new feature without any adverse effects on
the main branch. Once your changes are tried, tested,
and approved, you can merge the changes from the
new branch to the main branch. Here, the main branch
refers to the master branch, present in your repository
by default.
146 ◾ Mastering Git
Making Commits
Committing will save changes to your file. A commit
should ideally be accompanied by a message justifying and
explaining the changes that have been made. The commit
message is not compulsory, yet is strongly recommended
by nearly all organizations, for purposes of differentiation,
and helping the collaborators understand the history of a
file as well as the changes made. In order to make your first
commit on GitHub, follow the given steps in a chronologi-
cal order:
Pull Command
Pull command is one of the most important commands in
GitHub. It will inform you regarding the changes made to
a file, request your fellow contributors to view it, and merge
it with the master branch as well. Once a commit has been
made, anyone should be able to pull the file, and initiate a
discussion on the change/s. Once the iteration process is
complete, the file/s can be merged. If there are any con-
flicts between the different changesets, they will have to
be resolved in order to complete the merge. Now, let us go
through the various steps involved in order to conduct a
pull request on GitHub:
Merge Command
Through the use of the Merge command, we merge the
changes made into the master branch. To use the Merge
command on GitHub, follow these steps in a chronological
order:
After you click on Fork, it will take some time for the soft-
ware to give you your own local version of the public repos-
itory. Once done, you will be able to notice the name of that
particular repository under your account. Congratulations!
You have successfully managed to fork out an existing
repository under your own account on GitHub.
Organization Accounts
Organization Accounts are defined as shared accounts
where large groups of people are able to collaborate across
multiple projects at the same time. Administrators or the
owners tend to manage the access of various members to
an organization’s data as well as projects through a host
of administrative features as well as robust, sophisticated
security. Various features that you will be able to find in
Organization accounts are:
Enterprise Accounts
Through enterprise accounts, you should be able to man-
age billing as well as policy for multiple GitHub.com orga-
nizations at the same time. Enterprise accounts are usually
available with GitHub Enterprise Cloud as well as GitHub
Enterprise Server.
With this, we have come to the end of this chapter on
GitHub. In this chapter, we talked about what GitHub is,
152 ◾ Mastering Git
GitLab
IN THIS CHAPTER
➢ What is GitLab
➢ History of GitLab
➢ How to use GitLab
➢ Free and Enterprise accounts
In the previous chapter, we focused our mental faculties
on GitHub, what it was, its history, how to use it, different
kinds of accounts it offers, etc. With this chapter, we move
on to GitLab, keeping our concerns in similar directions.
So, let’s begin.
WHAT IS GITLAB
GitLab is a web-oriented DevOps tool that should be able
to provide you with a Git repository manager and features
pertaining to continuous integration and deployment,
DOI: 10.1201/9781003229100-7 153
154 ◾ Mastering Git
HISTORY OF GITLAB
In 2011, Dmitriy Zaporozhets was in need of a good tool
in order to be able to collaborate with his team. He was in
want of something that was efficient as well as enjoyable so
he could actually focus on and enjoy his work, rather than
getting caught up in the tools themselves. GitLab was cre-
ated by Zaporozhets from his house in Ukraine, a home
without running water. The GitLab official website claims
156 ◾ Mastering Git
Prerequisites
To be able to use SSH for your communication with GitLab,
you will need the following:
ssh-keygen -p -f/path/to/ssh_key
ssh-keygen -o -f ~/.ssh/id_rsa
ssh -T [email protected]
This command will not use the SSH Agent and will also
require Git 2.10 or later.
You can then use the git clone command to clone your
repositories, and ensure to update a previously-cloned
repository that will be aliased as an origin. Keep in mind
that private as well as public keys contain sensitive data.
You have to ensure that the permissions on the files make
them readable to you, and yet not accessible to others.
Creating a Project
In order to create a new project in GitLab, follow the given
steps:
Creating a Group
In order to create a group, follow the provided steps:
• On the top bar, select Menu > Groups, and on the right,
select “Create Group”. From the left side of the search
box, select the plus sign and then, click on “New Group”.
GitLab ◾ 173
changes, you are allowed to merge them into the rest of the
codebase using a merge request.
Creating Forks
A fork is a clone of an original repository that coders are
supposed to put in another namespace where they can
experiment as well as apply changes that might or might
not be shared later, without affecting the main project. In
order to create a fork on an existing project in GitLab:
GitLab creates your fork for you, and then redirects you
to the project page for you to find it. The permissions that
you have in the namespace will also be your permissions in
the fork. If a public project with a repository feature set of
the option “Members Only” is forked, the repository in the
fork is public. The owner of that fork shall have to manually
change its visibility.
From an Issue
You can create a new branch from an issue, a feature
introduced from GitLab 8.6 onward. If your develop-
ment workflow ends up requiring an issue for every
merge request that it has to make, you will have to cre-
ate a branch directly from the issue in order to speed up
the process. The new branch, and subsequently its merge
request, will be marked as related to the issue at hand.
After merging, the merge request will close the issue. You
should be able to see a Create merge request dropdown
below the location of the issue description. The Create
merge request button will not be displayed in one of the
following cases:
After the branch has been created, you should be able to edit
files in the repository so that you can fix this issue. When you
create a merge request based on the newly-created branch, the
description field will display the issue closing pattern Closes
#ID wherein “ID” is said to be the ID of the given issue. The
issue will be closed after the merge request gets accepted.
git add.
git commit -m "My commit message"
By Sending an Email
A brief caveat: the standard format of the generated email
address was changed from GitLab 11.7 onward. The earlier
format is still being supported so the existing aliases as well
as contacts will still be able to work. Now, coming to the
main point, you should be able to create a merge request by
sending out an email to GitLab. The merge request-target
branch is always the project’s default branch.
What needs to be ensured:
Project Templates
Project Templates are important since they are able to pre-
populate a new project with all the necessary files that you
shall need to get started quickly. There are two different
kinds of project templates:
Enterprise Templates
GitLab is also developing Enterprise templates in order to
help you streamline your audit management with a few
selected regulatory standards. These templates should
be able to automatically import the issues that will cor-
respond to each regulatory requirement. To create a new
project with an Enterprise template, follow these steps on
the New project page:
Star a Project
Starring a project will make it easier for you to find it among
other projects that you frequently use as well. The number
GitLab ◾ 191
• Go to Settings>General.
• Expand upon the Advanced section.
• Scroll down to the delete project section.
• Click on Delete project.
• Confirm the action by typing out the expected text.
192 ◾ Mastering Git
• Go to Settings>General.
• Make sure that you expand the Permissions, LFS, as
well as 2FA section.
• Check the option “Enable Delayed Project Removal”.
• This is optional. In order to prevent the subgroups
from being able to change the settings, select the
option “Enforce for all subgroups”.
• Click on “Save Changes”.
GitLab ◾ 193
Bitbucket
IN THIS CHAPTER
➢ What is Bitbucket
➢ History of Bitbucket
➢ How to use Bitbucket
➢ Free and Enterprise accounts
In the previous chapter, we learned about GitLab, what it is,
its history, functionality, and commands, the accounts it
offers, etc. Now, we move on to Bitbucket, with a similar set
of concerns in mind. So, let us proceed.
WHAT IS BITBUCKET
Bitbucket is a Git-based source code repository hosting ser-
vice that happens to be owned by Atlassian Corporation Plc.
(Programmable Logic Controller), an Australian software
company which develops products for project managers,
DOI: 10.1201/9781003229100-8 197
198 ◾ Mastering Git
Services
Bitbucket Cloud
Bitbucket Cloud (earlier known as just Bitbucket) is written
in Python and utilizes Django, a web framework following
the model-template-views, i.e. the MTV architectural pat-
tern. Mostly, Bitbucket is only used for code as well as code
reviews. The service provides a plethora of features like:
Steps:
Branch Permissions
For Bitbucket, branch permissions should help you to
enforce specific workflows as well as prevent errors like a
workspace member managing to delete the master branch.
With proper branch permissions, you should be able to:
• Dependent Merges
• These will ensure that users are only able to merge
changes with the passing builds.
• Select a particular number of successful builds
before actually conducting the merge.
• Can be used with Bitbucket Pipelines, a build tool
integration or the commit status REST API.
• Code Review Completion
• It ties your merges to the code reviews.
• Allows your colleagues to work collaboratively
with the aid of pull requests at their disposal.
• Keep your workflow consistent so that the devel-
opers always know what they need to do in order
to conduct the merge.
• Task Completion
• You will be able to create tasks on pull requests
in order to mark out the changes that have to be
made.
• Management of a pull request as it is progressing
toward approval.
• Make sure that all the tasks in a pull request are
completed before the final merge is conducted.
Bitbucket ◾ 207
Setting Result
Check for at least {#number} Users will get a notification
approvals if/when their pull requests do
not have the prescribed
number of approvals.
Check for the unresolved pull Users should get a notification
request tasks whenever they have pull
request tasks that are yet to be
finished.
Check for {#} passed builds in the Users shall get a notification if
last commit and when they do not have the
prescribed number of
successful builds in their most
recent commit.
Automatically merge a pull request The admin should enable this
when all the checks are passed feature so that so that a queued
up merge will be triggered
automatically once all the merge
checks have been successfully
passed.
208 ◾ Mastering Git
Setting Result
Enforce all the merge checks to Here, users will not be able to
ensure that every pull request conduct the merge as long as their
has been completely vetted pull requests continue to have
before the merge takes place unresolved merge checks. They
will get to see a checklist of all the
issues that they need to resolve via
their codes before it might be
allowed for the merge to be
executed.
Reset the approvals when your If any changes are made to the
source branch has been source branch of the pull request,
modified the pull request will be making
automatic updates without seeking
any kind of approval, and the
reviewers shall subsequently have
to review as well as approve of the
pull request again.
during the creation, you can always go back to the pull request
and edit it to add them later on. After you have created the
pull request as well as added the reviewers, you should ideally
wait to receive their approvals. However, the iterations and
the deliberations will soon begin as the reviewers will start
looking through your code as well as making comments. You
will also be receiving the email notifications of the ongoing
discussions, where you must participate, keeping your point
across with clarity as well as precision, thus becoming an
active contributor in the code review process.
• Find the SHA for the commit at the tip of the branch
you deleted using the git reflog command.
• Now, to restore the branch, use ‘git checkout -b
<branch> <sha>.
Bitbucket Server
Bitbucket Server (earlier known as Stash) is a combina-
tion of web interface product as well as a Git server that
is written in Java, a class-based, high-level, object-oriented
programming language designed so that it has as less
implementation dependencies as possible, and built with
Apache Maven, a built-automation tool that is mostly used
for Java projects. Bitbucket Server allows its users to be able
to do basic Git operations (like merging code or reviewing,
similar to GitHub) while also being able to control the read
as well as the write access to code. It also allows for integra-
tion with other products of Atlassian. Bitbucket Server is
also a commercial software product that can be licensed for
214 ◾ Mastering Git
HISTORY
Bitbucket, earlier, was an independent startup company
that was founded by Jesper Nøhr in 2008. On September 29,
2010, Bitbucket got acquired by Atlassian. Bitbucket was
then popularly known as a Mercurial Project Hosting site.
Mercurial, referenced earlier in this book, is a distributed
revision control tool meant to be used by software devel-
opers that was released in 2005. The product development
and software company Atlassian had already made it clear
that it would be investing heavily in the enterprise space.
Neither of the parties ended up disclosing the terms and
conditions of the deal. Bitbucket then used to play host to
over 60,000 accounts and was the premier code collabora-
tion provider for the distributed VCS offered by Mercurial
as well as a general services provider for the developers who
wished to share as well as encourage collaboration in their
projects. Bitbucket was understood as being quite similar
to GitHub as well as Google Code, and was also hosting the
codes of many incredible open-source projects like Adium,
Opera, MailChimp, etc. Bitbucket was incorporated into
Atlassian’s family of an extensive range of development
products and software collaboration tools that were help-
ing various teams to conceive, plan, develop, as well as
Bitbucket ◾ 215
Free
t *UJTGSFFPGDPTUGPSVQUo fiWFVTFST
t *UQSPWJEFTCVJMENJOVUFTQFSNPOUIB OEIBT
UIF-'4PG(#JOBMM
t *UEPFTOPUQSPWJEF0WFSBHFQSPUFDUJPO
Standard
Premium
Overage Protection
The standard as well as the premium plans includes over-
age protection for your build minutes as well as a LFS for all
users belonging to the workspace. However, if you happen
to go over your build minutes, Bitbucket will automatically
add more minutes in your current month. But when the
next billing cycle starts, the build minute usage will reset,
and you will not be billed the additional charge (unless you
have gone over the limit again). Similarly, if you go beyond
the limit of the LFS, Bitbucket will again automatically add
218 ◾ Mastering Git
In the case of the free plan with extra minutes as well as stor-
age, under the section “Free plan”, depending on your plan,
you will see the options “Get more minutes and storage” or
“Only pay for extra storage and minutes”. Click on these
options, if you need extra minutes as well as storage along with
the Free plan. If you are paying for extra storage as well as min-
utes alongside the Free plan and now wish to stop, you will be
able to see an option “Stop paying for storage and minutes”.
Once you are done, your payment information is
recorded and now, you should be able to see your new plan
in the Plan Details page. Your credit card will be billed
monthly as per the plan that you have chosen as well as the
number of users on your account. If you happen to miss a
payment, you get downgraded to a Free plan with a five-
user limit. If you used to have the premium plan, you will
now lose any saved Premium settings.
XIJDISFQPTJUPSJFTUIFZIBWFBDDFTTUPBTXFMMBTUIF
HSPVQT UIBU UIFZ BSF B QBSU PG $MJDL PO UIF JDPO PG
i9wUPSFNPWFUIFVTFSTGSPNUIJTMJTU XIJDITIPVME
BMTPCFBCMFUPSFNPWFUIFNGSPNUIPTFSFQPTJUPSJFT
BTXFMMBTHSPVQT
"EEJUJPOBMMZ UIFSFBSFUISFFEFQMPZNFOUPQUJPOTUIBUBSF
BWBJMBCMF BTGBSBTUIFDBTFPG#JUCVDLFUJTDPODFSOFE. ThFZBSF
t #JUCVDLFU$ MPVE*UJTIPTUFEPO"UMBTTJBOTTFSWFST
BOEB DDFTTFEU ISPVHIU IFV TFP GB6 3-# JUCVDLFU
$MPVEQSPWJEFTJUTVTFSTXJUI1JQFMJOFT BOFYDMVTJWFBT
XFMMBTBCVJMUJODPOUJOVPVTJOUFHSBUJPOUPPM FOBCMJOH
ZPVU PC VJME U FTU B TX FMMB TE FQMPZG SPNE JSFDUMZ
XJUIJOZPVS#JUCVDLFU)PXFWFS UIFSFBSFBMTPTPNF
SFTUSJDUFEGVODUJPOTJOUIF"UMBTTJBO$MPVE"QQT
t #JUCVDLFU4FSWFS*UJTIPTUFEPOMPDBUJPOBOEXJUIJO
ZPVSF OWJSPONFOU# JUCVDLFU4 FSWFSX JMMO PUD PNF
XJUIBC VJMUJOU FTUJOHP SE FQMPZNFOUU PPM C VUJ U
EPFTUFOEUPIBWFBTUSPOHTZTUFNPGJOUFHSBUJPOXJUI
#BNCPP UIFQPQVMBSDPOUJOVPVTJOUFHSBUJPOBTXFMM
BTD POUJOVPVTE FMJWFSZU PPMU IBUT IPVMEC FB CMFU P
BMMPXZ PVU PD PNQMFUFMZB VUPNBUFZ PVSC VJMEQ SP
DFTTFT:PVXJMMBMTPIBWFNPSFBQQTBUZPVSEJTQPTBM
UIBO$MPVE BOEUIFJSMJDFOTJOHXJMMCFQFSNBOFOU
t #JUCVDLFU%BUB$FOUFS The&OUFSQSJTFPЋFSJOHGSPN
#JUCVDLFU SFTFNCMFT B TJOHMF JOTUBODF PG #JUCVDLFU
4FSWFSGPSJUTVTFST FWFOUIPVHIJUJTIPTUFEPOBTJH
OJfiDBOUOVNCFSPGTFSWFSTXJUIJOBDMVTUFSPGZPVSPXO
FOWJSPONFOU. ThJTMFBETUPTJHOJfiDBOUBEWBOUBHFTMJLF
222 ◾ Mastering Git
A B
Accounts, 149 Bare and cloned repositories, 46
enterprise, 151–152 Bare Git, 7
organization, 150–151 Bare repos, 8
personal user, 149–150 Bare Repositories, 46, 58
Advantages of Git, 15 Bash Command Piping, 49
for budget management, 19 Benevolent dictator, 123
for customer support, 19 Bitbucket, 16, 31, 101, 140, 197
for designing, 18 branch permissions,
for development, 16–17 204–205
for HR, 19 changing your plan, 218–219
for marketing, 17 deleted branch, restoring,
for product management, 212–213
17–18 granting repository access
Aliases, Git, 72–80 to users and groups,
Alibaba Group, 158 201–203
Andreessen Horowitz, 137, 138, history, 214–215
139 overage protection, 217–218
Annotated tags, 81, 82 Premium Merge Checks, 205
Apache Maven, 213 pricing plan, 216
Apache Netbeans, 43 premium, 217–222
Append-only object database, 13 standard, 216–217
Apple, 37 pull requests, 210
Atlassian Corporation Plc., 197 authors, 210–211
August Capital, 158 process, 210
Autocorrection, 47–48 reviewers, 211–212
231
232 ◾ Index
GitHub, 3, 11, 23, 30, 31, 33, 39, how to create a branch,
63, 122, 129, 130 174–178
accounts, 149 merge requests, creating, 177
enterprise accounts, adding attachments when
151–152 creating merge request
organization accounts, by email, 183–184
150–151 from an issue, 178–179
personal user accounts, by sending an email,
149–150 182–183
account set up and setting the default target
configuration, 131–134 project, 184
email addresses, 135–136 when you create a branch,
history of, 137 180
acquired by Microsoft, when you have to add,
139–141 edit, or upload a file,
mascot, 141–143 179–180
how to use GitHub, 144 when you have to work in
cloning and forking a fork, 181–182
GitHub repository, when you use git
148–149 commands locally,
create branches, 145–146 180–181
creating a repository on new issue, creating, 177
GitHub, 144–145 pricing plan, 195–196
making commits, 146–147 projects, working with, 184
merge command, 148 custom project templates,
pull command, 147 188–190
replacing avatar, 135 enterprise templates,
Secure Shell (SSH) access, 187–188
134–135 group push rules, 194
Two-Factor Authentication IP restriction, 194–195
(2FA), 136–137 project templates, 186–187
GitHub Desktop, 36 star a project, 190–193
GitHub Octodex, 141 repository, adding files to,
GitLab, 31, 122, 140, 153 176–177
creating a group, 172–173 reserved project and group
creating a project, 172 names, 173–174
feature branch workflow, 175 and SSH keys, 161
forks, creating, 175–176 adding SSH key to GitLab
history of, 155–161 account, 166
Index ◾ 235
M O
Mac, installing Git on, 35–36, 37 Octopuss, 141
Marketing, Git for, 17 OpenID Foundation, 198
Mascot, 141–143 Organization accounts, 150–151
Index ◾ 237
P inspecting, 71
pushing to, 70
Packard, Keith, 32–33
removing, 72
Packfile, 13
renaming, 72
Pearce, Shawn, 30
showing, 68
Personal user accounts, 149–150
Repo optimization, 48
Pre-push cleaning, 54–55
Repositories in Git, 57, 58–60
Preseten-Werner, Tom, 137, 138
aliases, 72–80
Product management, Git for,
recording changes to repos,
17–18
60–66
Project templates, 186–187
remotes, 67
Pull command, 224
adding remote
Pull requests, 102–106, 210
repositories, 68–70
authors, 210–211
inspecting, 71
merging, 102
pushing to, 70
process, 210
removing, 72
reviewers, 211–212
renaming, 72
Push and Pull features, 12
showing, 68
PuTTY, 38
tags, 80
PuttyGen, 169
annotated, 82
check out, 84–85
R creating, 81
deleting, 83–84
RCS, see Revision Control
lightweight, 82
System
listing, 80–81
README file, 145
retagging/replacing old
ReadWriteWeb, 138
tags, 85–86
Rebasing, 51–52
sharing, 83
Redoing changes, 12
tagging later, 82–83
Remote branches, 106
Representational State Transfer
creation of, 92
(REST) Application
deleting, 111–112
Programming Interface
pulling, 111
(APIs), 200
pushing, 108–109
Reverting changes, 46–47
tracking branches,
Revision Control System (RCS),
109–111
4, 94
Remotes, 67
Role-based code, 18
adding remote repositories,
Ruby, 138
68–70
238 ◾ Index