Introduzione a git: prima parte
La
settimana scorsa si è tenuta la prima serata dedicata a
git, il sistema di controllo delle versioni
creato da Linus Torvalds ed adottato da innumerevoli progetti di
software libero.
In questo articolo vediamo passo passo come creare e popolare un repository come quello su cui abbiamo lavorato nel corso della serata.
Un nuovo progetto
Iniziamo un nuovo progetto che vogliamo salvare sotto git: non serve preoccuparsi di avere un server, e neanche un nome pubblicabile per il progetto, basta creare una directory (che potremo rinominare in futuro), dire a git di crearci un repository e poi si può inizare subito a lavorare.
$ mkdir greeter
$ cd greeter/
$ git init
Initialized empty Git repository in /home/[...]/greeter/.git/
Qualche file
Creiamo i nostri file, in questo caso un programma in python che saluterà le persone.
$ mkdir greeter
$ touch greeter/__init__.py
$ cat > greeter/greeter.py
class Greeter:
""" """
$ cat > greeter.py
#!/usr/bin/env python
def main():
pass
if __name__ == '__main__': main()
$ chmod 755 greeter.py
GIT
Con git status
possiamo vedere che git si è
accorto dell'esistenza di alcuni file, ma sono untracked, ovvero non
considerati dal controllo delle revisioni.
$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# greeter.py
# greeter/
nothing added to commit but untracked files present (use "git add" to track)
In staging
Aggiungiamo quel che abbiamo fatto alla staging area, ovvero diciamo a git di prendere in considerazione quella versione del file perché venga successivamente salvata.
$ git add greeter.py greeter/
$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: greeter.py
# new file: greeter/__init__.py
# new file: greeter/greeter.py
#
Altre modifiche
Facendo altre modifiche e riguardando git status
{.docutils
.literal} ci possiamo accorgere di come git non salvi automaticamente
tutti i cambiamenti presenti nei file di cui tiene traccia, ma solo
quelli che gli vengono indicati esplicitamente da salvare.
$ cat > greeter/__init__.py
from greeter import Greeter
$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: greeter.py
# new file: greeter/__init__.py
# new file: greeter/greeter.py
#
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: greeter/__init__.py
#
Ultimi preparativi
A questo punto possiamo aggiungere anche le ultime modifiche:
$ git add greeter/__init__.py
$ git commit
Se è la prima volta che usiamo git su questo computer salviamo qualche informazione su di noi, nel mio caso:
$ git config --global user.name "Elena ``of Valhalla'' Grandi"
$ git config --global user.email valhalla@trueelena.org
Commit
E finalmente possiamo creare il nostro primo commit, un insieme di file in una loro determinata versione al quale vengono associati alcuni metadati (autore, data, ...) e soprattutto un identificativo che è un hash crittografico dei contenuti.
Il comando git commit
apre un editor con il quale
scrivere un commento da associare al commit. Di solito si scrive una
descrizione breve da una riga (una 60ina di caratteri), e poi
eventualmente altre informazioni più approfondite.
Skeleton for the new project.
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: greeter.py
# new file: greeter/__init__.py
# new file: greeter/greeter.py
#
Commit (2)
".git/COMMIT_EDITMSG" 14L, 377C written
[master (root-commit) b54e94f] Skeleton for the new project.
3 files changed, 9 insertions(+)
create mode 100755 greeter.py
create mode 100644 greeter/__init__.py
create mode 100644 greeter/greeter.py
log
Con il comando git log
possiamo vedere
l'identificativo completo del commit appena fatto, e qualche metadato.
$ git log
commit b54e94fde972281ca31a56ef0d36204addd4906b
Author: Elena ``of Valhalla'' Grandi <valhalla@trueelena.org>
Date: Thu Nov 15 19:05:42 2012 +0100
Skeleton for the new project.
Show
E con git show
possiamo vedere i dettagli del
commit, con tutte le modifiche che sono state introdotte (sotto forma di
diff dalla versione precedente).
Possiamo vedere come non serva scrivere tutto l'identificativo del commit, ma bastino i primi caratteri sufficienti ad identificarlo univocamente nel repository.
$ git show b54e
commit b54e94fde972281ca31a56ef0d36204addd4906b
Author: Elena ``of Valhalla'' Grandi <valhalla@trueelena.org>
Date: Thu Nov 15 19:05:42 2012 +0100
Skeleton for the new project.
diff --git a/greeter.py b/greeter.py
new file mode 100755
index 0000000..b96deee
--- /dev/null
+++ b/greeter.py
@@ -0,0 +1,6 @@
+#!/usr/bin/env python
+
[...]
Iniziamo a lavorarci (1)
Iniziamo a lavorare al progetto, riempiendo qualche file.
greeter/greeter.py
:
class Greeter:
""" """
def greet(self):
print "Hello World!"
Iniziamo a lavorarci (2)
greeter.py
:
#!/usr/bin/env python
import greeter
def main():
grt = greeter.Greeter()
grt.greet()
if __name__ == '__main__': main()
Diamo in pasto a git
E vediamo di nuovo il workflow quotidiano: aggiungiamo le modifiche
fatte alla staging area con git add
per poi darle
in pasto agit commit
.
In questo caso anziché usare un editor per descrivere il commit ci
accontentiamo di una descrizione breve, passata per comodità con
l'opzione -m
.
$ git add greeter.py greeter/greeter.py
$ git commit -m 'Generic greetings'
[master adfbc73] Generic greetings
2 files changed, 8 insertions(+), 1 deletion(-)
$ git status
# On branch master
nothing to commit (working directory clean)
$ git log
commit adfbc7340ac1af8b1dc80ebb1526c7b2b9ad4d1f
Author: Elena ``of Valhalla'' Grandi <valhalla@trueelena.org>
Date: Thu Nov 15 19:08:29 2012 +0100
Generic greetings
commit b54e94fde972281ca31a56ef0d36204addd4906b
Author: Elena ``of Valhalla'' Grandi <valhalla@trueelena.org>
Date: Thu Nov 15 19:05:42 2012 +0100
Skeleton for the new project.
amend
Se ci si è accorti di aver sbagliato qualcosa nella descrizione del
commit lo si può cambiare con git commit --amend
.
$ git commit --amend
Generic greetings.
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
# (use "git reset HEAD^1 <file>..." to unstage)
#
# modified: greeter.py
# modified: greeter/greeter.py
[master 8cdccd9] Generic greetings.
2 files changed, 8 insertions(+), 1 deletion(-)
Notare come l'identificativo del commit sia cambiato: di
fatto git commit --amend
cancella l'ultimo commit
e ne crea uno nuovo.
Questo significa che questo comando non si può usare nel caso in cui si sia già distribuito in qualche modo il commit in questione, dato che la cosa può causare problemi negli altri repository.
gitignore
Lavorando al progetto capita che si generino file che si vogliono
ignorare, ad esempio i risultati di compilazione: basta aggiungerli al
file .gitignore
perché non vengano considerati.
$ ./greeter.py
Hello World!
$ git status
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# greeter/__init__.pyc
# greeter/greeter.pyc
nothing added to commit but untracked files present (use "git add" to track)
$ echo "*.pyc" >> .gitignore
$ git status
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ git add .gitignore
$ git commit -m '.gitignore: ignore .pyc files.'
Aggiungere funzionalità
Vogliamo aggiungere al nostro progetto la capacità di salutare persone diverse; dato che dobbiamo fare un po' di modifiche, perché non creare un nuovo feature branch?
Questo è il workflow naturale per git: ogni nuova funzionalità viene sviluppata a parte in un branch apposito, e poi integrata nel branch principale, che in questo modo rimane sempre funzionante.
$ git checkout -b people
greeter/greeter.py
:
class Greeter:
""" """
def greet(self,greetee="World"):
print "Hello %s!"%greetee
$ git add greeter/greeter.py
$ git commit -m 'greeter/greeter.py: support for multiple greetees.'
Arrivati a questo punto si può passare da un branch all'altro usando il
comando git checkout $NOME_BRANCH
, vedere i branch disponibili con
git branch
ed una loro rappresentazione grafica con gitk --all
.
Nella prossima serata vedremo come lavorare tra più repository separati, riunire branch divergenti e pubblicare il proprio lavoro.