igor@374: \chapter{Encontrar y arreglar sus equivocaciones} jerojasro@343: \label{chap:undo} jerojasro@343: igor@374: Errar es humano, pero tratar adecuadamente las consecuencias requiere igor@374: un sistema de control de revisiones de primera categoría. En este igor@374: capítulo, discutiremos algunas técnicas que puede usar cuando igor@374: encuentra que hay un problema enraizado en su proyecto. Mercurial igor@374: tiene unas características poderosas que le ayudarán a isolar las igor@374: fuentes de los problemas, y a dar cuenta de ellas apropiadamente. igor@374: igor@374: \section{Borrar la historia local} igor@374: igor@374: \subsection{La consignación accidental} igor@374: igor@374: Tengo el problema ocasional, pero persistente de teclear más rápido de igor@374: lo que pienso, que aveces resulta en consignar un conjunto de cambios igor@374: incompleto o simplemente malo. En mi caso, el conjunto de cambios igor@378: incompleto consiste en que creé un nuevo fichero fuente, pero olvidé igor@374: hacerle \hgcmd{add}. Un conjunto de cambios``simplemente malo'' no es igor@374: tan común, pero sí resulta muy molesto. igor@374: igor@378: \subsection{Hacer rollback una transacción} jerojasro@343: \label{sec:undo:rollback} jerojasro@343: igor@374: En la sección~\ref{sec:concepts:txn}, mencioné que Mercurial trata igor@374: modificación a un repositorio como una \emph{transacción}. Cada vez igor@374: que consigna un conjunto de cambios o lo jala de otro repositorio, igor@378: Mercurial recuerda lo que hizo. Puede deshacer, o hacer \emph{roll back}\ndt{El significado igual que en los igor@378: ambientes de sistemas manejadores de bases de datos se refiere a igor@378: la atomicidad e integridad al devolver un conjunto de acciones que igor@378: permitan dejar el repositorio en un estado consistente previo}, igor@374: exactamente una de tales acciones usando la orden \hgcmd{rollback}. igor@374: (Ver en la sección~\ref{sec:undo:rollback-after-push} una anotación igor@374: importante acerca del uso de esta orden.) igor@374: igor@374: A continuación una equivocación que me sucede frecuentemente: igor@374: consignar un cambio en el cual he creado un nuevo fichero, pero he igor@374: olvidado hacerle \hgcmd{add}. jerojasro@343: \interaction{rollback.commit} igor@374: La salida de \hgcmd{status} después de la consignación confirma igor@374: inmediatamente este error. jerojasro@343: \interaction{rollback.status} igor@378: La consignación capturó los cambios en el fichero \filename{a}, pero igor@374: no el nuevo fichero \filename{b}. Si yo publicara este conjunto de igor@374: cambios a un repositorio compartido con un colega, es bastante igor@374: probable que algo en \filename{a} se refiriera a \filename{b}, el cual igor@374: podría no estar presente cuando jalen mis cambios del repositorio. Me igor@374: convertiría el sujeto de cierta indignación. igor@374: igor@374: Como sea, la suerte me acompaña---Encontré mi error antes de publicar igor@374: el conjunto de cambios. Uso la orden \hgcmd{rollback}, y Mercurial igor@374: hace desaparecer el último conjunto de cambios. jerojasro@343: \interaction{rollback.rollback} igor@374: El conjunto de cambios ya no está en la historia del repositorio, y el igor@374: directorio de trabajo cree que el fichero \filename{a} ha sido igor@377: modificado. La consignación y el roll back dejaron el directorio de igor@377: trabajo exactamente como estaba antes de la consignación; el conjunto igor@374: de cambios ha sido eliminado totlamente. Ahora puedo hacer \hgcmd{add} igor@374: al fichero \filename{b}, y hacer de nuevo la consignación. jerojasro@343: \interaction{rollback.add} jerojasro@343: igor@374: \subsection{Erroneamente jalado} igor@374: igor@374: Mantener ramas de desarrollo separadas de un proyecto en distintos igor@374: repositorios es una práctica común con Mercurial. Su equipo de igor@374: desarrollo puede tener un repositorio compartido para la versión ``0.9'' igor@374: y otra con cambios distintos para la versión ``1.0''. igor@374: igor@374: Con este escenario, puede imaginar las consecuencias si tuviera un igor@374: repositorio local ``0.9'', y jalara accidentalmente los cambios del igor@374: repositorio compartido de la versión ``1.0'' en este. En el peor de igor@374: los casos, por falta de atención, es posible que publique tales igor@374: cambios en el árbol compartido ``0.9'', confundiendo a todo su equipo igor@374: de trabajo(pero no se preocupe, volveremos a este terrorífico igor@374: escenario posteriormente). En todo caso, es muy probable que usted se igor@374: de cuenta inmediatamente, dado que Mercurial mostrará el URL de donde igor@374: está jalando, o que vea jalando una sospechosa gran cantidad de igor@374: cambios en el repositorio. igor@374: igor@377: La orden \hgcmd{rollback} excluirá eficientemente los conjuntos de igor@377: cambios que haya acabado de jalar. Mercurial agrupa todos los cambios igor@377: de un \hgcmd{pull} a una única transacción y bastará con un igor@377: \hgcmd{rollback} para deshacer esta equivocación. igor@377: igor@377: \subsection{Después de publicar, un roll back es futil} jerojasro@343: \label{sec:undo:rollback-after-push} jerojasro@343: igor@377: El valor de \hgcmd{rollback} se anula cuando ha publicado sus cambios igor@377: a otro repositorio. Un cambio desaparece totalmente al hacer roll back, igor@377: pero \emph{solamente} en el repositorio en el cual aplica igor@377: \hgcmd{rollback}. Debido a que un roll back elimina la historia, igor@377: no hay forma de que la desaparición de un cambio se propague entre igor@377: repositorios. igor@377: igor@377: Si ha publicado un cambio en otro repositorio---particularmente si es igor@377: un repositorio público---esencialmente está ``en terreno agreste,'' igor@377: y tendrá que reparar la equivocación de un modo distinto. Lo que igor@377: pasará si publica un conjunto de cambios en algún sitio, hacer igor@377: rollback y después volver a jalar del repositorio del cual había igor@377: publicado, es que el conjunto de cambios reaparecerá en su repositorio. igor@377: igor@377: (Si está absolutamente segruro de que el conjunto de cambios al que igor@377: desea hacer rollback es el cambio más reciente del repositorio en el igor@377: cual publicó, \emph{y} sabe que nadie más pudo haber jalado de tal igor@377: repositorio, puede hacer rollback del conjunto de cambios allí, pero igor@377: es mejor no confiar en una solución de este estilo. Si lo hace, tarde igor@377: o temprano un conjunto de cambios logrará colarse en un repositorio igor@377: que usted no controle directamente(o del cual se ha olvidado), y igor@377: volverá a hostigarle.) igor@377: igor@377: \subsection{Solamente hay un roll back} igor@377: igor@377: Mercurial almacena exactamente una transacción en su bitácora de igor@377: transacciones; tal transacción es la más reciente de las que haya igor@377: ocurrido en el repositorio. Esto significa que solamente puede hacer igor@377: roll back a una transacción. Si espera poder hacer roll back a una igor@377: transacción después al antecesor, observará que no es el igor@377: comportamiento que obtendrá. jerojasro@343: \interaction{rollback.twice} igor@377: Una vez que haya aplicado un rollback en una transacción a un igor@377: repositorio, no podrá volver a hacer rollback hasta que haga una igor@377: consignación o haya jalado. jerojasro@343: igor@386: \section{Revertir un cambio equivocado} igor@386: igor@386: Si modifica un fichero y se da cuenta que no quería realmente cambiar igor@386: tal fichero, y todavía no ha consignado los cambios, la orden igor@386: necesaria es \hgcmd{revert}. Observa el conjunto de cambios padre del igor@386: directorio y restaura los contenidos del fichero al estado de tal igor@386: conjunto de cambios. (Es una forma larga de decirlo, usualmente igor@386: deshace sus modificaciones.) igor@386: igor@386: Ilustremos como actúa la orden \hgcmd{revert} con un ejemplo igor@386: pequeño. Comenzaremos modificando un fichero al cual Mercurial ya está igor@386: siguiendo. jerojasro@343: \interaction{daily.revert.modify} igor@386: Si no queremos ese cambio, podemos aplicar \hgcmd{revert} al fichero. jerojasro@343: \interaction{daily.revert.unmodify} igor@386: La orden \hgcmd{revert} nos brinda un grado adicional de seguridad igor@386: guardando nuestro fichero modificado con la extensión \filename{.orig}. jerojasro@343: \interaction{daily.revert.status} jerojasro@343: igor@386: Este es un resumen de casos en los cuales la orden \hgcmd{revert} es igor@386: de utilidad. Describiremos cada uno de ellos con más detalle en la igor@386: sección siguiente. jerojasro@343: \begin{itemize} igor@386: \item Si usted modifica un fichero, lo restaurará a su estado sin igor@386: modificación previo. igor@386: \item Si usted hace \hgcmd{add} a un fichero, revertirá el estado de igor@386: ``adicionado'' del fichero, pero no lo tocará igor@386: \item Si borra un fichero sin decirle a Mercurial, restaurará el igor@386: fichero con sus contenidos sin modificación. igor@386: \item Si usa la orden \hgcmd{remove} para eliminar un fichero, deshará igor@386: el estado ``removido'' del fichero, y lo restaurará con sus igor@386: contenidos sin modificación. jerojasro@343: \end{itemize} jerojasro@343: igor@386: \subsection{Errores al administrar ficheros} jerojasro@343: \label{sec:undo:mgmt} jerojasro@343: igor@386: La orden \hgcmd{revert} es útil para más que ficheros modificados. Le igor@386: permite reversar los resultados de todas las órdenes de administración igor@386: de ficheros que provee Mercurial---\hgcmd{add}, \hgcmd{remove}, y las igor@386: demás. igor@386: igor@386: Si usted hace \hgcmd{add} a un fichero, y no deseaba que Mercurial le igor@386: diera seguimiento, use \hgcmd{revert} para deshacer la adición. No se igor@386: preocupe; Mercurial no modificará de forma alguna el fichero. igor@386: Solamente lo ``desmarcará''. jerojasro@343: \interaction{daily.revert.add} jerojasro@343: igor@386: De forma similar, Si le solicita a Mercurial hacer \hgcmd{remove} a un igor@386: fichero, puede usar \hgcmd{revert} para restarurarlo a los contenidos igor@386: que tenía la revisión padre del directorio de trabajo. jerojasro@343: \interaction{daily.revert.remove} igor@386: Funciona de la misma manera para un fichero que usted haya eliminado igor@386: manualmente, sin decirle a Mercurial (recuerde que en la terminología igor@386: de Mercurial esta clase de fichero se llama ``faltante''). jerojasro@343: \interaction{daily.revert.missing} jerojasro@343: igor@386: Si usted revierte un \hgcmd{copy}, el fichero a donde se copió igor@386: permanece en su directorio de trabajo, pero sin seguimiento. Dado que igor@386: una copia no afecta el fichero fuente de copiado de ninguna maner, igor@386: Mercurial no hace nada con este. jerojasro@343: \interaction{daily.revert.copy} jerojasro@343: igor@386: \subsubsection{Un caso ligeramente especial:revertir un renombramiento} igor@386: igor@386: Si hace \hgcmd{rename} a un fichero, hay un detalle que debe tener en igor@386: cuenta. Cuando aplica \hgcmd{revert} a un cambio de nombre, no es igor@386: suficiente proveer el nombre del fichero destino, como puede verlo en igor@386: el siguiente ejemplo. jerojasro@343: \interaction{daily.revert.rename} igor@386: Como puede ver en la salida de \hgcmd{status}, el fichero con el nuevo igor@386: nombre no se identifica más como agregado, pero el fichero con el igor@386: nombre-\emph{inicial} se elimna! Esto es contra-intuitivo (por lo igor@386: menos para mí), pero por lo menos es fácil arreglarlo. jerojasro@343: \interaction{daily.revert.rename-orig} igor@386: Por lo tanto, recuerde, para revertir un \hgcmd{rename}, debe proveer igor@386: \emph{ambos} nombres, la fuente y el destino. jerojasro@343: jerojasro@343: % TODO: the output doesn't look like it will be removed! jerojasro@343: igor@386: (A propósito, si elimina un fichero, y modifica el fichero con el igor@386: nuevo nombre, al revertir ambos componentes del renombramiento, cuando igor@386: Mercurial restaure el fichero que fue eliminado como parte del igor@386: renombramiento, no será modificado. igor@386: Si necesita que las modificaciones en el archivo destino del igor@386: renombramiento se muestren, no olvide copiarlas encima.) igor@386: igor@387: Estos aspectos engorrosos al revertir un renombramiento se constituyen igor@386: discutiblemente en un fallo de Mercurial. jerojasro@343: igor@387: \section{Tratar cambios consignados} igor@387: igor@387: Considere un caso en el que ha consignado el cambio $a$, y otro cambio igor@387: $b$ sobre este; se ha dado cuenta que el cambio $a$ era igor@387: incorrecto. Mercurial le permite ``retroceder'' un conjunto de cambios igor@387: completo automáticamente, y construir bloques que le permitan revertir igor@387: parte de un conjunto de cambios a mano. igor@387: igor@387: Antes de leer esta sección, hay algo para tener en cuenta: la orden igor@387: \hgcmd{backout} deshace cambios \emph{adicionando} a la historia, sin igor@387: modificar o borrar. Es la herramienta correcta si está arreglando igor@387: fallos, pero no si está tratando de deshacer algún cambio que tiene igor@387: consecuencias catastróficas. Para tratar con esos, vea la sección~\ref{sec:undo:aaaiiieee}. igor@387: igor@387: \subsection{Retroceder un conjunto de cambios} igor@387: igor@387: La orden \hgcmd{backout} le permite ``deshacer'' los efectos de todo igor@387: un conjunto de cambios de forma automatizada. Dado que la historia de igor@387: Mercurial es inmutable, esta orden \emph{no} se deshace del conjunto igor@387: de cambios que usted desea deshacer. En cambio, crea un nuevo igor@387: conjunto de cambios que \emph{reversa} el conjunto de cambios que igor@387: usted indique. igor@387: igor@387: La operación de la orden \hgcmd{backout} es un poco intrincada, y lo igor@387: ilustraremos con algunos ejemplos. Primero crearemos un repositorio igor@387: con algunos cambios sencillos. jerojasro@343: \interaction{backout.init} jerojasro@343: igor@387: La orden \hgcmd{backout} toma un ID de conjunto de cambios como su igor@387: argumento; el conjunto de cambios a retroceder. Normalmente igor@387: \hgcmd{backout} le ofrecerá un editor de texto para escribir el igor@387: mensaje de la consignación, para dejar un registro de por qué está igor@387: retrocediendo. En este ejemplo, colocamos un mensaje en la igor@387: consignación usando la opción \hgopt{backout}{-m} . igor@387: igor@388: \subsection{Retroceder el conjunto de cambios punta} igor@387: igor@387: Comenzamos retrocediendo el último conjunto de cambios que consignamos. jerojasro@343: \interaction{backout.simple} igor@387: Puede ver que la segunda línea de \filename{myfile} ya no está igor@387: presente. La salida de \hgcmd{log} nos da una idea de lo que la orden igor@387: \hgcmd{backout} ha hecho. jerojasro@343: \interaction{backout.simple.log} igor@387: Vea que el nuevo conjunto de cambios que \hgcmd{backout} ha creado es igor@387: un hijo del conjunto de cambios que retrocedimos. Es más sencillo de igor@387: ver en la figura~\ref{fig:undo:backout}, que presenta una vista igor@387: gráfica de la historia de cambios. Como puede ver, la historia es igor@387: bonita y lineal. jerojasro@343: jerojasro@343: \begin{figure}[htb] jerojasro@343: \centering jerojasro@343: \grafix{undo-simple} igor@387: \caption{Retroceso de un cambio con la orden \hgcmd{backout}} jerojasro@343: \label{fig:undo:backout} jerojasro@343: \end{figure} jerojasro@343: igor@388: \subsection{Retroceso de un cambio que no es la punta} igor@387: igor@387: Si desea retrocede un cambio distinto al último que ha consignado, use igor@387: la opción \hgopt{backout}{--merge} a la orden \hgcmd{backout}. jerojasro@343: \interaction{backout.non-tip.clone} igor@387: Que resulta en un retroceso de un conjunto de cambios ``en un sólo igor@387: tiro'', una operación que resulta normalmente rápida y sencilla. jerojasro@343: \interaction{backout.non-tip.backout} jerojasro@343: igor@387: Si ve los contenidos del fichero \filename{myfile} después de igor@387: finalizar el retroceso, verá que el primer y el tercer cambio están igor@387: presentes, pero no el segundo. jerojasro@343: \interaction{backout.non-tip.cat} jerojasro@343: igor@387: Como lo muestra la historia gráfica en la igor@387: figura~\ref{fig:undo:backout-non-tip}, Mercurial realmente consigna igor@387: \emph{dos} cambios en estas situaciones (los nodos encerrados en una igor@387: caja son aquellos que Mercurial consigna automaticamente). Antes de igor@387: que Mercurial comience el proceso de retroceso, primero recuerda cuál igor@387: es el padre del directorio de trabajo. Posteriormente hace un igor@387: retroceso al conjunto de cambios objetivo y lo consigna como un igor@387: conjunto de cambios. Finalmente, fusiona con el padre anterior del igor@387: directorio de trabajo, y consigna el resultado de la fusión. jerojasro@343: jerojasro@343: % TODO: to me it looks like mercurial doesn't commit the second merge automatically! jerojasro@343: jerojasro@343: \begin{figure}[htb] jerojasro@343: \centering jerojasro@343: \grafix{undo-non-tip} igor@388: \caption{Retroceso automatizado de un cambio a algo que no es la punta con la orden \hgcmd{backout}} jerojasro@343: \label{fig:undo:backout-non-tip} jerojasro@343: \end{figure} jerojasro@343: igor@387: El resultado es que usted termina ``donde estaba'', solamente con un igor@387: poco de historia adicional que deshace el efecto de un conjunto de igor@387: cambios que usted quería evitar. jerojasro@343: igor@388: \subsubsection{Use siempre la opción \hgopt{backout}{--merge}} igor@388: igor@388: De hecho, dado que la opción \hgopt{backout}{--merge} siempre hara lo igor@388: ``correcto'' esté o no retrocediendo el conjunto de cambios punta igor@388: (p.e.~no tratará de fusionar si está retrocediendo la punta, dado que igor@388: no es necesario), usted debería usar \emph{siempre} esta opción cuando igor@388: ejecuta la orden \hgcmd{backout}. igor@388: igor@388: \subsection{Más control sobre el proceso de retroceso} igor@388: igor@388: A pesar de que recomiendo usar siempre la opción igor@388: \hgopt{backout}{--merge} cuando está retrocediendo un cambio, la orden igor@388: \hgcmd{backout} le permite decidir cómo mezclar un retroceso de un igor@388: conjunto de cambios. Es muy extraño que usted necestite tomar control igor@388: del proceso de retroceso de forma manual, pero puede ser útil entender igor@388: lo que la orden \hgcmd{backout} está haciendo automáticamente para igor@388: usted. Para ilustrarlo, clonemos nuestro primer repositorio, pero igor@388: omitamos el retroceso que contiene. jerojasro@343: jerojasro@343: \interaction{backout.manual.clone} igor@388: Como en el ejemplo anterior, consignaremos un tercer cambio, después igor@388: haremos retroceso de su padre, y veremos qué pasa. jerojasro@343: \interaction{backout.manual.backout} igor@388: Nuestro nuevo conjunto de cambios es de nuevo un descendiente del igor@388: conjunto de cambio que retrocedimos; es por lo tanto una nueva cabeza, igor@388: \emph{no} un descendiente del conjunto de cambios que era la punta. La igor@388: orden \hgcmd{backout} fue muy explícita diciéndolo. jerojasro@343: \interaction{backout.manual.log} jerojasro@343: igor@388: De nuevo, es más sencillo lo que pasó viendo una gráfica de la igor@388: historia de revisiones, en la figura~\ref{fig:undo:backout-manual}. igor@388: Esto nos aclara que cuando usamos \hgcmd{backout} para retroceder un igor@388: cambio a algo que no sea la punta, Mercurial añade una nueva cabeza al igor@388: repositorio (el cambio que consignó está encerrado en una caja). jerojasro@343: jerojasro@343: \begin{figure}[htb] jerojasro@343: \centering jerojasro@343: \grafix{undo-manual} igor@388: \caption{Retroceso usando la orden \hgcmd{backout}} jerojasro@343: \label{fig:undo:backout-manual} jerojasro@343: \end{figure} jerojasro@343: igor@388: Después de que la orden \hgcmd{backout} ha terminado, deja un nuevo igor@388: conjunto de cambios de ``retroceso'' como el padre del directorio de trabajo. jerojasro@343: \interaction{backout.manual.parents} igor@388: Ahora tenemos dos conjuntos de cambios aislados. jerojasro@343: \interaction{backout.manual.heads} jerojasro@343: igor@388: Reflexionemos acerca de lo que esperamos ver como contenidos de igor@388: \filename{myfile}. El primer cambio debería estar presente, porque igor@388: nunca le hicimos retroceso. El segundo cambio debió desaparecer, igor@388: puesto que es el que retrocedimos. Dado que la gráfica de la historia igor@388: muestra que el tercer camlio es una cabeza separada, \emph{no} igor@388: esperamos ver el tercer cambio presente en \filename{myfile}. jerojasro@343: \interaction{backout.manual.cat} igor@388: Para que el tercer cambio esté en el archivo, hacemos una fusión usual igor@388: de las dos cabezas. jerojasro@343: \interaction{backout.manual.merge} igor@388: Después de eso, la historia gráfica de nuestro repositorio luce como igor@388: la figura~\ref{fig:undo:backout-manual-merge}. jerojasro@343: jerojasro@343: \begin{figure}[htb] jerojasro@343: \centering jerojasro@343: \grafix{undo-manual-merge} igor@388: \caption{Fusión manual de un retroceso} jerojasro@343: \label{fig:undo:backout-manual-merge} jerojasro@343: \end{figure} jerojasro@343: igor@388: \subsection{Por qué \hgcmd{backout} hace lo que hace} igor@388: igor@388: Esta es una descripción corta de cómo trabaja la orden \hgcmd{backout}. jerojasro@343: \begin{enumerate} igor@388: \item Se asegura de que el directorio de trabajo es ``limpio'', esto igor@388: es, que la salida de \hgcmd{status} debería ser vacía. igor@388: \item Recuerda el padre actual del directorio de trabajo. A este igor@388: conjunto de cambio lo llamaremos \texttt{orig} igor@388: \item Hace el equivalente de un \hgcmd{update} para sincronizar el igor@388: directorio de trabajo con el conjunto de cambios que usted quiere igor@388: retroceder. Lo llamaremos \texttt{backout} igor@388: \item Encuentra el padre del conjunto de cambios. Lo llamaremos igor@388: \texttt{parent}. igor@388: \item Para cada archivo del conjunto de cambios que el igor@388: \texttt{retroceso} afecte, hará el equivalente a igor@388: \hgcmdargs{revert}{-r parent} sobre ese fichero, para restaurarlo a igor@388: los contenidos que tenía antes de que el conjunto de cambios fuera igor@388: consignado. igor@388: \item Se consigna el resultado como un nuevo conjunto de cambios y igor@388: tiene a \texttt{backout} como su padre. igor@388: \item Si especifica \hgopt{backout}{--merge} en la línea de comandos, igor@388: se fusiona con \texttt{orig}, y se consigna el resultado de la igor@388: fusión. jerojasro@343: \end{enumerate} jerojasro@343: igor@388: Una vía alternativa de implementar la orden \hgcmd{backout} sería usar igor@388: \hgcmd{export} sobre el conjunto de cambios a retroceder como un diff igor@388: y después usar laa opción \cmdopt{patch}{--reverse} de la orden igor@388: \command{patch} para reversar el efecto del cambio sin molestar el igor@388: directorio de trabajo. Suena mucho más simple, pero no funcionaría igor@388: bien ni de cerca. igor@388: igor@388: La razón por la cual \hgcmd{backout} hace una actualización, una igor@388: consignación, una fusión y otra consignación es para dar a la igor@388: maquinaria de fusión la mayor oportunidad de hacer un buen trabajo igor@388: cuando se trata con todos los cambios \emph{entre} el cambio que está igor@388: retrocediendo y la punta actual. igor@388: igor@388: Si está retrocediendo un conjunto de cambios que está a unas ~100 igor@388: atrás en su historia del proyecto, las posibilidades de que una orden igor@388: \command{patch} sea capaz de ser aplicada a un diff reverso, igor@388: claramente no son altas, porque los cambios que intervienen podrían igor@388: ``no coincidir con el contexto'' que \command{patch} usa para igor@388: determinar si puede aplicar un parche (si esto suena como cháchara, igor@388: vea una discusión de la orden \command{patch} en \ref{sec:mq:patch}). igor@388: Adicionalmente, la maquinaria de fusión de Mercurial manejará ficheros igor@388: y directorios renombrados, cambios de permisos, y modificaciones a igor@388: archivos binarios, nada de lo cual la orden \command{patch} puede manejar. jerojasro@343: igor@389: \section{Cambios que nunca debieron ocurrir} jerojasro@343: \label{sec:undo:aaaiiieee} jerojasro@343: igor@389: En la mayoría de los casos, la orden \hgcmd{backout} es exactamente lo igor@389: que necesita para deshacer los efectos de un cambio. Deja un registro igor@389: permanente y exacto de lo que usted hizo, cuando se consignó el igor@389: conjunto de cambios original y cuando se hizo la limpieza. igor@389: igor@389: En ocasiones particulares, puede haber consignado un cambio que no igor@389: debería estar de ninguna forma en el repositorio. Por ejemplo, sería igor@389: muy inusual, y considerado como una equivocación, consignar los igor@389: archivos objeto junto con el código fuente. los ficheros objeto no igor@389: tienen valor intrínseco y son \emph{grandes}, por lo tanto aumentan el igor@389: tamaño del repositorio y la cantidad de tiempo que se emplea al clonar igor@389: o jalar cambios. igor@389: igor@389: Antes de discutir las opciones que tiene si consignó cambio del tipo igor@389: ``bolsa de papel deschable'' (el tipo que es tan malo que le gustaría igor@389: colocarse una bolsa de papel desechable en su cabeza), permítame igor@389: discutir primero unas aproximaciones que probablemente no funcionen. igor@389: igor@389: Dado que Mercurial trata de forma acumulativa la historia---cada igor@389: cambio se coloca encima de todos los cambios que leo igor@389: preceden---usualmente usted no puede hacer que unos cambios desastros igor@389: desaparezcan. La única excepción es cuando usted ha acabado de igor@389: consignar un cambio y este no ha sido publicado o jalado en otro igor@389: repositorio. Ahí es cuando puede usar la orden \hgcmd{rollback} con igor@389: seguridad, Como detallé en la sección~\ref{sec:undo:rollback}. igor@389: igor@389: Después de que usted haya publicado un cambio en otro repositorio, usted igor@389: \emph{podría} usar la orden \hgcmd{rollback} para hacer que en su copia igor@389: local desaparezca el cambio, pero no tendrá las consecuencias que igor@389: desea. El cambio estará presente en un repositorio remoto, y igor@389: reaparecerá en su repositorio local la próxima vez que jale igor@389: igor@389: Si una situación como esta se presenta, y usted sabe en qué igor@389: repositorios su mal cambio se ha propagado, puede \emph{intentar} igor@389: deshacerse del conjunto de cambios de \emph{todos} los repositorios en igor@389: los que se pueda encontrar. Esta por supuesto, no es una solución igor@389: satisfactoria: si usted deja de hacerlo en un solo repositorio, igor@389: mientras esté eliminándolo, el cambio todavía estará ``allí afuera'', igor@389: y podría propagarse más tarde. igor@389: igor@389: Si ha consignado uno o más cambios \emph{después} del cambio que desea igor@389: desaparecer, sus opciones son aún más reducidas. Mercurial no provee igor@389: una forma de ``cabar un hueco'' en la historia, dejando los conjuntos igor@389: de cambios intactos. igor@389: igor@389: %Dejamos de traducir lo que viene a continuación, porque será igor@389: %modificado por upstream... jerojasro@343: jerojasro@343: XXX This needs filling out. The \texttt{hg-replay} script in the jerojasro@343: \texttt{examples} directory works, but doesn't handle merge jerojasro@343: changesets. Kind of an important omission. jerojasro@343: jerojasro@343: \subsection{Protect yourself from ``escaped'' changes} jerojasro@343: jerojasro@343: If you've committed some changes to your local repository and they've jerojasro@343: been pushed or pulled somewhere else, this isn't necessarily a jerojasro@343: disaster. You can protect yourself ahead of time against some classes jerojasro@343: of bad changeset. This is particularly easy if your team usually jerojasro@343: pulls changes from a central repository. jerojasro@343: jerojasro@343: By configuring some hooks on that repository to validate incoming jerojasro@343: changesets (see chapter~\ref{chap:hook}), you can automatically jerojasro@343: prevent some kinds of bad changeset from being pushed to the central jerojasro@343: repository at all. With such a configuration in place, some kinds of jerojasro@343: bad changeset will naturally tend to ``die out'' because they can't jerojasro@343: propagate into the central repository. Better yet, this happens jerojasro@343: without any need for explicit intervention. jerojasro@343: jerojasro@343: For instance, an incoming change hook that verifies that a changeset jerojasro@343: will actually compile can prevent people from inadvertantly ``breaking jerojasro@343: the build''. jerojasro@343: jerojasro@343: \section{Finding the source of a bug} jerojasro@343: \label{sec:undo:bisect} jerojasro@343: jerojasro@343: While it's all very well to be able to back out a changeset that jerojasro@343: introduced a bug, this requires that you know which changeset to back jerojasro@343: out. Mercurial provides an invaluable command, called jerojasro@343: \hgcmd{bisect}, that helps you to automate this process and accomplish jerojasro@343: it very efficiently. jerojasro@343: jerojasro@343: The idea behind the \hgcmd{bisect} command is that a changeset has jerojasro@343: introduced some change of behaviour that you can identify with a jerojasro@343: simple binary test. You don't know which piece of code introduced the jerojasro@343: change, but you know how to test for the presence of the bug. The jerojasro@343: \hgcmd{bisect} command uses your test to direct its search for the jerojasro@343: changeset that introduced the code that caused the bug. jerojasro@343: jerojasro@343: Here are a few scenarios to help you understand how you might apply jerojasro@343: this command. jerojasro@343: \begin{itemize} jerojasro@343: \item The most recent version of your software has a bug that you jerojasro@343: remember wasn't present a few weeks ago, but you don't know when it jerojasro@343: was introduced. Here, your binary test checks for the presence of jerojasro@343: that bug. jerojasro@343: \item You fixed a bug in a rush, and now it's time to close the entry jerojasro@343: in your team's bug database. The bug database requires a changeset jerojasro@343: ID when you close an entry, but you don't remember which changeset jerojasro@343: you fixed the bug in. Once again, your binary test checks for the jerojasro@343: presence of the bug. jerojasro@343: \item Your software works correctly, but runs~15\% slower than the jerojasro@343: last time you measured it. You want to know which changeset jerojasro@343: introduced the performance regression. In this case, your binary jerojasro@343: test measures the performance of your software, to see whether it's jerojasro@343: ``fast'' or ``slow''. jerojasro@343: \item The sizes of the components of your project that you ship jerojasro@343: exploded recently, and you suspect that something changed in the way jerojasro@343: you build your project. jerojasro@343: \end{itemize} jerojasro@343: jerojasro@343: From these examples, it should be clear that the \hgcmd{bisect} jerojasro@343: command is not useful only for finding the sources of bugs. You can jerojasro@343: use it to find any ``emergent property'' of a repository (anything jerojasro@343: that you can't find from a simple text search of the files in the jerojasro@343: tree) for which you can write a binary test. jerojasro@343: jerojasro@343: We'll introduce a little bit of terminology here, just to make it jerojasro@343: clear which parts of the search process are your responsibility, and jerojasro@343: which are Mercurial's. A \emph{test} is something that \emph{you} run jerojasro@343: when \hgcmd{bisect} chooses a changeset. A \emph{probe} is what jerojasro@343: \hgcmd{bisect} runs to tell whether a revision is good. Finally, jerojasro@343: we'll use the word ``bisect'', as both a noun and a verb, to stand in jerojasro@343: for the phrase ``search using the \hgcmd{bisect} command. jerojasro@343: jerojasro@343: One simple way to automate the searching process would be simply to jerojasro@343: probe every changeset. However, this scales poorly. If it took ten jerojasro@343: minutes to test a single changeset, and you had 10,000 changesets in jerojasro@343: your repository, the exhaustive approach would take on average~35 jerojasro@343: \emph{days} to find the changeset that introduced a bug. Even if you jerojasro@343: knew that the bug was introduced by one of the last 500 changesets, jerojasro@343: and limited your search to those, you'd still be looking at over 40 jerojasro@343: hours to find the changeset that introduced your bug. jerojasro@343: jerojasro@343: What the \hgcmd{bisect} command does is use its knowledge of the jerojasro@343: ``shape'' of your project's revision history to perform a search in jerojasro@343: time proportional to the \emph{logarithm} of the number of changesets jerojasro@343: to check (the kind of search it performs is called a dichotomic jerojasro@343: search). With this approach, searching through 10,000 changesets will jerojasro@343: take less than three hours, even at ten minutes per test (the search jerojasro@343: will require about 14 tests). Limit your search to the last hundred jerojasro@343: changesets, and it will take only about an hour (roughly seven tests). jerojasro@343: jerojasro@343: The \hgcmd{bisect} command is aware of the ``branchy'' nature of a jerojasro@343: Mercurial project's revision history, so it has no problems dealing jerojasro@343: with branches, merges, or multiple heads in a repoository. It can jerojasro@343: prune entire branches of history with a single probe, which is how it jerojasro@343: operates so efficiently. jerojasro@343: jerojasro@343: \subsection{Using the \hgcmd{bisect} command} jerojasro@343: jerojasro@343: Here's an example of \hgcmd{bisect} in action. jerojasro@343: jerojasro@343: \begin{note} jerojasro@343: In versions 0.9.5 and earlier of Mercurial, \hgcmd{bisect} was not a jerojasro@343: core command: it was distributed with Mercurial as an extension. jerojasro@343: This section describes the built-in command, not the old extension. jerojasro@343: \end{note} jerojasro@343: jerojasro@343: Now let's create a repository, so that we can try out the jerojasro@343: \hgcmd{bisect} command in isolation. jerojasro@343: \interaction{bisect.init} jerojasro@343: We'll simulate a project that has a bug in it in a simple-minded way: jerojasro@343: create trivial changes in a loop, and nominate one specific change jerojasro@343: that will have the ``bug''. This loop creates 35 changesets, each jerojasro@343: adding a single file to the repository. We'll represent our ``bug'' jerojasro@343: with a file that contains the text ``i have a gub''. jerojasro@343: \interaction{bisect.commits} jerojasro@343: jerojasro@343: The next thing that we'd like to do is figure out how to use the jerojasro@343: \hgcmd{bisect} command. We can use Mercurial's normal built-in help jerojasro@343: mechanism for this. jerojasro@343: \interaction{bisect.help} jerojasro@343: jerojasro@343: The \hgcmd{bisect} command works in steps. Each step proceeds as follows. jerojasro@343: \begin{enumerate} jerojasro@343: \item You run your binary test. jerojasro@343: \begin{itemize} jerojasro@343: \item If the test succeeded, you tell \hgcmd{bisect} by running the jerojasro@343: \hgcmdargs{bisect}{good} command. jerojasro@343: \item If it failed, run the \hgcmdargs{bisect}{--bad} command. jerojasro@343: \end{itemize} jerojasro@343: \item The command uses your information to decide which changeset to jerojasro@343: test next. jerojasro@343: \item It updates the working directory to that changeset, and the jerojasro@343: process begins again. jerojasro@343: \end{enumerate} jerojasro@343: The process ends when \hgcmd{bisect} identifies a unique changeset jerojasro@343: that marks the point where your test transitioned from ``succeeding'' jerojasro@343: to ``failing''. jerojasro@343: jerojasro@343: To start the search, we must run the \hgcmdargs{bisect}{--reset} command. jerojasro@343: \interaction{bisect.search.init} jerojasro@343: jerojasro@343: In our case, the binary test we use is simple: we check to see if any jerojasro@343: file in the repository contains the string ``i have a gub''. If it jerojasro@343: does, this changeset contains the change that ``caused the bug''. By jerojasro@343: convention, a changeset that has the property we're searching for is jerojasro@343: ``bad'', while one that doesn't is ``good''. jerojasro@343: jerojasro@343: Most of the time, the revision to which the working directory is jerojasro@343: synced (usually the tip) already exhibits the problem introduced by jerojasro@343: the buggy change, so we'll mark it as ``bad''. jerojasro@343: \interaction{bisect.search.bad-init} jerojasro@343: jerojasro@343: Our next task is to nominate a changeset that we know \emph{doesn't} jerojasro@343: have the bug; the \hgcmd{bisect} command will ``bracket'' its search jerojasro@343: between the first pair of good and bad changesets. In our case, we jerojasro@343: know that revision~10 didn't have the bug. (I'll have more words jerojasro@343: about choosing the first ``good'' changeset later.) jerojasro@343: \interaction{bisect.search.good-init} jerojasro@343: jerojasro@343: Notice that this command printed some output. jerojasro@343: \begin{itemize} jerojasro@343: \item It told us how many changesets it must consider before it can jerojasro@343: identify the one that introduced the bug, and how many tests that jerojasro@343: will require. jerojasro@343: \item It updated the working directory to the next changeset to test, jerojasro@343: and told us which changeset it's testing. jerojasro@343: \end{itemize} jerojasro@343: jerojasro@343: We now run our test in the working directory. We use the jerojasro@343: \command{grep} command to see if our ``bad'' file is present in the jerojasro@343: working directory. If it is, this revision is bad; if not, this jerojasro@343: revision is good. jerojasro@343: \interaction{bisect.search.step1} jerojasro@343: jerojasro@343: This test looks like a perfect candidate for automation, so let's turn jerojasro@343: it into a shell function. jerojasro@343: \interaction{bisect.search.mytest} jerojasro@343: We can now run an entire test step with a single command, jerojasro@343: \texttt{mytest}. jerojasro@343: \interaction{bisect.search.step2} jerojasro@343: A few more invocations of our canned test step command, and we're jerojasro@343: done. jerojasro@343: \interaction{bisect.search.rest} jerojasro@343: jerojasro@343: Even though we had~40 changesets to search through, the \hgcmd{bisect} jerojasro@343: command let us find the changeset that introduced our ``bug'' with jerojasro@343: only five tests. Because the number of tests that the \hgcmd{bisect} jerojasro@343: command performs grows logarithmically with the number of changesets to jerojasro@343: search, the advantage that it has over the ``brute force'' search jerojasro@343: approach increases with every changeset you add. jerojasro@343: jerojasro@343: \subsection{Cleaning up after your search} jerojasro@343: jerojasro@343: When you're finished using the \hgcmd{bisect} command in a jerojasro@343: repository, you can use the \hgcmdargs{bisect}{reset} command to drop jerojasro@343: the information it was using to drive your search. The command jerojasro@343: doesn't use much space, so it doesn't matter if you forget to run this jerojasro@343: command. However, \hgcmd{bisect} won't let you start a new search in jerojasro@343: that repository until you do a \hgcmdargs{bisect}{reset}. jerojasro@343: \interaction{bisect.search.reset} jerojasro@343: jerojasro@343: \section{Tips for finding bugs effectively} jerojasro@343: jerojasro@343: \subsection{Give consistent input} jerojasro@343: jerojasro@343: The \hgcmd{bisect} command requires that you correctly report the jerojasro@343: result of every test you perform. If you tell it that a test failed jerojasro@343: when it really succeeded, it \emph{might} be able to detect the jerojasro@343: inconsistency. If it can identify an inconsistency in your reports, jerojasro@343: it will tell you that a particular changeset is both good and bad. jerojasro@343: However, it can't do this perfectly; it's about as likely to report jerojasro@343: the wrong changeset as the source of the bug. jerojasro@343: jerojasro@343: \subsection{Automate as much as possible} jerojasro@343: jerojasro@343: When I started using the \hgcmd{bisect} command, I tried a few times jerojasro@343: to run my tests by hand, on the command line. This is an approach jerojasro@343: that I, at least, am not suited to. After a few tries, I found that I jerojasro@343: was making enough mistakes that I was having to restart my searches jerojasro@343: several times before finally getting correct results. jerojasro@343: jerojasro@343: My initial problems with driving the \hgcmd{bisect} command by hand jerojasro@343: occurred even with simple searches on small repositories; if the jerojasro@343: problem you're looking for is more subtle, or the number of tests that jerojasro@343: \hgcmd{bisect} must perform increases, the likelihood of operator jerojasro@343: error ruining the search is much higher. Once I started automating my jerojasro@343: tests, I had much better results. jerojasro@343: jerojasro@343: The key to automated testing is twofold: jerojasro@343: \begin{itemize} jerojasro@343: \item always test for the same symptom, and jerojasro@343: \item always feed consistent input to the \hgcmd{bisect} command. jerojasro@343: \end{itemize} jerojasro@343: In my tutorial example above, the \command{grep} command tests for the jerojasro@343: symptom, and the \texttt{if} statement takes the result of this check jerojasro@343: and ensures that we always feed the same input to the \hgcmd{bisect} jerojasro@343: command. The \texttt{mytest} function marries these together in a jerojasro@343: reproducible way, so that every test is uniform and consistent. jerojasro@343: jerojasro@343: \subsection{Check your results} jerojasro@343: jerojasro@343: Because the output of a \hgcmd{bisect} search is only as good as the jerojasro@343: input you give it, don't take the changeset it reports as the jerojasro@343: absolute truth. A simple way to cross-check its report is to manually jerojasro@343: run your test at each of the following changesets: jerojasro@343: \begin{itemize} jerojasro@343: \item The changeset that it reports as the first bad revision. Your jerojasro@343: test should still report this as bad. jerojasro@343: \item The parent of that changeset (either parent, if it's a merge). jerojasro@343: Your test should report this changeset as good. jerojasro@343: \item A child of that changeset. Your test should report this jerojasro@343: changeset as bad. jerojasro@343: \end{itemize} jerojasro@343: jerojasro@343: \subsection{Beware interference between bugs} jerojasro@343: jerojasro@343: It's possible that your search for one bug could be disrupted by the jerojasro@343: presence of another. For example, let's say your software crashes at jerojasro@343: revision 100, and worked correctly at revision 50. Unknown to you, jerojasro@343: someone else introduced a different crashing bug at revision 60, and jerojasro@343: fixed it at revision 80. This could distort your results in one of jerojasro@343: several ways. jerojasro@343: jerojasro@343: It is possible that this other bug completely ``masks'' yours, which jerojasro@343: is to say that it occurs before your bug has a chance to manifest jerojasro@343: itself. If you can't avoid that other bug (for example, it prevents jerojasro@343: your project from building), and so can't tell whether your bug is jerojasro@343: present in a particular changeset, the \hgcmd{bisect} command cannot jerojasro@343: help you directly. Instead, you can mark a changeset as untested by jerojasro@343: running \hgcmdargs{bisect}{--skip}. jerojasro@343: jerojasro@343: A different problem could arise if your test for a bug's presence is jerojasro@343: not specific enough. If you check for ``my program crashes'', then jerojasro@343: both your crashing bug and an unrelated crashing bug that masks it jerojasro@343: will look like the same thing, and mislead \hgcmd{bisect}. jerojasro@343: jerojasro@343: Another useful situation in which to use \hgcmdargs{bisect}{--skip} is jerojasro@343: if you can't test a revision because your project was in a broken and jerojasro@343: hence untestable state at that revision, perhaps because someone jerojasro@343: checked in a change that prevented the project from building. jerojasro@343: jerojasro@343: \subsection{Bracket your search lazily} jerojasro@343: jerojasro@343: Choosing the first ``good'' and ``bad'' changesets that will mark the jerojasro@343: end points of your search is often easy, but it bears a little jerojasro@343: discussion nevertheless. From the perspective of \hgcmd{bisect}, the jerojasro@343: ``newest'' changeset is conventionally ``bad'', and the older jerojasro@343: changeset is ``good''. jerojasro@343: jerojasro@343: If you're having trouble remembering when a suitable ``good'' change jerojasro@343: was, so that you can tell \hgcmd{bisect}, you could do worse than jerojasro@343: testing changesets at random. Just remember to eliminate contenders jerojasro@343: that can't possibly exhibit the bug (perhaps because the feature with jerojasro@343: the bug isn't present yet) and those where another problem masks the jerojasro@343: bug (as I discussed above). jerojasro@343: jerojasro@343: Even if you end up ``early'' by thousands of changesets or months of jerojasro@343: history, you will only add a handful of tests to the total number that jerojasro@343: \hgcmd{bisect} must perform, thanks to its logarithmic behaviour. jerojasro@343: jerojasro@343: %%% Local Variables: jerojasro@343: %%% mode: latex jerojasro@343: %%% TeX-master: "00book" jerojasro@343: %%% End: