Ciclo base di lavoro

Subversion has numerous features, options, bells and whistles, but on a day-to-day basis, odds are that you will only use a few of them. In this section we'll run through the most common things that you might find yourself doing with Subversion in the course of a day's work.

Subversion ha numerose caratteristiche ed opzioni ed offre moltissime opportunità, ma nel lavoro quotidiano è probabile che serva usarne solo alcune. In questa sezione verrà presentata una panoramica delle cose più comuni che bisogna imparare a fare con Subversion nel corso di un normale giorno di lavoro.

The typical work cycle looks like this:

Un tipico ciclo di lavoro assomiglia grossomodo a questo:

Aggiornare la propria copia di lavoro

When working on a project with a team, you'll want to update your working copy to receive any changes made since your last update by other developers on the project. Use svn update to bring your working copy into sync with the latest revision in the repository.

Quando si lavora ad un progetto in gruppo, si dovrà aggiornare la propria copia di lavoro per ricevere tutte le modifiche fatte, dopo l'ultimo aggiornamento, dagli altri sviluppatori. Si usa il comando svn update per allineare la propria copia di lavoro con l'ultima versione nel repository.

$ svn update
U  foo.c
U  bar.c
Updated to revision 2.

In this case, someone else checked in modifications to both foo.c and bar.c since the last time you updated, and Subversion has updated your working copy to include those changes.

In questo caso, qualcun altro ha effettuato delle modifiche ad entrambi i file foo.c e bar.c dall'ultima volta che si è fatto l'update e Subversion ha aggiornato la copia di lavoro per includere queste modifiche.

Let's examine the output of svn update a bit more. When the server sends changes to your working copy, a letter code is displayed next to each item to let you know what actions Subversion performed to bring your working copy up-to-date:

Andiamo ad esaminare un po' meglio l'output del comando svn update. Quando il server invia le modifiche alla propria copia di lavoro, viene visualizzata una lettera subito prima di ogni elemento per indicare l'azione compiuta da Subversion per aggiornare la copia di lavoro:

U foo

File foo was Updated (received changes from the server).

Il file foo è stato Updated (Aggiornato, ha ricevuto le modifiche dal server).

A foo

File or directory foo was Added to your working copy.

Il file o la directory foo è stato Added (Aggiunto) alla vostra copia di lavoro locale.

D foo

File or directory foo was Deleted from your working copy.

Il file o la directory foo è stato Deleted (Cancellato) dalla vostra copia di lavoro locale.

R foo

File or directory foo was Replaced in your working copy; that is, foo was deleted, and a new item with the same name was added. While they may have the same name, the repository considers them to be distinct objects with distinct histories.

Il file o la directory foo è stato Replaced (Sostituito) nella vostra copia di lavoro; il che significa che foo è stato cancellato, ed un nuovo oggetto con lo stesso nome è stato aggiunto. Nonostante possano avere lo stesso nome, il repository li considera due oggetti distinti con storie distinte.

G foo

File foo received new changes from the repository, but your local copy of the file had your modifications. Either the changes did not intersect, or the changes were exactly the same as your local modifications, so Subversion has successfully merGed the repository's changes into the file without a problem.

Il file foo ha ricevuto le nuove modifiche dal repository, ma la copia locale del file ha conservato le proprie modifiche. Sia che le modifiche non coincidano o che siano le stesse, Subversion ha fatto confluire con successo le modifiche presenti nel repository nel file senza problemi.

C foo

File foo received Conflicting changes from the server. The changes from the server directly overlap your own changes to the file. No need to panic, though. This overlap needs to be resolved by a human (you); we discuss this situation later in this chapter.

Il file foo ha ricevuto modifiche Conflicting (Conflittuali) dal server. Le modifiche dal server si sovrappongono direttamente alle proprie modifiche sul file. Niente panico. Questa sovrapposizione deve essere risolta da un intervento umano (il vostro); questa situazione sarà discussa nel seguito di questo capitolo.

Apportare modifiche alla propria copia di lavoro

Now you can get to work and make changes in your working copy. It's usually most convenient to decide on a particular change (or set of changes) to make, such as writing a new feature, fixing a bug, etc. The Subversion commands that you will use here are svn add, svn delete, svn copy, and svn move. However, if you are merely editing files that are already in Subversion, you may not need to use any of these commands until you commit. Changes you can make to your working copy:

A questo punto si è in grado di lavorare ed apportare modifiche alla propria copia di lavoro. Di solito è più conveniente decidere un particolare cambiamento (o un insieme di cambiamenti) da fare, come se si dovesse scrivere una nuova caratteristica, fissare un bug, etc. I comandi Subversion da usare sono svn add, svn delete, svn copy e svn move. Comunque se si stanno semplicemente modificando file che sono già presenti in Subversion, potrebbe non essere necessario nessuno di questi comandi finché non si fa la commit. Modifiche che si possono apportare alla propria copia di lavoro:

Modifiche al file

This is the simplest sort of change. You don't need to tell Subversion that you intend to change a file; just make your changes. Subversion will be able to automatically detect which files have been changed.

Questo è il tipo di modifica più semplice. Non c'è bisogno di dire a Subversion che si intende modificare un file; basta solo eseguire le modifiche. Subversion è in grado di stabilire automaticamente quali file siano stati modificati.

Modifiche all'albero del filesystem

You can ask Subversion to «mark» files and directories for scheduled removal, addition, copying, or moving. While these changes may take place immediately in your working copy, no additions or removals will happen in the repository until you commit them.

Si può richiedere a Subversion di «marcare» file e directory per la rimozione, l'aggiunta, la copia o lo spostamento. Queste modifiche avvengono istantaneamente nella propria copia di lavoro, ma non appariranno rimozioni o aggiunte nel repository finché non si fa la commit.

To make file changes, use your text editor, word processor, graphics program, or whatever tool you would normally use. Subversion handles binary files just as easily as it handles text files—and just as efficiently too.

Per apportare modifiche ad un file si può usare un editor di testi, un word processor, programmi di grafica e qualsiasi tool che si usa normalmente. Subversion gestisce i files binari con la stessa facilità con cui gestisce i file di testo— e con la stessa efficienza.

Here is an overview of the four Subversion subcommands that you'll use most often to make tree changes (we'll cover svn import and svn mkdir later).

Ecco una panoramica su 4 dei comandi di Subversion che si usano più spesso per apportare modifiche ad un albero di directory (si analizzeranno in seguito i comandi: svn import e svn mkdir).

[Avvertimento] Avvertimento

While you can edit your files with whatever tool you like, you shouldn't change the structure of your working copy without letting Subversion know what you're doing. Use the svn copy, svn delete, and svn move commands to change the structure of your working copy, and use the svn add command to place new files and directories under version control.

Mentre si possono modificare i files con qualsiasi tool si desideri, non è possibile modificare la struttura della propria directory di lavoro senza dire a Subversion quello che si sta per fare. Si utilizzano i comandi svn copy, svn delete, e svn move per modificare la struttura, ed il comando svn add per collocare nuovi file e directory sotto il controllo di versione.

svn add foo

Schedule file, directory, or symbolic link foo to be added to the repository. When you next commit, foo will become a child of its parent directory. Note that if foo is a directory, everything underneath foo will be scheduled for addition. If you only want to add foo itself, pass the --non-recursive (-N) switch.

Marca quali file, directory o link simbolici foo per l'aggiunta al repository. Quando si esegue la commit, foo diventerà un figlio della directory padre. Si noti che foo è una directory, tutto ciò che è contenuto in essa verrà pianificato per essere aggiunto. Se si vuole aggiungere soltanto foo bisogna usare l'opzione --non-ricorsivo. (-N).

svn delete foo

Schedule file, directory, or symbolic link foo to be deleted from the repository. If foo is a file or link, it is immediately deleted from your working copy. If foo is a directory, it is not deleted, but Subversion schedules it for deletion. When you commit your changes, foo will be removed from your working copy and the repository. [5]

Marca i file, le directory ed i link simbolici per la cancellazione dal repository. Se foo è un file o un link, viene cancellato immediatamente dalla propria copia di lavoro. Se foo è una directory, non viene cancellata ma Subversion la marca per la cancellazione. Quando si fa la commit delle modifiche, foo sarà rimosso sia dalla copia di lavoro locale che dal repository. [6]

svn copy foo bar

Create a new item bar as a duplicate of foo. bar is automatically scheduled for addition. When bar is added to the repository on the next commit, its copy history is recorded (as having originally come from foo). svn copy does not create intermediate directories.

Si crea un nuovo elemento bar come duplicato di foo. bar viene automaticamente marcato per essere aggiunto. Quando bar viene aggiunto al repository alla commit successiva, la storia della copia viene ereditata (come se provenisse originariamnete da foo). svn copy non crea directory intermedie.

svn move foo bar

This command is exactly the same as running svn copy foo bar; svn delete foo. That is, bar is scheduled for addition as a copy of foo, and foo is scheduled for removal. svn move does not create intermediate directories.

Questo comando è esattamente equivalente a svn copy foo bar; svn delete foo. bar è pianificato per essere aggiunto come copia di foo, e foo è pianificato per la rimozione. svn move non crea directory itermedie.

Esaminare le modifiche apportate

Once you've finished making changes, you need to commit them to the repository, but before you do so, it's usually a good idea to take a look at exactly what you've changed. By examining your changes before you commit, you can make a more accurate log message. You may also discover that you've inadvertently changed a file, and this gives you a chance to revert those changes before committing. Additionally, this is a good opportunity to review and scrutinize changes before publishing them. You can see exactly what changes you've made by using svn status, svn diff, and svn revert. You will usually use the first two commands to find out what files have changed in your working copy, and then perhaps the third to revert some (or all) of those changes.

Una volta che si è finito di apportare le modifiche, bisogna fare la commit sul repository, ma prima è una buona norma guardare con attenzione cosa si è cambiato esattamente. Esaminando le modifiche prima di effettuare la commit si può scrivere un messaggio di log più accurato. Ci si può anche rendere conto di aver modificato un file inavvertitamente e si può tornare indietro prima di fare la commit. Inoltre questa è una buona opportunità per rivedere ed analizzare le modifiche fatte prima di pubblicarle. Per vedere esattamente le modifiche apportate si possono usare i comandi svn status, svn diff e svn revert. In genere si usano i primi due comandi per vedere quali file siano stati modificati nella propria copia di lavoro, ed il terzo per annullare alcune delle modifiche effettuate (o anche tutte).

Subversion has been optimized to help you with this task, and is able to do many things without communicating with the repository. In particular, your working copy contains a secret cached pristine copy of each version controlled file within the .svn area. Because of this, Subversion can quickly show you how your working files have changed, or even allow you to undo your changes without contacting the repository.

Subversion è stato ottimizzato per aiutare in questo compito, e riesce a fare molte cose senza comunicare con il repository. In particolare, la propria directory di lavoro contiene una copia nascosta «originale», di ogni file sotto controllo di versione, all'interno della directory .svn. Per questo motivo, Subversion può mostrare velocemente come sono stati modificati i file di lavoro o anche permettere di annullare le modifiche senza contattare il repository.

svn status

You'll probably use the svn status command more than any other Subversion command.

Il comando svn status è probabilmente il più usato tra i comandi di Subversion.

If you run svn status at the top of your working copy with no arguments, it will detect all file and tree changes you've made. Below are examples of the different status codes that svn status can return. (Note that the text following # is not actually printed by svn status.)

Digitando il comando svn status in testa alla propria directory di lavoro, senza argomenti, esso cercherà tutti i file e le strutture ad albero che sono state create. Riportiamo degli esempi di codice relativi a stati differenti che il comando svn status può restituire. (Si noti che il testo che segue # non è attualmente visualizzato da svn status.)

  L     some_dir            # svn left a lock in the .svn area of some_dir
M       bar.c               # the content in bar.c has local modifications
 M      baz.c               # baz.c has property but no content modifications
X       3rd_party           # dir is part of an externals definition
?       foo.o               # svn doesn't manage foo.o
!       some_dir            # svn manages this, but it's missing or
incomplete
~       qux                 # versioned as file/dir/link, but type has
changed
I       .screenrc           # svn doesn't manage this, and is set to ignore
it
A  +    moved_dir           # added with history of where it came from
M  +    moved_dir/README    # added with history and has local modifications
D       stuff/fish.c        # file is scheduled for deletion
A       stuff/loot/bloo.h   # file is scheduled for addition
C       stuff/loot/lump.c   # file has textual conflicts from an update
 C      stuff/loot/glub.c   # file has property conflicts from an update
R       xyz.c               # file is scheduled for replacement
    S   stuff/squawk        # file or dir has been switched to a branch
     K  dog.jpg             # file is locked locally; lock-token present
     O  cat.jpg             # file is locked in the repository by other user
     B  bird.jpg            # file is locked locally, but lock has been
broken
     T  fish.jpg            # file is locked locally, but lock has been
stolen

In this output format svn status prints five columns of characters, followed by several whitespace characters, followed by a file or directory name. The first column tells the status of a file or directory and/or its contents. The codes printed here are:

In questo formato di output il comando svn status visualizza cinque colonne di caratteri, seguite da diversi spazi, seguiti da un nome di file o directory e/o il loro contenuto. I codici visualizzati sono:

A elemento

The file, directory, or symbolic link item has been scheduled for addition into the repository.

Il file, la directory o il collegamento simbolico elemento è stato pianificato per essere aggiunti al repository.

C elemento

The file item is in a state of conflict. That is, changes received from the server during an update overlap with local changes that you have in your working copy. You must resolve this conflict before committing your changes to the repository.

Il file elemento è in uno stato di conflitto. Questo succede quando le modifiche ricevute dal server, durante un aggiornamento, sono state sovraposte a modifiche fatte localmente nella propria directory di lavoro. Bisogna risolvere questo conflitto prima di fare la commit delle modifiche sul repository.

D elemento

The file, directory, or symbolic link item has been scheduled for deletion from the repository.

Il file, la directory o il collegamento simbolico elemento è stato pianificato per essere cancellati dal repository.

M elemento

The contents of the file item have been modified.

Il contenuto del file elemento è stato modificato.

R elemento

The file, directory, or symbolic link item has been scheduled to replace item in the repository. This means that the object is first deleted, then another object of the same name is added, all within a single revision.

Il file, la directory o il collegamento simbolico elemento è stato marcato per sostituire l'oggetto nel repository. Questo significa che prima l'oggetto viene cancellato, poi viene aggiunto un altro oggetto con lo stesso nome, tutto nella stessa versione.

X elemento

The directory item is unversioned, but is related to a Subversion externals definition. To find out more about externals definitions, see sezione chiamata «Externals Definitions».

La directory elemento non è sotto controllo di versione, ma è collegata ad una definizione esterna di Subversion. Per saperne di più sulle definizioni esterne si veda sezione chiamata «Externals Definitions».

? elemento

The file, directory, or symbolic link item is not under version control. You can silence the question marks by either passing the --quiet (-q) switch to svn status, or by setting the svn:ignore property on the parent directory. For more information on ignored files, see sezione chiamata «svn:ignore».

Il file, la directory o il collegamento simbolico elemento non è sotto il controllo di versione. Si può evitare il punto interrogativo usando l'opzione --quiet (-q) con il comando svn status, oppure impostando la proprietà svn:ignore nella directory padre. Per maggiori informazioni sui file ignorati, si veda sezione chiamata «svn:ignore».

! elemento

The file, directory, or symbolic link item is under version control but is missing or somehow incomplete. The item can be missing if it's removed using a non-Subversion command. In the case of a directory, it can be incomplete if you happened to interrupt a checkout or update. A quick svn update will refetch the file or directory from the repository, or svn revert file will restore a missing file.

Il file, la directory o il collegamento simbolico elemento è sotto il controllo di versione ma è mancante o incompleto. L'elemento può essere mancante perché è stato rimosso senza usare un comando Subversion. Nel caso di una directory, può essere incompleta se si è interrotto un checkout o un update. Il rapido uso del comando svn update andrà a riprendere il file o la directory dal repository, o il comando svn revert file riparerà il file mancante.

~ item

The file, directory, or symbolic link item is in the repository as one kind of object, but what's actually in your working copy is some other kind. For example, Subversion might have a file in the repository, but you removed the file and created a directory in its place, without using the svn delete or svn add command.

Il file, la directory o il collegamento simbolico elemento è salvato nel repository come un tipo di oggetto, ma è salvato, attualmente, nella propria copia di lavoro come oggetto di altro tipo. Ad esempio Subversion, potrebbe avere un file nel repository, ma è stato rimosso il file ed è stata creata una directory al suo posto, senza aver usato il comando svn delete oppure il comando svn add.

I elemento

The file, directory, or symbolic link item is not under version control, and Subversion is configured to ignore it during svn add, svn import and svn status operations. For more information on ignored files, see sezione chiamata «svn:ignore». Note that this symbol only shows up if you pass the --no-ignore option to svn status—otherwise the file would be ignored and not listed at all!

Il file, la directory o il collegamento simbolico elemento non è sotto il controllo di versione e Subversion è configurato per ignorarlo durante le operazioni di svn add, svn import and svn status. Per maggiori informazioni sui file ignorati si veda sezione chiamata «svn:ignore». Si noti che questo simbolo viene mostrato soltanto se si è usata l'opzione --no-ignore con il comando svn status—altrimenti il file viene ignorato e non viene elencato.

The second column tells the status of a file or directory's properties (see sezione chiamata «Proprietà» for more information on properties). If an M appears in the second column, then the properties have been modified, otherwise a whitespace will be printed.

La seconda colonna indica lo stato del file o le proprietà della directory (si veda sezione chiamata «Proprietà» per maggiori informazioni sulle proprietà). Se appare una M nella seconda colonna, allora vuol dire che le proprietà sono state modificate, altrimenti sarà visualizzato uno spazio vuoto.

The third column will only show whitespace or an L which means that Subversion has locked the directory's .svn working area. You will see an L if you run svn status in a directory where an svn commit is in progress—perhaps when you are editing the log message. If Subversion is not running, then presumably Subversion was interrupted and the lock needs to be cleaned up by running svn cleanup (more about that later in this chapter).

La terza colonna mostra soltanto spazi bianchi o una L che indica che la directory .svn è stata bloccata (Lock) da Subversion. Si vedrà una L se si esegue il comando svn status in una directory in cui è in corso un comando di svn commit —ad esempio quando si modificano messaggi di log. Se Subversion non è in esecuzione, probabilmente è stato interrotto ed il blocco deve essere rimosso tramite il comando svn cleanup (si dirà di più su questo argomento nel seguito del capitolo).

The fourth column will only show whitespace or a + which means that the file or directory is scheduled to be added or modified with additional attached history. This typically happens when you svn move or svn copy a file or directory. If you see A  +, this means the item is scheduled for addition-with-history. It could be a file, or the root of a copied directory. + means the item is part of a subtree scheduled for addition-with-history, i.e. some parent got copied, and it's just coming along for the ride. M  + means the item is part of a subtree scheduled for addition-with-history, and it has local modifications. When you commit, first the parent will be added-with-history (copied), which means this file will automatically exist in the copy. Then the local modifications will be uploaded into the copy.

La quarta colonna mostra soltanto spazi bianchi o un + che indica che il file o la directory sono stati marcati per essere aggiunti o modificati con uno storico allegato. Questo succede tipicamente quando si eseguono i comandi svn move o svn copy. Se si vede A  +, vuol dire che l'oggetto è marcato per essere aggiunto con il suo storico. Potrebbe essere un file oppure la radice di una directory copiata. + indica che l'oggetto è parte di un sottoalbero marcato per essere aggiunto con il suo storico, alcuni nodi padre possono essere stati già copiati e si sta aspettando il suo turno. M  +, indica che l'oggetto è parte di un sottoalbero marcato per essere aggiunto con il suo storico, ed è stato modificato localmente. Quando si esegue la commit, per prima cosa viene aggiunto il nodo padre (copiato), il che significa che il file esisterà automaticamente nella copia. In seguito, le modifiche locali saranno ricopiate nella copia.

The fifth column will only show whitespace or an S. This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch.

La quinta colonna mostra solo spazi bianchi o una S. Questo significa che il file o la directory sono stati spostati dal percorso della directory di lavoro in un ramo (usando il comando svn switch).

The sixth column shows information about locks, which is further explained in sezione chiamata «Locking». (These are not the same locks as the ones indicated by an L in the third column; see Three meanings of «lock».)

La sesta colonna mostra informazioni sui blocchi (lock), che sono stati spiegati in sezione chiamata «Locking». (Non sono gli stessi blocchi indicati dalla L nella terza colonna; si veda Three meanings of «lock».)

If you pass a specific path to svn status, it gives you information about that item alone:

Se si passa un percorso specifico al comando svn status, si ottengono informazioni solo su quell'oggetto:

$ svn status stuff/fish.c
D      stuff/fish.c

svn status also has a --verbose (-v) switch, which will show you the status of every item in your working copy, even if it has not been changed:

Il comando svn status ha anche un'opzione --verbose (-v), che mostra lo stato di ogni oggetto presente nella propria directory di lavoro, anche se non è stato modificato:

$ svn status --verbose
M               44        23    sally     README
                44        30    sally     INSTALL
M               44        20    harry     bar.c
                44        18    ira       stuff
                44        35    harry     stuff/trout.c
D               44        19    ira       stuff/fish.c
                44        21    sally     stuff/things
A                0         ?     ?        stuff/things/bloo.h
                44        36    harry     stuff/things/gloo.c

This is the long form output of svn status. The first column remains the same, but the second column shows the working-revision of the item. The third and fourth columns show the revision in which the item last changed, and who changed it.

Questa è la «forma estesa» del risultato del comando svn status. La prima colonna rimane la stessa, ma la seconda mostra la revisione di lavoro dell'oggetto. La terza e la quarta colonna mostrano la revisione nella quale l'oggetto ha subito l'ultimo cambiamento, e chi lo ha eseguito.

None of the above invocations to svn status contact the repository, they work only locally by comparing the metadata in the .svn directory with the working copy. Finally, there is the --show-updates (-u) switch, which contacts the repository and adds information about things that are out-of-date:

Nessuna delle precedenti invocazioni del comando svn status contatta il repository, poiché lavorano solo localmente confrontando i metadati presenti nella directory .svn con la directory di lavoro. Infine, c'è l'opzione --show-updates (-u) , che contatta il repository ed aggiunge informazioni sulle cose che non sono aggiornate:

$ svn status --show-updates --verbose
M      *        44        23    sally     README
M               44        20    harry     bar.c
       *        44        35    harry     stuff/trout.c
D               44        19    ira       stuff/fish.c
A                0         ?     ?        stuff/things/bloo.h
Status against revision:   46

Notice the two asterisks: if you were to run svn update at this point, you would receive changes to README and trout.c. This tells you some very useful information—you'll need to update and get the server changes on README before you commit, or the repository will reject your commit for being out-of-date. (More on this subject later.)

Si notino i due asterischi: se si esegue il comando svn update a questo punto, si riceveranno le modifiche al file README ed al file trout.c. Questo fornisce alcune informazioni molto utili — c'è bisogno di aggiornare e prendere le modifiche del server riguardo il file README prima di fare la commit, altrimenti il repository la rifiuterà perché non si è aggiornati. (Maggiori informazioni sull'argomento in seguito).

svn diff

Another way to examine your changes is with the svn diff command. You can find out exactly how you've modified things by running svn diff with no arguments, which prints out file changes in unified diff format:[7]

Un altro modo per esaminare le proprie modifiche è quello di usare il comando svn diff. Si può verificare esattamente quali siano i cambiamenti apportati lanciando svn diff senza argomenti, il quale stampa le modifiche nel formato 'unified diff':[8]

$ svn diff
Index: bar.c
===================================================================
--- bar.c	(revision 3)
+++ bar.c	(working copy)
@@ -1,7 +1,12 @@
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <stdio.h>

 int main(void) {
-  printf("Sixty-four slices of American Cheese...\n");
+  printf("Sixty-five slices of American Cheese...\n");
 return 0;
 }

Index: README
===================================================================
--- README	(revision 3)
+++ README	(working copy)
@@ -193,3 +193,4 @@
+Note to self:  pick up laundry.

Index: stuff/fish.c
===================================================================
--- stuff/fish.c	(revision 1)
+++ stuff/fish.c	(working copy)
-Welcome to the file known as 'fish'.
-Information on fish will be here soon.

Index: stuff/things/bloo.h
===================================================================
--- stuff/things/bloo.h	(revision 8)
+++ stuff/things/bloo.h	(working copy)
+Here is a new file to describe
+things about bloo.

The svn diff command produces this output by comparing your working files against the cached pristine copies within the .svn area. Files scheduled for addition are displayed as all added-text, and files scheduled for deletion are displayed as all deleted text.

Il comando svn diff produce questo risultato confrontando i propri file di lavoro con le copie «di ripristino» che si trovano nell'area .svn. I file pianificati per essere aggiunti vengono visualizzati come testi aggiunti, e i file pianificati per essere cancellati vengono visualizzati come testi cancellati.

Output is displayed in unified diff format. That is, removed lines are prefaced with a - and added lines are prefaced with a +. svn diff also prints filename and offset information useful to the patch program, so you can generate patches by redirecting the diff output to a file:

L'output è visualizzato in un formato unificato diff . Questo vuol dire che le linee cancellate sono precedute da un - e le linee aggiunte sono precedute da un +. svn diff visualizza inoltre il nome del file e un insieme di informazioni utili per il programma patch, così da poter generare «patch» ridirezionando l'output delle differenze in un file:

$ svn diff > patchfile

You could, for example, email the patch file to another developer for review or testing prior to commit.

Ad esempio si può inviare il file patch ad un altro sviluppatore via email, per una revisione o un test prima di eseguire la commit.

svn revert

Now suppose you see the above diff output, and realize that your changes to README are a mistake; perhaps you accidentally typed that text into the wrong file in your editor.

A questo punto si supponga che si siano analizzati gli output del comando diff visualizzati sopra,e si sia compreso che le modifiche apportate al file README siano un errore; forse si è accidentalmente scritto del testo nel file sbagliato.

This is a perfect opportunity to use svn revert.

È l'occasione perfetta per usare il comando svn revert.

$ svn revert README
Reverted 'README'

Subversion reverts the file to its pre-modified state by overwriting it with the cached pristine copy from the .svn area. But also note that svn revert can undo any scheduled operations—for example, you might decide that you don't want to add a new file after all:

Subversion riporta il file allo stato precedente alla modifica sovrascrivendo la copia «di ripristino» presente nell'area .svn. Ma si noti anche che il comando svn revert può annullare qualsiasi operazione pianificata — ad esempio, si può decidere di non voler aggiungere un nuovo file dopo tutto:

$ svn status foo
?      foo

$ svn add foo
A         foo

$ svn revert foo
Reverted 'foo'

$ svn status foo
?      foo
[Nota] Nota

svn revert ITEM has exactly the same effect as deleting ITEM from your working copy and then running svn update -r BASE ITEM. However, if you're reverting a file, svn revert has one very noticeable difference—it doesn't have to communicate with the repository to restore your file.

svn revert ITEM ha esattamente lo stesso effetto della cancellazione di ITEM dalla propria copia di lavoro e l'esecuzione del comando svn update -r BASE ITEM. Comunque, se si sta riportando un file allo stato precedente, il comando svn revert ha una notevole differenza — non deve comunicare con il repository per ripristinare il file.

Or perhaps you mistakenly removed a file from version control:

O forse per errore è stato rimosso un file dal controllo di versione:

$ svn status README
       README

$ svn delete README
D         README

$ svn revert README
Reverted 'README'

$ svn status README
       README

Risolvere i conflitti(Mettere insieme i cambiamenti operati da altri)

We've already seen how svn status -u can predict conflicts. Suppose you run svn update and some interesting things occur:

Si è già visto come il comando svn status -u può prevedere i conflitti. Si supponga di eseguire il comando svn update e che accada qualcosa di interessante:

$ svn update
U  INSTALL
G  README
C  bar.c
Updated to revision 46.

The U and G codes are no cause for concern; those files cleanly absorbed changes from the repository. The files marked with U contained no local changes but were Updated with changes from the repository. The G stands for merGed, which means that the file had local changes to begin with, but the changes coming from the repository didn't overlap with the local changes.

I codici di output U e G non sono utili alla causa; questi file hanno semplicemente assorbito le modifiche dal repository. I file marcati con U non contengono modifiche locali ma sono stati aggiornati con le modifiche presenti nel repository. La G indica la fusione, il che significa che il file ha modifiche locali ma che le modifiche provenienti dal repository non hanno sovrascritto quelle locali.

But the C stands for conflict. This means that the changes from the server overlapped with your own, and now you have to manually choose between them.

La C indica un conflitto. Questo vuol dire che le modifiche del server hanno sovrascritto quelle locali, ed ora bisogna scegliere manualmente tra esse.

Whenever a conflict occurs, three things typically occur to assist you in noticing and resolving that conflict:

Ogni volta che si crea un conflitto, servono tipicamente tre cose per avvisare del conflitto ed aiutare a risolverlo:

  • Subversion prints a C during the update, and remembers that the file is in a state of conflict.

    Subversion visualizza una C durante l'aggiornamento, e ricorda che il file è in stato di conflitto.

  • If Subversion considers the file to be of a mergeable type, it places conflict markers—special strings of text which delimit the sides of the conflict—into the file to visibly demonstrate the overlapping areas. (Subversion uses the svn:mime-type property to decide if a file is capable of contextual, line-based merging. See sezione chiamata «svn:mime-type» to learn more.)

    Se Subversion considera che il file possa essere fuso, inserisce dei marcatori di conflitto — stringhe speciali di testo che delimitano gli «estremi» del conflitto — all'interno del file per rendere visibili le aree sovrapponibili. (Subversion usa la proprietà svn:mime-typeper decidere se si può fare il merge del file. Per saperne di più si veda sezione chiamata «svn:mime-type».)

  • For every conflicted file, Subversion places up to three extra unversioned files in your working copy:

    Per ogni file che ha avuto un conflitto, Subversion mette nella propria copia di lavoro tre file extra che non sono sotto il controllo di versione.

    filename.mine

    This is your file as it existed in your working copy before you updated your working copy—that is, without conflict markers. This file has your latest changes in it and nothing else. (If Subversion considers the file to be unmergeable, then the .mine file isn't created, since it would be identical to the working file.)

    Questo è il file che c'era nella copia di lavoro prima dell'aggiornamento — ovvero, che non ha marcatori di conflitto. Questo file contiene le ultime modifiche fatte e nient'altro. (Se Subversion considera il file non fondibile, allora il file .mine non viene creato, poiché potrebbe essere identico al file di lavoro).

    filename.rOLDREV

    This is the file that was the BASE revision before you updated your working copy. That is, the file that you checked out before you made your latest edits.

    Questo è il file nella versione BASE precedente all'aggiornamento della copia di lavoro. È il file di cui si è fatto il check out prima delle ultime modifiche.

    filename.rNEWREV

    This is the file that your Subversion client just received from the server when you updated your working copy. This file corresponds to the HEAD revision of the repository.

    Questo è il file che il client di Subversion ha appena ricevuto dal server quando si è fatto l'aggiornamento della copia di lavoro. Questo file corrisponde alla revisione HEAD del repository.

    Here OLDREV is the revision number of the file in your .svn directory and NEWREV is the revision number of the repository HEAD.

    OLDREV è il numero di revisione del file nella directory .svn e NEWREV è il numero di revisione del repository HEAD.

For example, Sally makes changes to the file sandwich.txt in the repository. Harry has just changed the file in his working copy and checked it in. Sally updates her working copy before checking in and she gets a conflict:

Ad esempio, Sally modifica il file sandwich.txt nel repository. Harry ha appena modificato il file nella sua copia di lavoro e ha fatto la commit. Sally ha aggiornato la sua copia di lavoro prima della propria commit ed ottiene un conflitto:

$ svn update
C  sandwich.txt
Updated to revision 2.
$ ls -1
sandwich.txt
sandwich.txt.mine
sandwich.txt.r1
sandwich.txt.r2

At this point, Subversion will not allow you to commit the file sandwich.txt until the three temporary files are removed.

A questo punto, Subversion non permetterà la commit del file sandwich.txt finché non verranno rimossi i tre files temporanei.

$ svn commit --message "Add a few more things"
svn: Commit failed (details follow):
svn: Aborting commit: '/home/sally/svn-work/sandwich.txt' remains in conflict

If you get a conflict, you need to do one of three things:

Se si ha un conflitto, è necessario fare una di queste tre cose:

  • Merge the conflicted text by hand (by examining and editing the conflict markers within the file).

    Sistemare il conflitto «a mano» (esaminando e modificando i marcatori di conflitto all'interno del file).

  • Copy one of the temporary files on top of your working file.

    Usare uno dei file temporanei per sovrascrivere il file di lavoro.

  • Run svn revert <filename> to throw away all of your local changes.

    Eseguire il comando svn revert < filename> per annullare tutte le modifiche fatte in locale.

Once you've resolved the conflict, you need to let Subversion know by running svn resolved. This removes the three temporary files and Subversion no longer considers the file to be in a state of conflict.[9]

Una volta risolto il conflitto, bisogna informare Subversion eseguendo il comando svn resolved. In questo modo vengono rimossi i tre file temporanei e Subversion non considera più il file in stato di conflitto. [10]

$ svn resolved sandwich.txt
Resolved conflicted state of 'sandwich.txt'

Risolvere i conflitti a mano

Merging conflicts by hand can be quite intimidating the first time you attempt it, but with a little practice, it can become as easy as falling off a bike.

Risolvere i conflitti a mano può risultare difficile la prima volta che ci si prova, ma con un po' di pratica, può diventare facile come cadere dalla bicicletta.

Here's an example. Due to a miscommunication, you and Sally, your collaborator, both edit the file sandwich.txt at the same time. Sally commits her changes, and when you go to update your working copy, you get a conflict and we're going to have to edit sandwich.txt to resolve the conflicts. First, let's take a look at the file:

Ecco un esempio. A causa di una cattiva comunicazione, si modifica, insieme alla collaboratrice Sally, il file sandwich.txt nello stesso momento. Sally fa la commit delle sue modifiche, e quando si farà l'aggiornamento della propria copia di lavoro, si otterrà un conflitto e sarà necessario modificare il file sandwich.txt per risolverlo. Per prima cosa diamo uno sguardo al file:

$ cat sandwich.txt
Top piece of bread
Mayonnaise
Lettuce
Tomato
Provolone
<<<<<<< .mine
Salami
Mortadella
Prosciutto
=======
Sauerkraut
Grilled Chicken
>>>>>>> .r2
Creole Mustard
Bottom piece of bread

The strings of less-than signs, equal signs, and greater-than signs are conflict markers, and are not part of the actual data in conflict. You generally want to ensure that those are removed from the file before your next commit. The text between the first two sets of markers is composed of the changes you made in the conflicting area:

I segni di minore, maggiore e uguale sono marcatori di conflitto, e non fanno parte dei dati presenti nel conflitto. Bisogna assicurarsi di toglierli prima di eseguire la commit. Il testo compreso tra i primi due insiemi di marcatori è composto dalle modifiche fatte nell'area in conflitto:

<<<<<<< .mine
Salami
Mortadella
Prosciutto
=======

The text between the second and third sets of conflict markers is the text from Sally's commit:

Il testo compreso tra il secondo e terzo insieme di marcatori di conflitto è il testo del commit di Sally:

=======
Sauerkraut
Grilled Chicken
>>>>>>> .r2

Usually you won't want to just delete the conflict markers and Sally's changes—she's going to be awfully surprised when the sandwich arrives and it's not what she wanted. So this is where you pick up the phone or walk across the office and explain to Sally that you can't get sauerkraut from an Italian deli.[11] Once you've agreed on the changes you will check in, edit your file and remove the conflict markers.

Di solito non si vogliono solo cancellare i marcatori di conflitto e le modficihe di Sally — che resterebbe spiacevolmente sorpresa quando arriva il panino e non è quello che voleva. Così è il caso di prendere il telefono o di andare nell'ufficio di Sally e spiegarle che non si può avere un sauerkraut da un ristorante Italiano.[12] Una volta che si è d'accordo sulle modifiche, si modificherà il file, si cancelleranno i marcatori di conflitto e si effettuerà la commit.

Top piece of bread
Mayonnaise
Lettuce
Tomato
Provolone
Salami
Mortadella
Prosciutto
Creole Mustard
Bottom piece of bread

Now run svn resolved, and you're ready to commit your changes:

A questo punto con il comando svn resolved, si è pronti per fare la commit delle modifiche:

$ svn resolved sandwich.txt
$ svn commit -m "Go ahead and use my sandwich, discarding Sally's edits."

Remember, if you ever get confused while editing the conflicted file, you can always consult the three files that Subversion creates for you in your working copy—including your file as it was before you updated. You can even use a third-party interactive merging tool to examine those three files.

Si ricordi che, se si hanno dubbi mentre si modifica un file in conflitto, si possono consultare i tre files che Subversion crea nella copia di lavoro — includendo il file com'era prima dell'aggiornamento. Si può anche usare una terza-parte, un tool interattivo per esaminare questi tre files.

Copiare un file nel proprio file di lavoro

If you get a conflict and decide that you want to throw out your changes, you can merely copy one of the temporary files created by Subversion over the file in your working copy:

Se si è generato un conflitto e si decide di scartare le modifiche apportate, basta semplicemente copiare uno dei file temporanei i creati da Subversion sul file presente nella propria copia di lavoro:

$ svn update
C  sandwich.txt
Updated to revision 2.
$ ls sandwich.*
sandwich.txt  sandwich.txt.mine  sandwich.txt.r2  sandwich.txt.r1
$ cp sandwich.txt.r2 sandwich.txt
$ svn resolved sandwich.txt

Punting: Usando il comando svn revert

If you get a conflict, and upon examination decide that you want to throw out your changes and start your edits again, just revert your changes:

Se si è generato un conflitto e dopo aver esaminato le modifiche fatte si decide di scartarle e ricominciare a scrivere basta fare il revert delle modifiche:

$ svn revert sandwich.txt
Reverted 'sandwich.txt'
$ ls sandwich.*
sandwich.txt

Note that when you revert a conflicted file, you don't have to run svn resolved.

Si noti che quando si fa il revert di un file con conflitto non serve eseguire il comando svn resolved.

Now you're ready to check in your changes. Note that svn resolved, unlike most of the other commands we've dealt with in this chapter, requires an argument. In any case, you want to be careful and only run svn resolved when you're certain that you've fixed the conflict in your file—once the temporary files are removed, Subversion will let you commit the file even if it still contains conflict markers.

A questo punto si è pronti per controllare le proprie modifiche. Si noti che il comando svn resolved, a differenza della maggior parte degli altri comandi che si sono visti in questo capitolo, richiede un solo argomento. In ogni caso, bisogna essere prudenti ed eseguire il comando svn resolved soltanto se si è sicuri di aver fissato i conflitti nel proprio file — una volta che i file temporanei sono stati rimossi, Subversion permette di eseguire la commit del file anche se contiene ancora marcatori di conflitto.

Fare la commit delle modifiche

Finally! Your edits are finished, you've merged all changes from the server, and you're ready to commit your changes to the repository.

Finalmente! Le modifiche sono finite, sono stati presi tutti i cambiamenti dal server e si è pronti ad eseguire la commit delle modifiche fatte sul repository.

The svn commit command sends all of your changes to the repository. When you commit a change, you need to supply a log message, describing your change. Your log message will be attached to the new revision you create. If your log message is brief, you may wish to supply it on the command line using the --message (or -m) option:

Il comando svn commit invia tutte le modifiche al repository. Quando si fa la commit di una modifica bisogna aggiungere un messaggio di log , che descriva il cambiamento. Il messaggio di log sarà allegato alla nuova revisione appena creata. Se il messaggio di log è breve, è possibile aggiungerlo da riga di comando usando l'opzione --message (o -m):

$ svn commit --message "Corrected number of cheese slices."
Sending        sandwich.txt
Transmitting file data .
Committed revision 3.

However, if you've been composing your log message as you work, you may want to tell Subversion to get the message from a file by passing the filename with the --file switch:

Comunque, se si è composto il messaggio di log durante il lavoro, è possibile comunicare a Subversion di prendere il messaggio da file passandogli il nome del file con l'opzione --file:

$ svn commit --file logmsg
Sending        sandwich.txt
Transmitting file data .
Committed revision 4.

If you fail to specify either the --message or --file switch, then Subversion will automatically launch your favorite editor (see the editor-cmd section in sezione chiamata «Config») for composing a log message.

Se ci si dimentica di specificare una delle due opzioni --message o --file, Subversion lancia automaticamente il proprio editor preferito (si veda la sezione editor-cmd in sezione chiamata «Config») per comporre un messaggio di log.

[Suggerimento] Suggerimento

If you're in your editor writing a commit message and decide that you want to cancel your commit, you can just quit your editor without saving changes. If you've already saved your commit message, simply delete the text and save again.

Se si sta compilando con il proprio editor un messaggio di commit e si decide di annullare la commit, basta chiudere l'editor senza salvare le modifiche. Se si è già salvato il messaggio di commit, basta cancellare il testo e salvare di nuovo.

$ svn commit
Waiting for Emacs...Done

Log message unchanged or not specified
a)bort, c)ontinue, e)dit
a
$

