Sacando el mayor partido al Git en GNOME
Contents
Introducción
Git es un método poderoso de permitir a muchos desarrolladores trabajar con el mismo código fuente. Se utiliza ampliamente en el proyecto GNOME y, a menudo resulta ser el primer obstáculo para los nuevos desarrolladores que se sienten atraídos por el proyecto GNOME.
Cada desarrollador clona una copia del repositorio del código fuente de Git y luego es capaz de trabajar en su copia personal por separado de otros desarrolladores. Cuando se han realizado cambios, se confirman a nivel local. Después de que ellos están satisfechos con sus confirmaciones se empujan de vuelta al repositorio Git. De esta manera una serie de confirmaciones pueden ser preparadas y probadas a nivel local y luego empujarlas como un evento único.
Con git todo el mundo tiene a su disposición todas las herramientas y pueden hacer lo que quieran con su copia local. Además, casi todas las operaciones son locales, por lo que son rápidas y se pueden realizar sin conexión con el repositorio original.
El proyecto GNOME ha creado también la búsqueda online de su repositorio Git.
Si te gustaría seguir los cambios de lo que ocurre en varios proyectos Git GNOME, suscríbet a la lista de correo de git-commits-list, un alto volumen, la lista de solo lectura que recibe el correo cada vez que alguien envie algo en el repositorio. Puede aplicar un filtro de correo de esta lista por el título de los proyectos que se interese.
Configuración de Git
Lo primero que debes hacer es configurar git para saber quién eres:
git config --global user.name "Rupert Monkey" git config --global user.email rupert@example.com
Puedes omitir --global para cambiarlo para un repositorio único de sólo comprobación.
Si te gustan bastante los colores en tu salida del terminal, puedes habilitarlos también:
git config --global color.ui auto
o
git config --global color.diff auto git config --global color.status auto git config --global color.branch auto
Si después de cambiar a lindos colores, en su lugar ves basura en tu salida, puede que tengas que añadir esta línea a su ~/.bashrc
export LESS=-R
Consiguiendo el código
Acceso anónimo
Para clonar toda la historia y ramas de un proyecto, desde una consola:
git clone git://git.gnome.org/[proyecto]
Deberías reemplazar [proyecto] con el nombre del proyecto que tu quieras. Si quieres que la salida se ponga en una carpeta que no sea la misma que el nombre de proyecto, especifica tu propia carpeta como un segundo argumento a git clone.
Acceso desarrollador
Los desarrolladores GNOME registrados pueden usar su llave SHH para autentificarse ellos mismos en el servidor GIt pro eso ellos pueden empujar muchos cambios de vuelta a los repositorios Git. Ellos usan una URL ligereamente diferente para clonar y tratar con los proyectos Git:
git clone ssh://[login@]git.gnome.org/git/[proyecto]
En este caso, si tu acceso local no es elmismo que tu acceso desarrollador de GNOME, necesitarás especificarlo en el a URL.
Una alternativa para suministrarte tu acceso desarrollador GNOME directamente en la URL es configurar tu SSH para automaticamente suministrarlo cuando se haga un intento de conexión al servidor git.gnome.org. Para hacerlo, simplemente incluye lo siguiente en ~/.ssh/config :
Host git.gnome.org User [login] Compression yes CompressionLevel 3
gnome: clone alias
Desde que todos los módulos de gnome tiene un prefijo url común, puede ser conveniente establecer un clone alias:
git config --global url.ssh://[login@]git.gnome.org/git/.enlugarde gnome:
Entonces la linea clonada llega a ser mucho más breve:
git clone gnome:[proyecto]
Archivos comunes
Cuando el clon haya sido completado, empezaras a notar que muchos proyectos en el Git de GNOME contienen muchos archivos similares:
- .git: este directorio esta presente el el directorio raíz de un proyecto dado. Contiene la información sobre los números de verios, desde donde vino el código, etc. Puede ignorarlo para todos los propósitos, pero no deberías borrarlo.
- autogen.sh: este es un script que envuelve a gettextize, intltoolize, libtoolize, aclocal, autoheader, automake y autoconf que usaras para empezar a construir el proyecto. Por ejemplo
./autogen.sh --prefix=/usr/local empezará el proceso de construcción comprobando tu sistema, generando todos los Makefiles necesarios antes de que estés listo para escribir 'make' y 'make install'.
- README: This generally gives information about the Git project in terms of project requirements, where to report bugs etc..
- HACKING: This file usually specifies the rules [if any] for development in the project.
- MAINTAINERS: This file lists the people who are responsible for the day to day maintenance of the project. Generally these are the people you should send patches to.
Usando ramas
Git allows you to isolate changes onto a separate line of development, known as a branch. Quite often in GNOME, there are stable and unstable branches of development for a given project - as a result, the main branch [also known as 'master'] may not be suitable for your needs. Stable branches in GNOME Git are generally a mixture of lowercase alphabetic and numeric characters separated by dashes ie. of the form:
[proyecto]-[MAYOR]-[MENOR]
donde mayor, menos son números de versiones. Por ejemplo:
gnome-2-0 gtk-2-0
In Git, branches and tags are simply references to a commit. For a list of the available local branches for a given project you can use:
git branch
Listando ramas
Para una lista de las ramas remotas disponibles para un proyecto dado puedes usar:
git branch -r
Comprobando una rama
Puedes comprobar una rama local existente usando el siguiente comando:
git checkout -b [branch name] origin/[branch name]
That specifies a local branch that will be created, to track the remote (origin/) branch. You must use a local branch, and you must give it the same name as the remote branch, or things will get very complicated when you try to push your commits later. If you do it as we show here, then a simple "git push" will work.
Note that before switching branches your working tree must be clean. If it is not, you can stash your changes (explained below) or commit them temporarily.
The following example will check out gnome-utils master and then check out the 'gnome-2-26' branch:
$ git clone git://git.gnome.org/gnome-utils $ cd gnome-utils $ git checkout -b gnome-2-26 origin/gnome-2-26
Creando ramas
Ver #Branching sobre crear ramas remotas en git.gnome.org.
Ramas locales
TODO: Explain what local branches are.
You can create a local branch using:
git branch my-branch
You can create a local branch tracking a remote branch by using:
git branch my-branch origin/my-branch
You can create a new branch and check out it at the same time with:
git checkout -b my-branch origin/my-branch
- If you have a version of git greater than 1.6.1 you can also use:
git checkout --track origin/my-branch
which will create a local branch called my-branch tracking the origin/my-branch remote branch.
- If you already created a local branch you can switch easily between them using:
# Switch to my-branch git checkout my-branch # Switch back to master git checkout master
Usando etiquetas
Maintainers 'tag' their projects in GNOME Git to mark releases. Tags in GNOME Git are generally a mixture of uppercase alphabetic and numeric characters separated by underscores ie. of the form
[PROJECT]_[MAJOR]_[MINOR]_[MICRO]
where MAJOR, MINOR and MICRO are version numbers. For example
GTK_2_0_6 GNOME_UTILS_2_0_2
Listando etiquetas
Para una lista de todas las etiquetas disponibles para un proyecto dado:
git tag -l
As all the data is local you can examine the history very fast. To see the history up to the current revision:
git log -p gitk
where the '-p' is to see the patch and the last one is a graphical viewer.
Consiguiendo cambios
Git is designed so that whenever there were any changes in the source code, you don't need to remove your sources and re-check out. The following command syncs up your code with what is stored in the Git repository
git pull --rebase
When you pull, you will notice a summary of the changes transferred (updated/new branches and tags) and a diffstat of the changes applied to your working copy. If you have local commits then the --rebase option will ensure that your local commits will first be removed temporarily, then the new changes from the remote git repository are fetched and applied, after which your local commits are reapplied on top of the new changes. If you do not use --rebase and you have local commits, your local commits will be merged with the new changes introducing a new commit which is often undesired.
Escondiendo los cambios locales
If you have conflicting changes in your working copy the changes will not be applied. You can stash them first, do the pull, and apply you changes again with:
git stash git pull --rebase git stash pop
If you still have conflicts, you must resolve these, in general, before being able to rebuild the source code.
Check the output of 'git status' to know in which stage is each file and what you can do.
Note: The pull command should do what is called a fast-forward - that is, just update to a later revision.
Contribuyendo con parches
Now that you have successfully checked out a GNOME Git project and hopefully managed to build it, you are ready to move forward and become a GNOME contributor.
GNOME contributors send 'patches' [sometimes called 'diffs'] to each other and attach them to bug reports in bugzilla.gnome.org. A 'patch' describes changes in some files. Generally, you will use git format-patch to create a patch suitable for mailing or attaching to bugzilla, which looks like:
From 5eaf4b1061621ba5bc3157777f749237150b4cc8 Mon Sep 17 00:00:00 2001 From: Joe Bloggs <joe.bloggs@gnome.org> Date: Fri, 17 Apr 2009 12:35:45 -0700 Subject: [PATCH] Add myself to AUTHORS. Fixes bug #12345. --- AUTHORS | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) diff --git a/AUTHORS b/AUTHORS index 15c2e37..12731aa 100644 --- a/AUTHORS +++ b/AUTHORS @@ -8,3 +8,4 @@ Sandy Armstrong <sanfordarmstrong@gmail.com> Sebastian Rittau <srittau@jroger.in-berlin.de> Kevin Kubasik <kevin@kubasik.net> Stefan Schweizer <steve.schweizer@gmail.com> +Joe Bloggs <joe.bloggs@gnome.org> -- 1.6.2.1
Here you can see the lines added prepended with a '+'. If you had removed [or edited] a line of code, you would have been likely to see a line prepended with '-'. Notice it also shows you the revision of the file you are creating a patch against (in the index line). Because you created the patch with git format-patch, your name and email address show up along with your commit message.
Once you make changes to some given files you can generate a patch very easily.
First, see which files you've modified with git status, which should have output like:
# On branch master # Changed but not updated: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: AUTHORS # no changes added to commit (use "git add" and/or "git commit -a")
Here you can see the the "AUTHORS" file is modified, and that if you want to undo your change, you can use git checkout -- AUTHORS.
If you want to see the actual changes of the modified files, you can with:
git diff [files]
Then you have to commit your changes with:
git commit [files]
where [files] are the files that have changed, or use '-a' to commit all the changes. When committing changes into git, please use the guidelines for commit messages.
After committing, you can use the git-bz extension to git to submit a bug directly to bugzilla.gnome.org:
git-bz file product/component HEAD
Substitute product and component with the Bugzilla identifiers, like gnome-panel/general. Or you can can generate a patch file manually with:
git format-patch HEAD^
- This makes a patch out of your last commit, including the changes, the commit message, and your contact information.
Note: If your patch is big or does many different things you may want to split it to make the review easier.
Aplicando parches
If you are the one that gets sent a 'patch', then you can apply the commit in the patch with the following command:
git am [patch]
- If you have a patch based on an old version of the project and you want to update it to the current version you can do it with:
git pull --rebase
- Note that you may need to resolve some conflicts and commit afterwards.
Remember that git is a very flexible tool, and there are many different ways to use it. The above workflow is convenient for working on small patches, or for those who are just getting started with git.
Publicando tu árbol
If you are working on a large change, or need to make your patches available frequently, you may want to publish your tree somewhere where other people can clone from it.
Publishing your tree on github
github is a free (but not libre) web-based git hosting service. To publish a GNOME git tree to github:
Create an "Open Source" account, at http://github.com/signup/free. (Free accounts only let you create public source code repositories; paid accounts let you create private repos as well.)
After creating your account, click the link marked "(create a new one)" next to "Your repositories".
- Fill in the name and description, and click "Create Repository".
- It will then give you instructions on how to fill in your repository; however, since you are going to be pulling from git.gnome.org but pushing to github.com, you need to do something slightly different from what they say:
- Look at the directions under "Existing Git Repo?"
cd to your git checkout, and copy the git remote add command from the git page, but change "origin" to "github"
to push all of your local branches to github, type: git push --all github
Now you can continue to pull and merge changes from git.gnome.org as described above, and create as many local branches as you want, and just do "git push --all github" to push all of your branches to github, where other developers can see them, and clone their own copies of your repository.
Publicando tu árbol en Gitorious
Gitorious is another free web-based git hosting service, which is also AGPL-licensed and can thus be installed on other servers as well.
FIXME. Fill in instructions on using Gitorious
Increased Trust: Pushing your changes upstream
As you supply more and more patches to a given maintainer, or attach them to bugs in bugzilla.gnome.org, the maintainer may ask you to obtain your own Git account to make your own source code check ins. To push your local commits back to the central repository, you would typically:
git pull --rebase
check that everything looks OK, test it,... You can also check what would be pushed with:
git push --dry-run
to finally push the new commits with:
git push
If you do not pull beforehand, and changes have occurred that you never pulled, you may receive an error when you try to push. So, it is always best to pull before you push.
To apply for your own Git account, please read the New Account instructions.
Git, by default, pushes all the local branches which exist also in the remote repository. That may not be what you want so git displays this warning:
warning: You did not specify any refspecs to push, and the current remote warning: has not configured any push refspecs. The default action in this warning: case is to push all matching refspecs, that is, all branches warning: that exist both locally and remotely will be updated. This may warning: not necessarily be what you want to happen. warning: warning: You can specify what action you want to take in this case, and warning: avoid seeing this message again, by configuring 'push.default' to: warning: 'nothing' : Do not push anything warning: 'matching' : Push all matching branches (default) warning: 'tracking' : Push the current branch to whatever it is tracking warning: 'current' : Push the current branch
(comment: is it advisable to change push.default?) To only push the current branch to the remote repository use:
git push origin HEAD
or configure the remote to push only the current branch with:
git config remote.origin.push HEAD
Trabajando como un mantenedor de un módulo
With an increased amount of trust and responsibility, you may even be asked to start maintaining a project within GNOME Git - or indeed, one of your own that you may have imported.
Committing on behalf of a contributor
When committing code on behalf of others use the --author option, e.g.:
git commit -a --author "Joe Coder <joe@coder.org>"
This makes it easier to know who has contributed the code. You will still appear as committer.
Liberando
Maintainers must make tarball releases of their projects. This is well-documented at MaintainersCorner/Releasing.
Branching
At some point, you will need to branch your project for a stable set of releases, while continuing development on master; this works very much like tagging. This is documented at MaintainersCorner#branches.
Please make sure to read MaintainersCorner to familiarize yourself with other requirements of maintainers, including how to create Git/NewRepository.
Referencias
A good git cheat sheet is available from here.