Gestión de repositorios Subversion (SVN)
Última actualización 30/07/09
En esta entrada vamos a ver que es exactamente un sistema de control de versiones (concretamente hablaremos de subversion), como crear repositorios y cómo usarlos. Hay mucha información por internet acerca de cómo manejar todas las funcionalidades de svn, pero quizás no tan integrada y breve como pretendo mostraros a continuación.
¿Qué es subversion?
Subversion es un sistema de contro de versiones de código abierto. Es decir, subversión maneja ficheros y directorios, y los cambios realizados en ellos a lo largo del tiempo. Esto te permite recuperar viejas versiones de tus datos o examinar la historia de cómo han ido cambiando tus datos. En cierta manera mucha gente piensa en un sistema de control de versiones como una pequeña “máquina del tiempo”.
Subversión puede operar a través de redes, lo que le permite ser usada por personas en diferentes ordenadores. En algún nivel, la habilidad necesaria para que varias personas modifiquen y gestionen el mismo conjunto de datos desde sus respectivas localizaciones fomenta la colaboración. El progreso puede ir más rápido sin un único conducto por el cual todas las modificaciones deban ocurrir. Y dado que el trabajo está versionado, no debes tener miedo de que los datos no vayan solo por un conducto, si algún cambio se ha realizado incorrectamente, solo tienes que deshacer dicho cambio.
Svn en su núcleo es un repositorio, que es un almacen central de datos. El repositorio almaneca información como un sistema de ficheros con forma de árbol – una jerarquía típica de ficheros y directorios. Cualquier número de clientes se conectan al repositorio, y leen o escriben dichos ficheros. Cuando escriben datos, un cliente hace que la información esté disponible para los otros, cuando se leen datos, el cliente recive la información a partir de otros.
Entonces, ¿Por qué es esto interesante? Hasta el momento, esto parece ser la definición de un típico servidor de ficheros. Y de hecho, el repositorio es un tipo de servidor de ficheros, pero no es su objetivo principal. Lo que hace al repositorio subversion espacial es que este recuerda todos los cambios realizados en él – todos los cambios a todos los ficheros, e incluso los cambios hechos al propio directorio, tales cómo la adición, eliminación y la reordenación de ficheros y directorios.
Instalación SVN
Para instalar un repositorio svn nos hace falta instalar los siguientes paquetes en nuestra distribución:
- subversion
- apache2
- apache2-utils
- libapache2-svn
El servidor no tiene porque ser apache2 necesariamente, pero es cómo voy a explicarlo aquí, ya que es uno de los servidores más usados del mundo. Además si usamos un servidor ssh la instalación de apache no será necesaria. Primero vamos a ver la forma de hacerlo con apache y finalmente veremos cómo hacer exactamente lo mismo con ssh.
Crear el repositorio
Normalmente apache tiene como directorio por defecto para montar los servicios en /etc/www, en nuestro caso, vamos a hacer que el directorio para los repositorios de svn esté en /var/svn (aunque podríamos hacerlo en un directorio local):
mkdir svn cd svn svnadmin create repo
Servir el repositorio con apache
Lo más sencillo es editar el fichero /etc/apache2/mods-available/dav_svn.conf. Tienes que añadir un bloque similar a éste:
<Location /svn/myrepo> DAV svn SVNPath /var/svn/repo </Location>
Location establece la ruta a escribir tras el host, y SVNPath representa la ruta en nuestro sistema de archivos local. Ahora hay que asegurarse de que el módulo DAV_SVN está activado. Normalmente estará activado automáticamente, pero si no es tu caso, se hace con:
a2enmod dav_svn
Hay que permitir que Apache pueda leer y escribir en el repositorio:
chown -R root.www-data /var/svn (si es en un directorio local root se reemplaza por el usuario) chmod -R g+rw /var/svn
Por último reiniciamos el servidor para que surtan efecto los cambios:
/etc/init.d/apache2 restart
El repositorio es accesible para clientes subversion, webdav o navegadores web convencionales, a través de:
http://example.com/svn/myrepo/
Con esto tendrás un repositorio completamente público. Todo el que quiera podrá acceder tanto para descargar como para subir ficheros. Como eso normalmente no es lo deseable, podemos crear también repositorios privados.
Repositorio privado
Si solo quieres que ciertos usuarios puedan acceder al repositorio tienes que realizar algunos camios en el fichero /etc/apache2/mods-available/dav_svn.conf:
<Location /svn/myrepo> DAV svn SVNPath /var/svn/repo AuthType Basic AuthName "My Repository" AuthUserFile /etc/apache2/dav_svn.passwd Require valid-user </Location>
La sintaxis es análoga a la que se utiliza en Apache para restringir el acceso a un directorio. El fichero /etc/apache2/dav_svn.passwd es un fichero de claves típico de Apache. Para añadir usuarios utiliza el método habitual:
# htpasswd2 /etc/apache2/dav_svn.passw usuario
En este caso es muy recomendable habilidar SSL en el servidor Apache, pues de otro modo la contraseña viajaría ‘en claro’ a través de la red.
Acceso restringido
Otra posibilidad (muy común en el mundo del software libre) es tener un repositorio accesible para todo el mundo, pero sólo modificable por ciertos usuarios. En este caso la configuración sería algo como:
<Location /svn/myrepo>
DAV svn
SVNPath /var/svn/repo
AuthType Basic
AuthName "My Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
<LimitExcept GET PROPFIND OPTIONS REPORT>
Require valid-user
</LimitExcept>
</Location>
Con SSH
Si disponemos de un servidor SSH no será necesario instalar apache y además no necesitaremos realizar ninguno de los pasos explicados hasta ahora excepto el paso “Creación del repositorio”. En los siguientes pasos explicaré las dos formas de trabajar.
Crear un módulo
Cuando se comienza un nuevo desarrollo es necesario crear un nuevo módulo en el repositorio (algo similar a un directorio en el sistema de ficheros local). Para ello, supondremos que ya existe un repositorio accesible en http://example.com/repos. Tienes que ejecutar algo similar a:
$ svn import /home/user/job http://example.com/repos/myjob (APACHE) $ svn import /home/user/job svn+ssh://usuario@host/ruta (SSH) $ svn import /home/user/job file://localhost/ruta (Local)
Siendo job el directorio que contiene los ficheros del nuevo proyecto. Esto creará el módulo myjob en el repositorio repos del host example.com y subirá allí el contenido de /home/user/job, creando así la versión inicial. Justo después de poner este comando nos aparecerá nuestro editor por defecto del sistema (normalmente vim o nano) para que escribamos, si queremos, una descripción del proyecto que estamos subiendo. En cuanto guardamos y cerremos este fichero se creará la versión inicial del proyecto.
Descargar un módulo
Esta es la operación más habitual y también una de las más simples:
$ svn checkout http://example.com/repo/anotherjob (APACHE) $ svn checkout svn+ssh://example.com/repo/anotherjob (SSH) $ svn checkout file://localhost/ruta (Local)
Esto obtiene la úitima copia del módulo anotherjob. Crea un directorio con el mismo nombre en el directorio actual. En vez de checkout también podemos poner co.
Actualizar una copia local
Suponiendo que haya nuevas versiones disponibles del módulo del ejemplo anterior, puedes actualizar tu copia a la última versión con:
$ svn update
Desde el directorio de trabajo.
Añadir un fichero
Si has creado un fichero nuevo en el módulo dentro en tu sistema de ficheros local, y quieres que esté en el repositorio tienes que añadirlo explícitamente. Recuerda que un repositorio está pensado para “fuentes” (no binarios). No subas nada que se pueda generar a partir de otros ficheros. Nada de binarios, ficheros objeto, copias de seguridad, pdf o cualquier cosa que se pueda obtener como resultado de una compilación.
$ svn add nuevo_fichero
Para añadir un directorio y todo su contenido recursivamente utilizamos la opción “–depth infinity”.
$ svn add --depth infinity directorio
Por ejemplo para un proyecto software que se genere mediante las autotools, la estructura de archivos que deberíamos subir es la siguiente:
-rwxr-xr-x 1 pipo pipo 45153 2008-11-29 12:49 autogen.sh -rw-r--r-- 1 pipo pipo 2 2008-11-29 12:50 ChangeLog -rw-r--r-- 1 pipo pipo 609 2008-11-29 12:50 configure.ac -rw-r--r-- 1 pipo pipo 35148 2008-11-29 12:50 COPYING drwxr-xr-x 3 pipo pipo 4096 2008-11-29 12:50 doc -rw-r--r-- 1 pipo pipo 9512 2008-11-29 12:50 INSTALL -rw-r--r-- 1 pipo pipo 11007 2008-11-29 12:50 libguoctree.dox.in -rw-r--r-- 1 pipo pipo 373 2008-11-29 12:51 libguoctree.pc.in -rw-r--r-- 1 pipo pipo 866 2008-11-29 12:51 libguoctree.spec.in -rw-r--r-- 1 pipo pipo 912 2008-11-29 12:51 Makefile.am -rw-r--r-- 1 pipo pipo 0 2008-11-29 12:51 NEWS -rw-r--r-- 1 pipo pipo 282 2008-11-29 12:51 README drwxr-xr-x 4 pipo pipo 4096 2008-11-29 12:51 src drwxr-xr-x 4 pipo pipo 4096 2008-11-29 12:51 utils
Seguramente cualquier otro archivo que esté en el directorio del proyecto sea generado a partir de estos.
Eliminar un fichero
Al igual que podemos añadir ficheros a nuestro repositorio, podemos eliminarlos cuando ya no sean necesarios. Para ello ejecutamos el siguiente comando
$ svn delete dir/ruta-archivo
Mover fichero o directorio
Si nos apetece cambiar el nombre de un fichero o directorio se puede hacer fácilmente con la opción move:
$ svn move directorio/ nuevo-directorio
Subversion automáticamente crea el nuevo directorio, mueve todo el contenido del directorio viejo al nuevo y añade y elimina los archivos de las respectivas rutas.
Subir cambios locales al repositorio
Para subir los cambios, confirmar una adición o eliminación en el módulo en el que estamos trabajando se debe ejecutar el siguiente comando:
$ svn commit
Justo después de poner este comando nos aparecerá nuestro editor por defecto del sistema (normalmente vim o nano) para que escribamos, si queremos, una descripción de la transacción que estamos realizando, donde podemos hacer referencia a los ficheros que eliminamos o añadimos, a las modificaciones realizadas, etc. En cuanto guardamos y cerremos este fichero se realizará la transacción.
Log del repositorio
Para ver un log de los cambios realizados:
svn log
Listar archivos del repositorio
Para ver todos los archivos que forman parte de un repositorio:
svn list -vR http://svn.collab.net/repos/sv svn list -vR svn+ssh://svn.collab.net/repos/sv svn list -vR file://localhost/ruta
Crear una nueva rama (branch)
Si no quieres interferir en el trabajo de compañeros de trabajo, lo más seguro es crear una rama personal del directorio principal de trabajo (trunk)
svn copy trunk branches/piponazo
En este caso branches ya debería formar parte del repositorio, sino lo creamos. (Más información aquí).
Otros
Se pueden realizar muchas más acciones con svn, pero con las que aquí describo tenéis más que suficiente para empezar. En los siguientes enlaces tenéis información suficiente por si queréis ampliar conocimientos:
http://svnbook.red-bean.com/index.es.html
In this post we’ll see what exactly is a version control system (specifically I talk about subversion), how to create repositories and how to use it. The are a lot of information on Internet about how to manage all the features of svn, but perhaps not as integrated and brief as intend to show you below.
What Is Subversion?
Subversion is a free/open source version control system. That is, Subversion manages files and directories, and the changes made to them, over time. This allows you to recover older versions of your data or examine the history of how your data changed. In this regard, many people think of a version control system as a sort of “time machine.”
Subversion can operate across networks, which allows it to be used by people on different computers. At some level, the ability for various people to modify and manage the same set of data from their respective locations fosters collaboration. Progress can occur more quickly without a single conduit through which all modifications must occur. And because the work is versioned, you need not fear that quality is the trade-off for losing that conduit—if some incorrect change is made to the data, just undo that change.
Svn at its core is a repository, which is a central store of data. The repository stores information in the form of a filesystem tree—a typical hierarchy of files and directories. Any number of clients connect to the repository, and then read or write to these files. By writing data, a client makes the information available to others; by reading data, the client receives information from others.
So why is this interesting? So far, this sounds like the definition of a typical file server. And indeed, the repository is a kind of file server, but it’s not your usual breed. What makes the Subversion repository special is that it remembers every change ever written to it—every change to every file, and even changes to the directory tree itself, such as the addition, deletion, and rearrangement of files and directories.
When a client reads data from the repository, it normally sees only the latest version of the filesystem tree. But the client also has the ability to view previous states of the filesystem. For example, a client can ask historical questions such as “What did this directory contain last Wednesday?” and “Who was the last person to change this file, and what changes did he make?” These are the sorts of questions that are at the heart of any version control system: systems that are designed to track changes to data over time.
SVN Installation
To install a svn repository we need to install the following packages in our distribution:
- subversion
- apache2
- apache2-utils
- libapache2-svn
The server doesn’t have to be apache2 necessarily, but it¡s how I¡m going to explain it here, because it’s one of the world’s most widely used servers. Besides, if we use a ssh server, the installation of apache isn’t neccesary. In first place we’ll see the way to do this with apache and finally with ssh.
Create the reposiroty
Normally apache have the /etc/www folder as default folder to mount the web services, in our case, we’re going to set the /var/svn folder as default folder for the svn repositories (although we can do it with a local folder):
root@example:/var# mkdir svn root@example:/var# cd svn root@example:/var/svn# svnadmin create repo
Serve the repository with apache
The simplest way is to edit the /etc/apache2/mods-available/dav_svn.conf file. You have to add a block code like this:
<Location /svn/myrepo> DAV svn SVNPath /var/svn/repo </Location>
Location establishes the path to write behind the host, and SVNPath represents the path of our local filesystem.Now we must ensure that the DAV_SVN module is activated. Normally it will be activated, but if this is not your case, it’s done with:
# a2enmod dav_svn
We must allow Apache can read and write in the repository:
# chown -R root.www-data /var/svn (if it's a local folder, root is replaced to the user) # chmod -R g+rw /var/svn
Finally restart the server for the changes take effect
# /etc/init.d/apache2 restart
At this moment the repository is accessible for subversion clients, webdav or conventional web browsers, through:
http://example.com/svn/myrepo/
With these steps you’ll have a completely plublic repository. Anyone who wants will be able to access to download and upload files. As it usually isn’t desirable, we can also create private repositories.
Private repository
If you only want that certain users can access to the repository you have to make some changes in the /etc/apache2/mods-available/dav_svn.conf file:
<Location /svn/myrepo> DAV svn SVNPath /var/svn/repo AuthType Basic AuthName "My Repository" AuthUserFile /etc/apache2/dav_svn.passwd Require valid-user </Location>
The syntax is similar to that used in Apache to restrict access to a directory. The /etc/apache2/dav_svn.passwd file is a typical apache key file. To add users use the standard method:
# htpasswd2 /etc/apache2/dav_svn.passw usuario
In this case is highly recommended turn on SSL in the apache server, otherwise tha password will travel as “plain text” over the network.
Restricted Access
Another possibility (very common in the world of open source) is to have a accessible repository for everyone, but only editable for certain users. In this case the setup would be somehing like:
<Location /svn/myrepo>
DAV svn
SVNPath /var/svn/repo
AuthType Basic
AuthName "My Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
<LimitExcept GET PROPFIND OPTIONS REPORT>
Require valid-user
</LimitExcept>
</Location>
Using SSH
If we have a SSH server it isn’t neccesary to install apache and also don’t need to do any of the steps explained so far except the “Creation of the repository”. In the following steps I’ll explain the two ways of working.
Create a module
When starting a new development is neccessary to create a new module (something similar to a folder in the local filesystem). For tis purpose, we’ll assume that there is already an accessible repository in http://example.com/repos. You must execute a command lke this:
$ svn import /home/user/job http://example.com/repos/myjob (APACHE) $ svn import /home/user/job svn+ssh://user@host/path (SSH) $ svn import /home/user/job file://localhost/path (Local)
Being job the folder that contains the files of the new project. This will create the myjob module in the repos repository of the example.com host, and upload there the content of the /home/user/job folder, creating in this way the initial version. Just after we put this command appears our default text editor of the system (usually vim or nano) to wite , if we want, a description of the project that we are uploading. As we save and close the file it will create the initial version of the project.
Download a module
This is the most common operation and also one of the simplest:
$ svn checkout http://example.com/repo/anotherjob (APACHE) $ svn checkout svn+ssh://example.com/repo/anotherjob (SSH) $ svn checkout file://localhost/path (SSH)
This obtain the last version of the anotherjob module. It create a folder with the same name in the current folder. Instead of checkout we can type co too.
Upadte a local copy
Assuming that there are new available version of the module in the example above, you cad update your copy to the lastest version with:
$ svn update
From the working directory.
Add a file
If you created a new file in the module into your local filesystem, and want to be in the repository, you have to add it explicitly. Remember that a respository is designed to “sources” (not binaries). Don’t upload anything that can be generated from other files. None of binary, object files, backups, pdf, or anything that can be obtained as result of a compilation.
$ svn add nuevo_fichero
To add a directory and their contents recursively use the “–depth infinity” option.
$ svn add --depth infinity directorio
For instance, for a software project generated through the autotools, the file estructure we should upload is the next :
-rwxr-xr-x 1 pipo pipo 45153 2008-11-29 12:49 autogen.sh -rw-r--r-- 1 pipo pipo 2 2008-11-29 12:50 ChangeLog -rw-r--r-- 1 pipo pipo 609 2008-11-29 12:50 configure.ac -rw-r--r-- 1 pipo pipo 35148 2008-11-29 12:50 COPYING drwxr-xr-x 3 pipo pipo 4096 2008-11-29 12:50 doc -rw-r--r-- 1 pipo pipo 9512 2008-11-29 12:50 INSTALL -rw-r--r-- 1 pipo pipo 11007 2008-11-29 12:50 libguoctree.dox.in -rw-r--r-- 1 pipo pipo 373 2008-11-29 12:51 libguoctree.pc.in -rw-r--r-- 1 pipo pipo 866 2008-11-29 12:51 libguoctree.spec.in -rw-r--r-- 1 pipo pipo 912 2008-11-29 12:51 Makefile.am -rw-r--r-- 1 pipo pipo 0 2008-11-29 12:51 NEWS -rw-r--r-- 1 pipo pipo 282 2008-11-29 12:51 README drwxr-xr-x 4 pipo pipo 4096 2008-11-29 12:51 src drwxr-xr-x 4 pipo pipo 4096 2008-11-29 12:51 utils
Surely any other file on the project directory is generated from these.
Delete a file
In the same way that we can add files to our repository, we can remove them when they are no longer needed. To do this execute the next comand:
$ svn delete dir/ruta-archivo
Move files or directories
If we want to rename a file or directory can be done easily with the move option:
$ svn move directory/ new-directory
Subversion automatically creates the new directory, move all the content from the old directory to the new one, and add/delete files to/from the respective routes.
Upload local changes to the repository
To upload the changes, confirming an addition or deletion in the module in which we are working the following command must be executed:
$ svn commit
Just after we put this command our system default text editor will appear (usually vim or nano) to write, if we want, a description of the transaction we are doing, where we can refer to the files that we remove of add, to the changes made, and so on. As we save and close this file, the transaction will be performed. este fichero se realizará la transacción.
Log of the repository
To see the log of the changes made:
$ svn log
List all the files of the repository
To see the files contained in the repository:
$ svn list -vR http://svn.collab.net/repos/sv $ svn list -vR svn+ssh://svn.collab.net/repos/sv $ svn list -vR file://localhost/path
Create a new branch
If you don’t want interfere in the work of workmates, the most safe is to create a new personal branch of the main work directory (trunk)
svn copy trunk branches/piponazo
In this case branches should already form part of the repository, otherwise you must create it before. (More information here).
Other thins
Many more actions can be done with svn, but with which I describe here you have more that enought to start. In the following links you have enough information if you want to broaden kownledge:
loading...



loading...
Vaya pepinazo de post tío !! Esto tiene que ir directo a PDF como Howto imprescindible !
Un saludo,
loading...
Joder… impresionante tío… Esto tengo q madurarlo poquito a poco!
Un saludo!
loading...
Gracias por los comentarios chicos, aunque me he guiado en mucho del contenido por los links que he puesto ;). Saludos!