The repository doesn't know or care if your changes make any sense as a whole; it only checks to make sure that nobody else has changed any of the same files that you did when you weren't looking. If somebody has done that, the entire commit will fail with a message informing you that one or more of your files is out-of-date:

Il repository non sa e non è interessato al fatto che le modifiche apportate abbiano un senso; si assicura soltanto che nessun altro abbia modificato qualcosa degli stessi file senza accorgersene. Se qualcuno l'ha fatto l'intero commit fallirà e un messaggio informerà che uno o più file non sono aggiornati:

$ svn commit --message "Add another rule"
Sending        rules.txt
svn: Commit failed (details follow):
svn: Out of date: 'rules.txt' in transaction 'g'

At this point, you need to run svn update, deal with any merges or conflicts that result, and attempt your commit again.

A questo punto bisogna eseguire il comando svn update, gestire conflitti e fusioni risultanti ed eseguire la commit di nuovo.

That covers the basic work cycle for using Subversion. There are many other features in Subversion that you can use to manage your repository and working copy, but you can get by quite easily using only the commands that we've discussed so far in this chapter.

Questo conclude il ciclo base di lavoro per usare Subversion. Ci sono molte altre caratteristiche in Subversion che possono essere usate per gestire il repository e la copia di lavoro, ma si può procedere facilmente usando solo i comandi che sono stati discussi in precedenza in questo capitolo.



[5] Of course, nothing is ever totally deleted from the repository—just from the HEAD of the repository. You can get back anything you delete by checking out (or updating your working copy) a revision earlier than the one in which you deleted it.

[6] Naturalmente niente viene completamente cancellato dal repository — ma solo dalla testa del repository. Si può ritrovare tutto quello che si è cancellato facendo checkout (o l'update della copia di lavoro) ad una versione precedente a quella in cui si è fatta la cancellazione.

[7] Subversion uses its internal diff engine, which produces unified diff format, by default. If you want diff output in a different format, specify an external diff program using --diff-cmd and pass any flags you'd like to it using the --extensions switch. For example, to see local differences in file foo.c in context output format while ignoring whitespace changes, you might run svn diff --diff-cmd /usr/bin/diff --extensions '-bc' foo.c.

[8] Subversion calcola le differenze utilizzando il suo algoritmo interno che predefinitamente produce un formato unificato diff. Se si vuole utilizzare un formato diverso, bisogna specificare un programma diff esterno usando l'opzione --diff-cmd e passando tutti i flag necessari con l'opzione --extensions. Per esempio, per vedere le differenze locali nel file foo.c in un formato di stampa che ignori le modifiche degli spazi bianchi, si può usare il comando svn diff --diff-cmd /usr/bin/diff --extensions '-bc' foo.c.

[9] You can always remove the temporary files yourself, but would you really want to do that when Subversion can do it for you? We didn't think so.

[10] Si possono sempre rimuovere i file autonomamente, ma perché farlo se Subversion può farlo al nostro posto? Non la pensavamo così.

[11] And if you ask them for it, they may very well ride you out of town on a rail.

[12] E se gielo chiedi ti manderebbero fuori città su un treno.