igor@324: \chapter{Administración de Versiones y desarrollo ramificado} igor@324: \label{chap:branch} igor@324: igor@324: Mercurial ofrece varios mecanismos que le permitirán administrar un igor@324: proyecto que avanza en múltiples frentes simultáneamente. Para igor@324: entender estos mecanismos, demos un vistazo a la estructura usual de igor@324: un proyecto de software. igor@324: igor@324: Muchos proyectos de software liberan una versión``mayor'' que contiene igor@324: nuevas características substanciales. En paralelo, pueden liberar igor@324: versiones ``menores''. Estas usualmente son idénticas a las igor@324: versiones mayores en las cuales están basadas, pero con arreglo de igor@324: algunos fallos. igor@324: igor@324: En este capítulo, comenzaremos hablando de cómo mantener registro de igor@324: las etapas del proyecto como las liberaciones de una igor@324: versión. Continuaremos hablando del flujo de trabajo entre las igor@324: diferentes fases de un proyecto, y como puede ayudar Mercurial a igor@324: independizar y administrar tal trabajo. igor@324: igor@324: \section{Dar un nombre persistente a una revisión} igor@324: igor@324: Cuando se decide a otorgar a una revisión el nombre particular de una igor@324: ``versión'', es buena idea grabar la identidad para tal revisión. igor@324: Lo cual permitirá reproducir tal versión en una fecha posterior, o el igor@324: propósito que se considere en ese momento (reproducir un fallo, portar igor@324: a una nueva plataforma, etc). igor@324: \interaction{tag.init} igor@324: igor@324: Mercurial le permite dar un nombre permanente a cualquier revisión igor@324: usando la orden \hgcmd{tag}. Sin causa de sorpresa, esos nombres se llaman igor@324: ``tags''(etiquetas). igor@324: \interaction{tag.tag} igor@324: igor@324: Un tag no es más que un ``nombre simbólico'' para una revisión. Los igor@324: tags existen únicamente para su conveniencia, dotándolo de una forma igor@324: permanente y sencilla para referirse a una revisión; Mercurial no igor@324: interpreta de ninguna manera los nombres de los tags que usted use. igor@324: Mercurial tampoco impone restricción alguna al nombre de un tag, más igor@324: allá de lo necesario para asegurar que un tag puede parsearse sin igor@324: ambigüedades. El nombre de un tag no puede tener ninguno de los igor@324: caracteres siguientes: igor@324: \begin{itemize} igor@324: \item Dos puntos (ASCII 58, ``\texttt{:}'') igor@324: \item Retroceso (return) (ASCII 13, ``\Verb+\r+'') igor@324: \item Nueva línea (ASCII 10, ``\Verb+\n+'') igor@324: \end{itemize} igor@324: igor@324: Puede usar la orden \hgcmd{tags} para observar los tags presentes en igor@324: su repositorio. Al desplegarse, cada revisión marcada se identifica igor@324: primero con su nombre, después el número de revisión y finalmente con igor@324: un hash único de la revisión. igor@324: \interaction{tag.tags} igor@324: Note que \texttt{tip} aparece en la lista de \hgcmd{tags}. El tag igor@324: \texttt{tip} es un tag ``flotante'' especial, que identifica siempre igor@324: la revisión más nueva en el repositorio. igor@324: igor@324: Al desplegar la orden \hgcmd{tags}, los tags se listan en orden igor@324: inverso, por número de revisión. Lo que significa usualmente que los igor@324: tags más recientes se listan antes que los más antiguos. También igor@324: significa que el tag \texttt{tip} siempre aparecerá como primer tag igor@324: listado al desplegar la orden \hgcmd{tags}. igor@324: igor@324: Cuando ejecuta \hgcmd{log}, se desplegará la revisión que tenga los igor@324: tags asociados a ella, se imprimirán tales tags. igor@324: \interaction{tag.log} igor@324: igor@324: Siempre que requiera indicar un ~ID de revisión a una Orden de igor@324: Mercurial, aceptará un nombre de tag en su lugar. Internamente, igor@324: Mercurial traducirá su nombre de tag en el ~ID de revisión igor@324: correspondiente, y lo usará. igor@324: \interaction{tag.log.v1.0} igor@324: igor@330: No hay límites en la cantidad de tags por reposirorio, o la cantidad igor@330: de tags que una misma revisión pueda tener. Siendo prácticos, no es igor@330: muy buena idea tener ``demasiados'' (la cantidad variará de un igor@330: proyecto a otro), debido a que la intención es ayudarle a encontrar igor@330: revisiones. Si tiene demasiados tags, la facilidad para identificar igor@330: revisiones disminuirá rápidamente. igor@330: igor@330: Por ejemplo, si su proyecto tiene etapas(milestones) frecuentes en pocos igor@330: días, es perfectamente razonable asignarle un tag a cada una de igor@330: ellas. Pero si tiene un sistema de construcción automática de binarios igor@330: que asegura que cada revisión puede generarse limpiamente, estaría igor@330: introduciendo mucho ruido si se usara un tag para cada generación igor@330: exitosa. Más bien, podría usar tags para generaciones fallidas (en igor@330: caso de que estas sean raras!), o simplemente evitar los tags para igor@330: llevar cuenta de la posibilidad de generación de binarios. igor@330: igor@324: igor@331: Si desea eliminar un tag que no desea, use igor@324: \hgcmdargs{tag}{--remove}. igor@324: \interaction{tag.remove} igor@331: También puede modificar un tag en cualquier momento para que igor@331: identifique una revisión distinta, basta con aplicar una nueva orden igor@331: \hgcmd{tag}. Deberá usar la opción \hgopt{tag}{-f} para indicarle a igor@331: Mercurial que desea actualizar el tag \emph{en serio}. igor@324: \interaction{tag.replace} igor@331: De todas maneras habrá un registro permanente de la antigua identidad igor@331: del tag, pero Mercurial no la usará. Por lo tanto no hay castigo al igor@331: marcar con un tag una revisión incorrecta; lo único que debe hacer es igor@331: mover el tag hacia la revisión correcta tan pronto como localice el igor@331: error. igor@331: igor@331: Mercurial almacena los tags en un archivo controlado por revisiones en igor@331: su repositorio. Si ha creado tags, los encontrará en un archivo igor@331: llamado \sfilename{.hgtags}. Cuando invoca la orden \hgcmd{tag}, igor@331: Mercurial modifica este archivo, y automáticamente hace commit del igor@331: cambio al mismo. Esto significa que cada vez que ejecuta \hgcmd{tag}, igor@331: verá el conjunto de cambios correspondiente en la salida de \hgcmd{log}. igor@324: \interaction{tag.tip} igor@324: igor@331: \subsection{Manejo de conflictos entre tags durante una fusión} igor@331: igor@331: Es usual no tener que preocuparse por el archivo \sfilename{.hgtags}, igor@331: pero aveces hace su aparición durante una fusión. El formato del igor@331: archivo es sencillo: Consiste de una serie de líneas. Cada línea igor@331: comienza con un hash de Conjunto de Cambios, seguido por un espacio, igor@331: seguido por el nombre de un tag. igor@331: igor@331: Si está resolviendo un conflicto en el archivo \sfilename{.hgtags} igor@331: durante una fusión, hay un detalle para tener en cuenta al modificar igor@331: el archivo \sfilename{.hgtags}: igor@331: cuando Mercurial parsea los tags en el repositorio \emph{nunca} igor@331: lee la copia de trabajo del archivo \sfilename{.hgtags}. En cambio, igor@331: lee la versión \emph{consignada más reciente} del archivo. igor@331: igor@331: Una consecuencia desafortunada de este diseño es que usted no puede igor@331: verificar que su archivo \sfilename{.hgtags} fusionado es correcto hasta igor@331: \emph{después} de haber consignado(hecho commit). Así que si se igor@331: encuentra resolviendo un conflicto en \sfilename{.hgtags} durante una igor@331: fusión, asegúrese de ejecutar la orden \hgcmd{tags} después de igor@331: consignar. Si encuentra un error en el archivo \sfilename{.hgtags}, igor@331: reportará el lugar del error, que podrá arreglar y después igor@331: consignar. Posteriormente ejecute de nuevo la orden \hgcmd{tags} para igor@331: asegurar que su arreglo fue correctamente aplicado. igor@331: igor@331: \subsection{Tags y clonado} igor@331: igor@331: Puede haber notado que la orden \hgcmd{clone} tiene la opción igor@331: \hgopt{clone}{-r} que le permite clonar una copia exacta del igor@331: repositorio hasta un conjunto de cambios específico. El nuevo clon no igor@331: tendrá historia posterior a la revisión que usted haya igor@331: especificado. Esta forma de interactuar puede sorprender a los igor@331: desprevenidos. igor@331: igor@331: Recuerde que un tag se almacena como una revisión al archivo igor@331: \sfilename{.hgtags}, consecuente con esto, cuando crea un tag, el igor@331: conjunto de cambios en el cual este se almacena necesariamente se igor@331: refiere a un conjunto de cambios anterior. Cuando ejecuta igor@331: \hgcmdargs{clone}{-r foo} para clonar un repositorio hasta el tag igor@331: \texttt{foo}, el nuevo clon \emph{no contendrá la historia que creo igor@331: el tag} que usó para clonar el repositorio. El resultado es que tendrá igor@331: exactamente el subconjunto correcto de la historia del proyecto en el igor@331: nuevo repositorio, pero, \emph{no} el tag que podría haber esperado. igor@331: igor@331: \subsection{Cuando los tags permanentes son demasiado} igor@331: igor@331: Dado que los tags de Mercurial están controlados por revisiones y se igor@331: llevan en la historia del proyecto, todas las personas involucradas igor@331: verán los tags que usted haya creado. El hecho de dar nombres a las igor@331: revisiones tiene usos más allá que simplemente hacer notar que la igor@331: revisión \texttt{4237e45506ee} es realmente \texttt{v2.0.2}. Si está igor@331: tratando de encontrar un bug sutil, posiblemente desearía colocar un igor@331: tag recordándole algo como ``Ana vió los síntomas con esta revisión''. igor@331: igor@331: Para estos casos, lo que posiblemente desearía serían tags igor@331: \emph{locales}. Puede crear un tag local con la opción \hgopt{tag}{-l} igor@331: de la orden \hgcmd{tag}. Esto guardará el tag en un archivo llamado igor@331: \sfilename{.hg/localtags}. A diferencia de \sfilename{.hgtags}, igor@331: \sfilename{.hg/localtags} no está controlado por revisiones. igor@331: Cualquier tag que usted cree usando \hgopt{tag}{-l} se mantendrá igor@331: localmente en el repositorio en el que esté trabajando en ese momento. igor@331: igor@331: \section{El flujo de cambios---El gran cuadro vs. el pequeño} igor@331: igor@331: Retomando lo mencionado en el comienzo de un capítulo, pensemos en el igor@331: hecho de que un proyecto tiene muchas piezas concurrentes de trabajo igor@331: en desarrollo al mismo tiempo. igor@331: igor@331: Puede haber prisa por una nueva versión ``principal''; Un nueva igor@331: versión con un rreglo de fallo a la última versión; y una versión de igor@331: ``mantenimiento correctivo'' a una versión antigua que ha entrado en igor@331: modo de mantenimiento. igor@331: igor@331: Usualmente la gente se refiere a esas direcciones igor@331: concurrentes de desarrollo es como ``ramas''. Aunque hemos visto que igor@331: en variadas ocasiones Mercurial trata a \emph{toda la historia} como igor@331: una serie de ramas y fusiones. Realmente lo que tenemos aquí es dos igor@331: ideas que se relacionan periféricamente, pero que en esencia comparten igor@331: un nombre. igor@324: \begin{itemize} igor@331: \item ``El gran cuadro'' Las ramas representan un barrido de la igor@331: evolución del proyecto; la gente les da nombres y hablan acerca de igor@331: ellas en sus conversaciones. igor@331: \item ``El cuadro pequeño'' Las ramas son artefactos de las igor@331: actividades diarias de al desarrollar y fusionar cambios. Exponen la igor@331: narrativa de cómo se desarrolló el código. igor@324: \end{itemize} igor@324: igor@331: \section{Administrar ramas en el gran cuadro en los repositorios} igor@324: igor@324: The easiest way to isolate a ``big picture'' branch in Mercurial is in igor@331: a dedicated repositorio. If you have an existing shared igor@331: repositorio---let's call it \texttt{myproject}---that reaches a ``1.0'' igor@324: milestone, you can start to prepare for future maintenance releases on igor@324: top of version~1.0 by tagging the revision from which you prepared igor@324: the~1.0 release. igor@324: \interaction{branch-repo.tag} igor@331: You can then clone a new shared \texttt{myproject-1.0.1} repositorio as igor@324: of that tag. igor@324: \interaction{branch-repo.clone} igor@324: igor@324: Afterwards, if someone needs to work on a bug fix that ought to go igor@324: into an upcoming~1.0.1 minor release, they clone the igor@331: \texttt{myproject-1.0.1} repositorio, make their changes, and push them igor@324: back. igor@324: \interaction{branch-repo.bugfix} igor@324: Meanwhile, development for the next major release can continue, igor@331: isolated and unabated, in the \texttt{myproject} repositorio. igor@324: \interaction{branch-repo.new} igor@324: igor@324: \section{Don't repeat yourself: merging across branches} igor@324: igor@324: In many cases, if you have a bug to fix on a maintenance branch, the igor@324: chances are good that the bug exists on your project's main branch igor@324: (and possibly other maintenance branches, too). It's a rare developer igor@324: who wants to fix the same bug multiple times, so let's look at a few igor@324: ways that Mercurial can help you to manage these bugfixes without igor@324: duplicating your work. igor@324: igor@324: In the simplest instance, all you need to do is pull changes from your igor@324: maintenance branch into your local clone of the target branch. igor@324: \interaction{branch-repo.pull} igor@324: You'll then need to merge the heads of the two branches, and push back igor@324: to the main branch. igor@324: \interaction{branch-repo.merge} igor@324: igor@331: \section{Naming branches within one repositorio} igor@331: igor@331: In most instances, isolating branches in repositorios is the right igor@324: approach. Its simplicity makes it easy to understand; and so it's igor@324: hard to make mistakes. There's a one-to-one relationship between igor@324: branches you're working in and directories on your system. This lets igor@324: you use normal (non-Mercurial-aware) tools to work on files within a igor@331: branch/repositorio. igor@324: igor@324: If you're more in the ``power user'' category (\emph{and} your igor@324: collaborators are too), there is an alternative way of handling igor@324: branches that you can consider. I've already mentioned the igor@324: human-level distinction between ``small picture'' and ``big picture'' igor@324: branches. While Mercurial works with multiple ``small picture'' igor@331: branches in a repositorio all the time (for example after you pull igor@324: changes in, but before you merge them), it can \emph{also} work with igor@324: multiple ``big picture'' branches. igor@324: igor@324: The key to working this way is that Mercurial lets you assign a igor@324: persistent \emph{name} to a branch. There always exists a branch igor@324: named \texttt{default}. Even before you start naming branches igor@324: yourself, you can find traces of the \texttt{default} branch if you igor@324: look for them. igor@324: igor@324: As an example, when you run the \hgcmd{commit} command, and it pops up igor@324: your editor so that you can enter a commit message, look for a line igor@324: that contains the text ``\texttt{HG: branch default}'' at the bottom. igor@324: This is telling you that your commit will occur on the branch named igor@324: \texttt{default}. igor@324: igor@324: To start working with named branches, use the \hgcmd{branches} igor@324: command. This command lists the named branches already present in igor@331: your repositorio, telling you which changeset is the tip of each. igor@324: \interaction{branch-named.branches} igor@324: Since you haven't created any named branches yet, the only one that igor@324: exists is \texttt{default}. igor@324: igor@324: To find out what the ``current'' branch is, run the \hgcmd{branch} igor@324: command, giving it no arguments. This tells you what branch the igor@324: parent of the current changeset is on. igor@324: \interaction{branch-named.branch} igor@324: igor@324: To create a new branch, run the \hgcmd{branch} command again. This igor@324: time, give it one argument: the name of the branch you want to create. igor@324: \interaction{branch-named.create} igor@324: igor@324: After you've created a branch, you might wonder what effect the igor@324: \hgcmd{branch} command has had. What do the \hgcmd{status} and igor@324: \hgcmd{tip} commands report? igor@324: \interaction{branch-named.status} igor@324: Nothing has changed in the working directory, and there's been no new igor@324: history created. As this suggests, running the \hgcmd{branch} command igor@324: has no permanent effect; it only tells Mercurial what branch name to igor@324: use the \emph{next} time you commit a changeset. igor@324: igor@324: When you commit a change, Mercurial records the name of the branch on igor@324: which you committed. Once you've switched from the \texttt{default} igor@324: branch to another and committed, you'll see the name of the new branch igor@324: show up in the output of \hgcmd{log}, \hgcmd{tip}, and other commands igor@324: that display the same kind of output. igor@324: \interaction{branch-named.commit} igor@324: The \hgcmd{log}-like commands will print the branch name of every igor@324: changeset that's not on the \texttt{default} branch. As a result, if igor@324: you never use named branches, you'll never see this information. igor@324: igor@324: Once you've named a branch and committed a change with that name, igor@324: every subsequent commit that descends from that change will inherit igor@324: the same branch name. You can change the name of a branch at any igor@324: time, using the \hgcmd{branch} command. igor@324: \interaction{branch-named.rebranch} igor@324: In practice, this is something you won't do very often, as branch igor@324: names tend to have fairly long lifetimes. (This isn't a rule, just an igor@324: observation.) igor@324: igor@331: \section{Dealing with multiple named branches in a repositorio} igor@331: igor@331: If you have more than one named branch in a repositorio, Mercurial will igor@324: remember the branch that your working directory on when you start a igor@324: command like \hgcmd{update} or \hgcmdargs{pull}{-u}. It will update igor@324: the working directory to the tip of this branch, no matter what the igor@324: ``repo-wide'' tip is. To update to a revision that's on a different igor@324: named branch, you may need to use the \hgopt{update}{-C} option to igor@324: \hgcmd{update}. igor@324: igor@324: This behaviour is a little subtle, so let's see it in action. First, igor@324: let's remind ourselves what branch we're currently on, and what igor@331: branches are in our repositorio. igor@324: \interaction{branch-named.parents} igor@324: We're on the \texttt{bar} branch, but there also exists an older igor@324: \hgcmd{foo} branch. igor@324: igor@324: We can \hgcmd{update} back and forth between the tips of the igor@324: \texttt{foo} and \texttt{bar} branches without needing to use the igor@324: \hgopt{update}{-C} option, because this only involves going backwards igor@324: and forwards linearly through our change history. igor@324: \interaction{branch-named.update-switchy} igor@324: igor@324: If we go back to the \texttt{foo} branch and then run \hgcmd{update}, igor@324: it will keep us on \texttt{foo}, not move us to the tip of igor@324: \texttt{bar}. igor@324: \interaction{branch-named.update-nothing} igor@324: igor@324: Committing a new change on the \texttt{foo} branch introduces a new igor@324: head. igor@324: \interaction{branch-named.foo-commit} igor@324: igor@324: \section{Branch names and merging} igor@324: igor@324: As you've probably noticed, merges in Mercurial are not symmetrical. igor@331: Let's say our repositorio has two heads, 17 and 23. If I igor@324: \hgcmd{update} to 17 and then \hgcmd{merge} with 23, Mercurial records igor@324: 17 as the first parent of the merge, and 23 as the second. Whereas if igor@324: I \hgcmd{update} to 23 and then \hgcmd{merge} with 17, it records 23 igor@324: as the first parent, and 17 as the second. igor@324: igor@324: This affects Mercurial's choice of branch name when you merge. After igor@324: a merge, Mercurial will retain the branch name of the first parent igor@324: when you commit the result of the merge. If your first parent's igor@324: branch name is \texttt{foo}, and you merge with \texttt{bar}, the igor@324: branch name will still be \texttt{foo} after you merge. igor@324: igor@331: It's not unusual for a repositorio to contain multiple heads, each with igor@324: the same branch name. Let's say I'm working on the \texttt{foo} igor@324: branch, and so are you. We commit different changes; I pull your igor@324: changes; I now have two heads, each claiming to be on the \texttt{foo} igor@324: branch. The result of a merge will be a single head on the igor@324: \texttt{foo} branch, as you might hope. igor@324: igor@324: But if I'm working on the \texttt{bar} branch, and I merge work from igor@324: the \texttt{foo} branch, the result will remain on the \texttt{bar} igor@324: branch. igor@324: \interaction{branch-named.merge} igor@324: igor@324: To give a more concrete example, if I'm working on the igor@324: \texttt{bleeding-edge} branch, and I want to bring in the latest fixes igor@324: from the \texttt{stable} branch, Mercurial will choose the ``right'' igor@324: (\texttt{bleeding-edge}) branch name when I pull and merge from igor@324: \texttt{stable}. igor@324: igor@324: \section{Branch naming is generally useful} igor@324: igor@324: You shouldn't think of named branches as applicable only to situations igor@324: where you have multiple long-lived branches cohabiting in a single igor@331: repositorio. They're very useful even in the one-branch-per-repositorio igor@324: case. igor@324: igor@324: In the simplest case, giving a name to each branch gives you a igor@324: permanent record of which branch a changeset originated on. This igor@324: gives you more context when you're trying to follow the history of a igor@324: long-lived branchy project. igor@324: igor@331: If you're working with shared repositorios, you can set up a igor@324: \hook{pretxnchangegroup} hook on each that will block incoming changes igor@324: that have the ``wrong'' branch name. This provides a simple, but igor@324: effective, defence against people accidentally pushing changes from a igor@324: ``bleeding edge'' branch to a ``stable'' branch. Such a hook might igor@324: look like this inside the shared repo's \hgrc. igor@324: \begin{codesample2} igor@324: [hooks] igor@324: pretxnchangegroup.branch = hg heads --template '{branches} ' | grep mybranch igor@324: \end{codesample2} igor@324: igor@324: %%% Local Variables: igor@324: %%% mode: latex igor@324: %%% TeX-master: "00book" igor@324: %%% End: