forked from sergutsan/groovyck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.tex
More file actions
905 lines (758 loc) · 36.9 KB
/
Copy pathgit.tex
File metadata and controls
905 lines (758 loc) · 36.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
%TODO: stress the point of initialising a REPO, not just I: or H:
\section{Version control}
\label{sec:version-control}
What is version control? It is something as simple (and as difficult
to make right) as keeping track of changes in some piece of work, over
time. You
are probably familar with some very rudimentary version of version
control. Have you ever listed the documents in a folder and seen
something similar to this?
\begin{itemize}
\item myDocument
\item myDocument-2
\item myDocument-3
\item myDocument-final
\item myDocument-final2
\item myDocument-final-final
\item myDocument-definitive
\item myDocument-defitive-USE-THIS-ONE
\end{itemize}
If so, you already understand the most important idea behind version
control: our work is never created in one go, it changes over time and
sometimes we want to make sure we can go back in time to a former
version of it\ldots just in case.
Many modern programs have version control embedded into them,
e.g. word processors like Microsoft Word, OpenOffice Write, or Google
Docs (also known as Google Drive). Very often they just track the
changes made to the document, sometimes they allow the user to go back
and forth in time to review, accept, or discard changes. This is also
very common in wiki sites like the Wikipedia.
% TODO: add a screenshot of the version control in wikipedia here.
Version control systems were initially created to track changes in
\emph{source code}. They were created by programmers for
programmers. We have come a long way since those days, and now version
control is spread over many different applications, but they still
pursue the same two goals:
\begin{description}
\item[Reversibility: ] the capacity of going back in time if you mess
up and introduce bugs in your code (sorry, I meant \emph{when} you
introduce bugs in your code).
\item[Concurrency: ] the capacity of working together with other
people on the same project, on the same file, at the same time.
\end{description}
These two capacities are basic for any modern programmer, and that is
why version control is (or should be) part of every programmer's daily
life. Modern programs are big and complex, and several programmers
work on them. Without appropriate version control, they cannot work at
the same time: they need to take turns, pass the baton\ldots this is
really unproductive, good programmers do not work like
that. Additionally, programmers ---even good programmers, as long as
they are human--- make mistakes all the time, sometimes serious
mistakes that break their programs completely, and they need to go
back in time to the point where everything was working fine and start
again (in large and complicated programs, this may mean a long time).
In this chapter we will learn to make version control on your source
code files \emph{right}, not as shown above (e.g. myProgramOLD.jdc,
etc). We will use a program for doing so called \emph{Git}.
\section{Git}
\label{sec:git}
There are many programs for performing source code version control
nowadays. For this course, we are using Git, a version control system
created by Linus Torvalds, the same guy that created Linux. It is not
difficult to use but it is very powerful.
Other very common version control systems are Subversion (also known
as svn) and Mercurial. There are many more. There are many sources
online, starting with Wikipedia, that will tell you the history of
version control, the differences between different systems, and much
more. I encourage you to go and read about it if you think the topic
is fascinating. If you just want to learn to use Git normally in
your life as a programmer, this section will help you learn the
basics.
As you can imagine, a full book could be written about all the
possibilities and options that come with Git ---actually, several ones
have been published already. In this section I will just present the
most important 10\% of Git, which is all
you will need 90\% of the time.
\subsection{Starting a new project}
\label{sec:starting-new-project}
Let's start by creating a new programming project. There are two ways
of doing this, locally and using an online repository manager. As the
latter is simpler from the point of view of sharing your code (more on
that later), we will explain that option here.
We will use GitHub (www.github.com),
one of the most well-knowned online repository
managers\footnote{There are many others: BitBucket, Google Code\ldots
the list is endless.}.
It is also costless to use, which is a big plus.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{gfx/gitHubScreenshot.eps}
\caption{Screenshot of GitHub. You can see the name of the user
(``bbk-msccs''), the name of the repository
(``currency-exchanger''), and the URL.
% You can use the URL both to
% clone the reposity and to push your changes (as long as this
% repository is yours, i.e. you can \emph{write} on it).
}
\label{fig:github}
\end{figure}
Creating an account on GitHub is easy and free. Click on the ``Create
a repo'' button, choose a name and a description, and you are ready to
go. It could not be easier.
Now that you now how to create repositories, we will learn how use
them to keep track of the evolution of your source code. For the
purposes of the following discussion, I will assume that you have an
account at GitHub and that your account name is ``ilovegit''. In some
cases I will need a sample repository to explain some of the features;
unless the text says otherwise, I will assume that you have created a
repository in GitHub called ``my-currency-exchange'' and the examples
will refer to this repository created by ``ilovegit''.
% REMOVED - FOR EXTRA INFO
% Create a new folder
% where you will put your programs. Now we want to start keeping track
% of all changes. Assuming Git is installed in your system, and that you
% are on the right folder, you only need to type \verb+git init+. With
% this simple command, you have told Git to \emph{be ready} to keep
% track of whatever happens in this folder. So the full initialisation
% of a complex complete version control system with Git looks like this:
% \begin{verbatim}
% > mkdir MyProject
% > cd MyProject
% > git init
% \end{verbatim}
% That was easy, wasn't it? Now you can keep track of all changes to
% your files in this folder. Moving on\ldots
% \subsection{Name and email address}
% \label{sec:name-email-address}
% Every time somebody makes a change to a program, Git marks the change
% with the name and the email address of the person responsible for it.
% As you do not want to do is writing your
% name and your email address every time you make a change, this is
% usually set up at the beginning. You can do it with the command
% \verb+git config+.
% \begin{verbatim}
% > git config --global user.name "John Smith"
% > git config --global user.email "john.smith@student-bbk-ac-uk"
% > git config --global user.email "john.smith@gmail"
% \end{verbatim}
% These commands will set your name and email address for every (local)
% repository in your machine because you are using the \verb+--global+
% flag.
% %
% Without the \verb+--global+ flag,
% the command modifies the configuration of
% the current repository only.
% Sometimes you want to have different names or
% emails on different repositories, although this is rare.
% Note that the email address does not need to be valid. To avoid spam,
% it is not uncommon for users to use email addresses that are perfectly
% understandable for human beings but confusing for spambots,
% e.g. removing the last \verb+.com+ (john.smith@gmail)
% or changing dots for dashes (john.smith@student-bbk-ac-uk).
\subsection{Think global, act local}
\label{sec:cloning-technology}
A repository is just a place (somewhere on the internet or in a
private intranet) where the source code for a software project is
stored. There are two types of repositories for any project:
\emph{local copies}, where you do the work; and \emph{one public
copy}, that other people can look at. Any machine on the internet
can be used to host a public copy of a Git project and GitHub
(\verb+www.github.com+) is a convenient place that many people use.
You cannot write your programs on GitHub, you can only do it in your
local copy. Therefore, the first thing you have to do after creating
your repository on GitHub is making a local copy, a process known as
\emph{cloning}.
\begin{verbatim}
> git clone https://github.com/bbk-myName/my-repository.git
\end{verbatim}
This will create a local copy of the remote repository you have just
created. You can now make changes to it: create new files, modify the
existing ones, etc.
(You can also clone repositories that were created long time ago and/or
by other people. More on that later.)
\subsection{Keeping track of changes}
\label{sec:keep-track-chang}
Let's start by writing some code. For example, let's create a
simple \emph{Hello World} application in Groovy\footnote{Feel free to
use Java Decaf or Java instead of Groovy for the following
examples.}. In other words, we
will edit a file called \verb+helloworld.groovy+ and write on it:
\begin{verbatim}
print "Hello World!"
\end{verbatim}
If we execute this little program, it will print the words ``Hello
World!'' on the screen. So far, so good. Time to start filling up our
\emph{version journal}!
The first step is to tell Git that we want to keep track of this
file. In other words, we \emph{add} it to the list of files under
Git's responsibility.
\begin{verbatim}
> git add helloworld.groovy
\end{verbatim}
And now we must perform the most important operation in any version control
system: \emph{committing} our changes.
\begin{verbatim}
> git commit
\end{verbatim}
You will be asked to introduce some description of what this \emph{commit}
is about. Git automatically adds information about which files are
committed and what changes have been performed on them. The programmer
must provide some additional information: a short message to explain
to other programmers what the changes are about. Note that ``other
programmers'' can mean yourself in two weeks time ---when you have
forgotten what you committed at this point. Typical messages are
``First commit'', ``Fixed bug \#1304'', ``Added a new feature
for\ldots''; examples of bad non-informative commit messages are ``new
commit'', ``More code'', or ``Fixed it AT LAST!'' (what is
\emph{it}?). Write whatever you
want, but make a (small) effort to think what message will be useful
for people reading it in the future.
When you finish writing your commit description, save it and close the
editor. The commit will be performed, and you will be given some
output from Git. That output will include information about the
branch (by default, it is called \emph{master}), the identifier for
this commit (a unique identifier similar to ``12a0006''),
your commit text, and some
statistics about what the commit did: lines added, edited, or removed,
files added or removed, etc (\emph{see
Figure~\ref{fig:git-example-output}}).
\begin{figure}[htbp!]
\centering
\begin{framed}
\begin{verbatim}
> git commit
[master 12a0006] Added first line: just says "Hello World!"
1 file changed, 7 insertions(+), 1 deletion(-)
>
\end{verbatim}
\end{framed}
\caption{Example of Git's output after a commit.}
\label{fig:git-example-output}
% TODO: add hand-written tags to screenshot
\end{figure}
Now your project has a history!
It looks more or less like Figure~\ref{fig:git-example-1}.
Not very impressive, but we are just starting.
\begin{figure}[htbp!]
\centering
\includegraphics[width=\textwidth]{gfx/commit_history_1.eps}
\caption{Initial history of this project}
\label{fig:git-example-1}
\end{figure}
\subsubsection*{What to do when you mess up}
\label{sec:what-do-when}
Let's say we are not happy with our program. It does not do much. We
can modify the program to look like this:
\begin{verbatim}
println "Hello World!"
println "What's your name?"
String s = System.console().readline()
println "Hello " + s + "!"
\end{verbatim}
Once we have saved the changes, we can commit again
(\verb+git add helloworld.groovy+; \verb+git commit+,
plus a commit description).
However, if we try to run the program, Groovy will complain.
We have messed up! At this point, we have two options:
\begin{itemize}
\item If we know where the problem is (and in this simple example, we
do) we can just fix it and commit again. A good commit message would
be ``Fixed typo in line 3: readline() should be readLine()''. The
history of the project is represented in
Figure~\ref{fig:git-example-2}.
\item If we did not know where the problem is, as it is usually the
case in big programs, we can go back in time
until we find the commit in
which the problem started. Looking at the changes on that commit we
can see how the \emph{bug} was introduced. Thanks to version
control, finding bugs is much easier (and
finding bugs is 80\% of the job).
\end{itemize}
\begin{figure}[htbp!]
\centering
\includegraphics[width=\textwidth]{gfx/commit_history_2.eps}
\caption{History of this project after second commit}
\label{fig:git-example-2}
\end{figure}
The simplest way to travel in time is by looking at the change log of
a file, and we are going to see how to do that in the next section.
\subsection{Looking into the past}
\label{sec:looking-into-past}
Contrary to most novelists, professional programmers do not usually
start working on a project from a blank editor page.
The most common situation is to work
on a project that has already been going on for some time. Maybe the
programmer is a new employee in the company, or has been transferred
to a different project, or has ``inherited'' a project that somebody
else started. Or it may be that the programmer wants to contribute to
another project because the project is appealing or
famous\footnote{Examples of interesting free/open-source projects with
many contributors include web browsers like Firefox or Chrome, the
Linux kernel, the Android operating system (based on Linux), the
LibreOffice suite of applications, mail programs
like Thunderbird, and many others.}. Or maybe the programmer starts a
project from scratch and then realises that somebody else is doing the
same thing, only they started long ago and have made a lot of
progress, so it makes sense to join their team instead of reinventing
the wheel. For any of these reasons ---and many others--- you will
find yourself in a situation where you want to get a copy of the
source code that other people have written. This is very easy to do in
Git. You just need to be given a URL\footnote{A Uniform
Resource Locator (URL) is a specific character string that
constitutes a reference to an Internet resource. Examples of URLs
are \texttt{http://www.bbk.ac.uk} and
\texttt{ftp://gb.archive.ubuntu.com/ubuntu/}.
} to the source code, and clone it. Cloning other people's project
works in the same way as cloning your own project:
\begin{verbatim}
> git clone https://github.com/bbk-msccs/currency-exchanger.git
\end{verbatim}
Now that we have a copy of the Currency Exchanger project, let's look
at it. You will see that it has only two files: a ``read me'' file
called \verb+README.md+ (that explains what the project is about) and
a Groovy file called \verb+currencyConverter.groovy+. This is the
interesting one.
Look at the code of \verb+currencyConverter.groovy+ and understand
what it does and how it works. Then come back and continue reading. Go
on, I will wait for you here.
As you can imagine, this little program was not written in one go. You
can see a summary of the history of the file by looking at its
\emph{commit log}:
\begin{verbatim}
> git log currencyConverter.groovy
\end{verbatim}
This will show the list of commits on your screen, ordered
chronologically. For every commit, you can see the commit ID, the
author, and the date and time on which the commit was made. You can
also read the commit message.
You can pass arguments to \verb+git log+ so that Git only shows you
commits for one author, or between two specific dates, and many
other options. Type \verb+git help log+ for more information. You can
use \verb+git help <command>+ to get help on any other command.
The problem with \verb+git log+ is that it does not show how the code
changed from one commit to the next. But there is a way to do this:
\verb+git diff+. Let's have a look at an example:
\begin{verbatim}
> git diff ab9d6 9ecf9
\end{verbatim}
This command shows the changes between those two commits. Note that I
did not have to write the whole commit ID (40 characters!) but only
the first five are fine \emph{as long as they are unique}. If the
shortened IDs you use are not unique, Git will complain. In this case,
the short IDs are unique and Git tells that only one line was changed:
\begin{verbatim}
index 2d97cf4..5650842 100644
--- a/currencyConverter.groovy
+++ b/currencyConverter.groovy
@@ -23,7 +23,7 @@ while (!finished) {
case 2:
print "How many euro would you like to convert? ";
double euro = Double.parseDouble(System.console().readLine());
- double pounds = euro * poundOverEuroRatio;
+ double pounds = pounds * euroOverPoundRatio;
println euro + "€ will give you £" + pounds;
break;
case 0:
\end{verbatim}
The ``-'' sign on the margin shows a deleted line while the ``+'' sign
shows an added line; the other lines were not changed.
If you take everything into account, the only thing that changed
in this commit was the name of two variables on that line.
You can also use some special tag names for referring to a commit, as
shown on Figure
\begin{table}[hbtp]
\centering
\begin{tabular}{p{2cm}p{8cm}}
ID & Identifies\ldots \\
\hline
9ecf9 & \ldots any commit whose 40-digit ID contains \emph{9ecf9}
as long as there is only one \\
HEAD & \ldots the latest commit done \\
\verb+^+ & \ldots this suffix identifies the commit before another one \\
HEAD\verb-^- & \ldots the commit before the latest \\
9ecf9\verb-^^- & \ldots the commit before the commit before \emph{9ecf9} \\
\end{tabular}
\caption{Commit names in Git}
\label{tab:tagnames}
\end{table}
\subsection{Sharing is caring}
\label{sec:sharing-caring}
% TODO: This section requires non-trivial rewriting.
% - Before we can push, we need to clone from github
% - Before we can do that, we need to "git init" in GitHub.
% - The former point makes all the discussion about
% git init mostly moot. Maybe better to remove it and
% add it to "extra"
%
% EXTRA: explain what a bare repository is, how to create one
% (with 'git clone --bare . path/to/somewhereelse/reponame.git)
% and possibly how to create a non-bare repo here as well.
\subsubsection{Push}
\label{sec:push}
If you wanted to improve the former program (the currency converter),
you could edit it yourself, add
new features, change some code, etc. You would commit regularly to
make sure you always have the history of your project up to date (so
you can see what changes you introduced over time).
At some point you will want to make your changes public (in Git
jargon, this is called \emph{pushing your changes}), e.g. to allow
other members of your team to see what you have done.
Usually, you push to the same public copy that you cloned the code
from; by default, this public copy is called ``origin'' by Git,
although you can change this name and/or have more than one remote
copies where you push your changes (``git help remote'' is the place
to start if you want to learn more about this). Pushing changes is
very easy:
% To make your
% changes public, you usually need a place to put your \emph{public
% repository} (as opposed to your \emph{local copy}, where you
% work). You can host your public repository anywhere you want, but
% GitHub is a convenient, well-known, and costless possibility. For the
% purposes of this discussion, I will assume that you have an account at
% GitHub, that your account name is ``ilovegit'', and that you have
% created a repository in GitHub called ``my-currency-exchange''.
% The first thing you have to do (but you only need to do this the first
% time) is telling Git where to push the changes. This is done by adding
% a remote site (with the command\ldots \verb+git remote+, surprise!):
% \begin{verbatim}
% > git remote add origin https://github.com/sergutsan/groovyck.git
% \end{verbatim}
% There are many things on that line that need explaining. First,
% ``add'' tells git that you want to add a new remote site; you can also
% remove (``rm'') and rename (``rename'') remote sites. By default,
% \verb+git remote+ will just show a list of your remote sites (name,
% url\ldots). The word ``origin'' is just a name for the new remote site
% to be used locally; origin is a common name for the main repository
% where you push your changes. We could have used ``my-projects'', or
% ``myRemoteSite'', or any other name as long as we have not used it
% yet. Finally, the URL is where the remote site
% is. GitHub\footnote{GitHub does give you much more than just hosting
% your repositories: issue tracker, statistics, graphs, and limited
% social networking capabilities are some of the features you can use
% easily from their webpage. Not bad for a free service. Another good
% option is Google Code.} will give
% you a URL that you can copy and paste (see Figure~\ref{fig:github}).
% \begin{figure}[htbp]
% \centering
% \includegraphics[width=\textwidth]{gfx/gitHubScreenshot.eps}
% \caption{Screenshot of GitHub. You can see the name of the user
% (``bbk-msccs''), the name of the repository
% (``currency-exchanger''), and the URL. You can use the URL both to
% clone the reposity and to push your changes (as long as this
% repository is yours, i.e. you can \emph{write} on it).}
% \label{fig:github}
% \end{figure}
% Once you have configured your remote repository or repositories,
% pushing your changes is very easy: you only need to say where to push.
\begin{verbatim}
> git push origin
Username for 'https://github.com': ilovegit
Password for 'https://ilovegit@github.com':
To https://github.com/ilovegit/my-currency-exchange.git
6457568..55ca3da master -> master
\end{verbatim}
The system will ask for your username (``ilovegit'' in this example)
and your password. Then, if everything goes according to plan,
it will inform you that it has pushed your commits. Note that
this step could
fail for several reasons, like your network connection going down.
\subsubsection{Pull}
\label{sec:pull}
Once you have pushed your changes, how do other people see them? How
do they take the code you have \emph{pushed} into your remote
repository and put it in their local copies of the source code? As you
can imagine, they \emph{pull} it.
\begin{verbatim}
> git pull origin master
\end{verbatim}
When you pull, you have to specify the remote repository you are
pulling from (``origin'' in this case) and the branch you are pulling
from. We will talk later about branches, but for now it suffices to
say that the default branch in most projects is called ``master'', and
sometimes it is the only one. If you are not sure which branch you are
pulling from, ``master'' is usually a good guess.
Once you pull, Git will download the code (or, in other words, the
changes made public at that
remote repository and merge them with your local copy. Once it
finishes, you have the latest copy of the project's source code,
including those changes that somebody else (maybe you) made in a
different computer.
At this point, you have surely noticed that Git can be used to
synchronise with other team members, each of them pulling whatever
changes others have pushed so that everybody is up to date; but it can
also be used to keep up to date with yourself: you can work on
different computers (at home, at the office, on your laptop on a
plane) and you can push your changes and then pull them from the other
computers. There is no need to carry around USB sticks with folders
called ``currencyExchangev2'', ``currencyExchangev3'', or
``currencyExchangev4usethisnottheother''. Git will always have the
latest version as long as you do not forget to commit and push
timely (Figure~\ref{fig:pushpull}).
\begin{figure}[htbp!]
\centering
\includegraphics[width=\textwidth]{gfx/pushpull}
\caption{Pushing and pulling: when Alfred pushes his changes to make
them public, Bertha will be able to pull them and work on the last
version of the software. If Alfred takes a plane to Paris, he will
be able to pull the changes from Paris to get the last
version\ldots including any changes that Bertha and other
co-workers may have pushed while he was on the plane!}
\label{fig:pushpull}
\end{figure}
\subsection{When should I commit?}
\label{sec:when-should-i}
As a general rule: \emph{commit early, commit often}. It is generally
a good idea to make small commits so that it is easier to go through
the history of your code and understand every step if you have to. The
cost of
committing is almost zero so you should not be afraid of having too
many commits (there is no such thing as ``too many commits'').
Of course, this does not mean that you commit every single character
that you write. Committing every single line is also probably too
much, unless those lines are really special (e.g.~they fix a bug).
\emph{Do not spend more time
writing commit messages than writing code}. That said, if you have not
committed for the last half hour, either you have written a lot of
code and you should commit early (as in \emph{now}); or you are tired
or distracted, and not really programming, so maybe you should have a
break.
If you are not sure what you have changed since the last commit,
you can use \verb+git diff+. Another ---less verbose--- possibility
is to use \verb+git status+. The latter will tell you
which files have changed since the last commit, without details of the
changes.
Additionally, you should \emph{push} your changes to your public
repository fairly often. Some people say \emph{push early, push
often}, but it does not mean that you need to push after every
commit. Sometimes
you cannot even push because you do not have a network connection,
although this is becoming more and more uncommon these days, where you
can connect to the internet from planes, submarines, and almost a
robot wandering around Mars\footnote{Actually, a robot in Mars cannot
connect to the internet, at least not what we call ``the Internet''
in 2012 (computers interconnected using the TCP/IP and related protocols).
Radio waves travel \emph{only} as fast as light-speed, and it
takes them so long to reach the Earth that internet hosts would
timeout before a connection could be stablished.
You \emph{could} connect to
the Internet from the Moon, though, but your bandwitdh would be
very poor compared to your home connection.}.
As a rule of thumb, push every time you
have finished a coding session (e.g. before turning off the computer
or before standing up to grab some lunch),
or as soon as possible after that.
\subsection{Back to the past\ldots}
\label{sec:branching}
If you have been reading carefully until now, you will have noticed
that we do not know yet how to \emph{move back in time}. So far we
have only learnt how to look into the past using \verb+git log+. In
order to be able to \emph{roll back} when we mess up things, we need
to do one of two things: either we can \emph{revert} changes or we can
\emph{branch} the history of our source code
(Section~\ref{sec:branch-branch-everyw}).
\subsubsection{Time reversal}
\label{sec:time-reversal}
The simplest form of time reversal is by using the command
\verb+git revert+. This command makes a commit
that cancels all the commits that
you specify. Confusing?
Maybe, but think that the typical use case is cancelling just the last
commit: you make some changes, you commit them, and then you realise
that you forgot to do something before committing\ldots maybe you
forgot to add a file, or something of the sort. At this point, you can
follow two courses of action. Either you do the things you had
forgotten and then commit them (using a message like ``this is what I
forgot to do in commit 25cec5a... 4''), which is not optimal; or you
revert and then commit again, like in this example.
\begin{verbatim}
(modify file1 and file2)
> git add file1
> git commit
(realise you forgot to add file2)
> git revert HEAD
> git add file2
> git commit
\end{verbatim}
HEAD is a special tag that means\footnote{Strictly speaking, it means
the last commit \emph{for the current branch}, but for now we are
assuming we only have one branch, called \emph{master}.} ``the last
commit'' (see Table~\ref{tab:tagnames}). Git will ask you
to introduce a commit message to explain why you are reverting that
change. You are not limited to revert the last commit. You can revert
many commits, as in this example (remember the special tags from
Table~\ref{tab:tagnames}) that reverts the last four commits
(you will need to add a message for each reverting commit):
\begin{verbatim}
> git revert HEAD HEAD^ HEAD^^ HEAD^^^
\end{verbatim}
Git will take care of all the changes to the source code for you.
\subsubsection{Conflicts}
\label{sec:conflicts}
You can also revert any combination of commits that you want.
\begin{verbatim}
> git revert a827e5fe 067cac919 938f6821a
\end{verbatim}
Usually, Git will do all the necessary changes to revert all those
commits and give the resulting files.
However, reverting arbitrary commits
may result in a \emph{conflict}. A conflict happens when Git
cannot reliably make a change in the code to accommodate your
wishes. This is uncommon, but may happen if you are not careful when
reverting changes or merge two very different pieces of code.
When a conflict happens, Git will tell you which files have conflicts
so that you can fix the source files yourself. A file with a conflict
looks like this:
\begin{verbatim}
(some source code here)
<<<<<<< comit-ID-1
(source code as in ID-1
=======
(source code as in ID-2
>>>>>>> commit-ID-2
(more source code here)
\end{verbatim}
Your role as programmer gifted with a human intelligence ---Git is
able to solve most conflicts itself, but not all--- is to decide
which code should stay: the code between \verb+<<<<+ and \verb+=====+
or the code between \verb+====+ and \verb+>>>>+. Maybe none is
correct and you need to write new code to fix the conflict (and remove
the \verb+<+, \verb+=+, and \verb+>+ symbols, of course).
In any case, once the conflict is resolved (by you),
you have to commit the changes.
\subsection{Branches, branches everywhere\ldots}
\label{sec:branch-branch-everyw}
Last, but definitely not least, we need to learn about branches. You
have already met the most important one, called \emph{master}. This is
the default branch in any Git repository, and sometimes it is the only
one. But a Git repository can have an unlimited number of branches,
and this is very common for large projects.
Branches are important in Git, and in any version control
system. Branches allow programmers to advance development without
compromising the stability of the code released to clients, to try
experimental features that may or may not be worth been added to the
project, and to collaborate with external programmers that want to
help in the development.
There are many interesting things that you can do with branches, and
this is one of the most important features of Git. However, for the
moment we are going to see just the basic functionality.
You create a new branch with the command
\verb+git branch <branch_name>+, and change branches with the command
\verb+git checkout <branch_name>+. Whatever you commit to a branch is
only visible to that branch, at least until you merge it with another
branch.
Let's see what branches are about with a small step-by-step example:
\begin{enumerate}
\item Create a new empty Git repository. Clone it.
\item Create a new file called \verb+mainFile+ inside
the local copy of the repository, and then make some
simple changes to it (e.g. add a few lines of text).
Commit your changes (to \emph{master}).
\item Create a new branch: \verb+git branch testing+. Change to the
new branch: \verb+git checkout testing+.
\item You are now in \verb+testing+. Create a new file
\verb+experimentalFile+ and add some lines to it. Commit.
Add some lines
to \verb+mainFile+ too. Commit.
\item See the history of your files using \verb+git log+.
\item Go back to the \emph{master} branch:
\verb+git checkout master+.
\item See the history of your files using \verb+git log+. Do you see
any difference?
\item Add some lines (different from before) to
\verb+mainFile+. Commit.
\item Change branches again: \verb+git checkout testing+. Read the
content of mainFile. Check the history: \verb+git log mainFile+. Is
it the same history as in the other branch?
\end{enumerate}
As you can see, opening branches allows you to do experimental or
not-well-tested code without compromising your main line of
development (see Figure~\ref{fig:git-example-3}).
After branches diverge, any new commits you make in \verb+testing+ are not
visible in \verb+master+ and viceversa.
\begin{figure}[htbp!]
\centering
\includegraphics[width=\textwidth]{gfx/commit_history_3.eps}
\caption{Project with two branches: master and experimental}
\label{fig:git-example-3}
\end{figure}
If at a later point you become convinced that your work
in testing is worth being merged into the main branch, you can do so
with:
\begin{verbatim}
> git checkout master
> git merge testing
\end{verbatim}
This will merge both branches and create a new commit in \emph{master}
that includes all the changes from \emph{testing}. Note that,
depending on the changes you have made in both branches since they
separated, a conflict may arise and you will need to
fix it (and then commit) manually (see Section~\ref{sec:conflicts}).
\begin{figure}[htbp!]
\centering
\includegraphics[width=\textwidth]{gfx/commit_history_4.eps}
\caption{Merging branch ``experimental'' into ``master''}
\label{fig:git-example-4}
\end{figure}
\subsubsection*{Replacing a branch}
\label{sec:exercise-1ff}
You can also use branches to go back in time and change the way you
are doing things. For instance, think of a situation where your work
in \emph{master} was based on one technology and, further down the
line, you discover another technology that is much better. Another
possibility is that you messed up but do not realise until several
commits laters.
You could of course just delete the code of the old technology and
start writing your new code for the new technology. But there is a
better way. You can move back in time, branch, and then continue your
development in the new branch\ldots and call it \emph{master}. The
process would be as follows:
\begin{verbatim}
> git checkout 33gfg32 [1]
> git branch newMaster [2]
> git branch -m oldTech [3]
> git branch newMaster
> git branch -b master [4]
\end{verbatim}
The first command [1] puts you at the right point where you want to
start a new branch. Note that you can use \verb+git checkout+ to
change branches or to change to a specific commit\footnote{Actually,
branches in Git are implemented as aliases of commits, so it is
basically the same thing. In other words, a branch is just a pointer
that points to a commit and that gets updated every time there is a
commit and that branch is active.}. Then you create a new branch [2]
as we have seen before. Then you change the name of the current
branch [3], using \verb+git branch -b+ (look up the help for more
details). Finally, you change branches and rename the new branch to
\emph{master} [4]. Then you continue your development in the new
branch.
There is much more that can be said about branches and how they make
it easy to have several levels of development in your projects, and
how they make it easy for many programmers to work on the same
project, but we will see all of that at a later point.
\subsection{Ignoring files}
\label{sec:ignoring-files}
Sometimes you want Git to ignore some files. You do not want to keep
them under version control, cannot delete them, and do not want to
have them appearing on the screen every time that you check the status
of the repository. This is a common occurrence for temporary files
like \verb+.o+ files in C/C++, \verb+.class+ files in Java,
\verb+.dvi+ files in \LaTeX, automatic backup files, etc.
The way to tell Git to ignore these files is by listing them in a file
called \verb+.gitignore+ at the root of the repository. This file can
contain name files, but can also include wildcards. The typical
content of a \verb+.gitignore+ file can look like this:
\begin{verbatim}
*.o
*.class
*~
\end{verbatim}
You can add comments to a \verb+.gitignore+ file (with ``\#''), add
exceptions to wildcard rules (with ``!''), and many more useful
tricks. Remember, \verb+git help gitignore+ is a good place to start
looking for help.
The file \verb+.gitignore+ can (and should) be added and
committed to your repository like any other file.
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End: