hgbook

view es/mq.tex @ 444:da4d34e0e250

Translated some more mq paragraphs to spanish
author Igor TAmara <igor@tamarapatino.org>
date Mon Dec 08 20:37:58 2008 -0500 (2008-12-08)
parents 2daeda01fe98
children 40ba5d8583c7
line source
1 \chapter{Administración de cambios con Colas de Mercurial}
2 \label{chap:mq}
4 \section{El problema de la administración de parches}
5 \label{sec:mq:patch-mgmt}
7 Un escenario frecuente: usted necesita instalar un paquete de software
8 desde las fuentes, pero encuentra un fallo que debe arreglar antes de
9 poder comenzar a usarlo. Hace sus cambios, y se olvida del paquete
10 por un tiempo, unos meses después necesita actualizar a una nueva
11 versión del paquete. Si la nueva versión del paquete todavía tiene el
12 fallo, debe extraer su arreglo del árbol de fuentes anteriores y
13 aplicarlo a la nueva versión. Una tarea tediosa en la cual es fácil
14 equivocarse.
16 Este es un caso simple del problema del ``manejo de parches''. Usted
17 tiene un árbol de fuentes del ``mantenedor principal'' que no puede
18 cambiar: necesita hacer algunos cambios locales sobre el árbol
19 principal; y desearía poder mantener tales cambios separados, de forma
20 tal que pueda aplicarlos a versiones más nuevas del árbol principal.
22 El problema de administración de parches surge en muchas situaciones.
23 Probablemente la más visible es cuando un usuario de un proyecto de
24 software de fuentes abiertas contribuye con un arreglo de un fallo o
25 una nueva característica a los mantenedores del proyecto en la forma
26 de un parche.
28 Aquellos que distribuyen sistemas operativos que incluyen programas
29 abiertos usualmente requieren hacer cambios en los paquetes que
30 distribuyen de tal forma que se armen apropiadamente en sus ambientes.
32 Cuando hay pocos cambios por mantener, es muy sencillo administrar un
33 solo parche con los programas estándar \command{diff} y
34 \command{patch}( ver la sección~\ref{sec:mq:patch} para ver cómo
35 emplear tales herramientas). Cuando la cantidad de cambios comienza a
36 crecer, tiene sentido mantener parches como ``porciones de trabajo''
37 individual, de forma que cada cambio contiene solamente un arreglo de
38 un fallo(el parche puede modificar varios archivos, pero está
39 ``haciendo una sola cosa''), y puede tener cierta cantidad de tales
40 parches para diferentes fallos y cambios locales. En esta situación,
41 si envía un parche que arregla un fallo a los mantenedores principales
42 de un paquete y ellos incluyen su arreglo en una publicación
43 posterior, puede deshacerse de tal parche cuando se actualice a la
44 nueva versión.
46 Mantener un solo parche frente a un árbol principal es algo tedioso y
47 es fácil equivocarse, pero no es difícil. Aunque, la complejidad del
48 problema crece rápidamente a medida que la cantidad de parches que
49 tiene que mantener crece. Con más que una pequeña cantidad de
50 cambios, entender cuáles ha aplicado se convierte de algo desordenado
51 a algo avasallante.
53 Afortunadamente Mercurial provee una extensión poderos: Colas de
54 Mercurial( o simplemente ``MQ''), que simplifica en gran medida el
55 problema de administración de parches.
57 \section{La prehistoria de las Colas de Mercurial}
58 \label{sec:mq:history}
60 A finales de los 90s, muchos desarrolladores del núcleo de Linux
61 comenzaron a mantener ``series de parches'' que modificaron el
62 comportamiento del núcleo de Linux. Algunos se enfocaban en
63 estabilidad, otros en aumentar las características, y otros un poco
64 más especulativos.
66 Los tamaños de las series de parches crecieron rápidamente. En el
67 2002, Andrew Morton publicó algunos guiones de línea de órdenes que
68 estuvo usando para automatizar la tarea de administrar su cola de
69 parches. Andrew usó exitósamente tales guiones para administrar
70 centenas( aveces millares) de parches en el núcleo de Linux.
72 \subsection{Trabajar parches con quilt}
73 \label{sec:mq:quilt}
75 A comienzos del 2003, Andreas Gruenbacher y Martin Quinson tomaron la
76 aproximación de los guiones de Andrew y publicaron una herramienta
77 llamada
78 ``patchwork quilt''~\cite{web:quilt}, o simplemente ``quilt''
79 (ver~\cite{gruenbacher:2005} el paper que lo describe). Dado que
80 quilt automatizaba sustancialmente la administración de parches, fue
81 adoptado en gran medida por desarrolladores de programas abiertos.
83 Quilt maneja una \emph{pila de parches} sobre un árbol de directorios.
84 Para comenzar, usted le indica a quilt que administre un árbol de
85 directorios, le indica qué archivos manejar; Este almacena los nombres
86 y los contenidos de estos archivos. Para arreglar un fallo, usted
87 crea un nuevo parche(con una sola orden), edita los archivos que está
88 arreglando y ``refresca'' el parche.
90 El paso de refresco hace que quilt revise el árbol de directorios;
91 actualiza el parche con todos los cambios que usted haya hecho. Puede
92 crear otro parche sobre el primero, que hará seguimiento de los
93 cambios requeridos para modificar el árbol desde ``el árbol con un
94 parch aplicado'' a un ``árbol con dos parches aplicados''.
96 Usted puede \emph{elegir} qué cambios desea aplicar al árbol. Si
97 ``pop''\ndt{saca} un parche, los cambios hechos por tal parchve
98 desapareceŕan del árbol de directorios. Quilt recuerda qué parches ha
99 sacado, para que pueda ``introducirlos''\ndt{push} posteriormente, así el
100 árbol de directorios se restaurará con las modificaciones que vienen
101 del parche. Lo más importante es que puede ejecutar la orden
102 ``refresh'' en cualquier momento, y el último parche será
103 actualizado. Esto significa que puede, en cualquier momento, cambiar
104 qué parches serán aplicados y qué modificaciones hacen ellos.
106 Quilt no tiene nada que ver con herramientas de control de versiones,
107 y puede trabajar bien sobre un conjunto de fuentes que viene de un
108 archivo comprimido y empaquetado o una copia de trabajo de Subversion.
110 \subsection{Pasar de trabajo con parches con Quilt hacia Colas de Mercurial}
111 \label{sec:mq:quilt-mq}
113 A mediados de 2005, Chris Mason tomó las características de quilt y
114 escribió una extensión que llamó Colas de Mercurial\ndt{Mercurial
115 Queues}, que proporcionó un comportamiento a Mercurial al estilo
116 quilt.
118 La diferencia clave entre quilt y MQ es que quilt no sabe nada acerca
119 del sistema de control de revisiones, mientras que MQ está
120 \emph{integrado} con Mercurial. Cada parche que usted introduce se
121 representa como un conjunto de cambios en Mercurial. Si sustrae un
122 parche, el conjunto de cambios desaparece.\ndt{introduce originalmente es
123 push y pop es sustraer en este contexto, usaremos el original en inglés
124 cuando encontremos que facilita la comprensión}
126 Dado que quilt no se preocupa por las herramientas de control de
127 revisiones, continúa siendo una porción de software tremendamente útil
128 para aquellas situaciones en las cuales no puede usar Mercurial y MQ.
130 \section{La gran ventaja de MQ}
132 No puedo sobreestimar el valor que MQ ofrece en la unificación de
133 parches y el control de revisiones.
135 La principal razón por la cual los parches han persistido en el mundo
136 del software libre y de fuentes abiertas--a pesar de la creciente
137 disponibilidad de herramientas poderosas de control de revisiones-- es
138 la \emph{agilidad} que ofrecen.
140 Las herramientas tradicionales de control de revisiones llevan un
141 registro permanente e irreversible de todo lo que usted hace. A pesar
142 de que esto tiene gran valor, también es bastante sutil. Si requiere
143 realizar un experimento ((((wild-eyed)))), debe ser cuidadoso en cómo
144 lo hace, o puede dejar trazas innecesarias--o peor aún,
145 desconcertantes o desestabilizantes--- de los pasos y errores en el
146 registro de revisiones de forma permanente.
148 En contraste, con la cohesión de MQ con el control de revisiones
149 distribuidos y los parches, resulta más sencillo aislar su trabajo.
150 Sus parches viven encima de la historia de revisiones normales, y
151 puede hacer que ellos desaparezcan o reaparezcan cuando lo desee. Si
152 no le gusta un parche, puede desecharlo. Si un parche no satisface
153 todo lo que usted desea, puede arreglarlo---tantas veces como lo
154 requiera, hasta que lo haya refinado lo suficiente hacia sus
155 expectativas.
157 Por ejemplo, la integración de parches con el control de revisiones
158 hace que el entender los parches y revisar sus efectos---y sus
159 interacciones con el código en el cuál están enlazados--- sea
160 \emph{mucho} más sencillo. Dado que todo parche que se aplique tiene
161 un conjunto de cambios asociado, puede usar
162 \hgcmdargs{log}{\emph{filename}} para ver qué conjuntos de cambios y
163 parches afectaron un fichero. Puede usar la orden \hgext{bisect} para
164 hacer una búsqueda binaria sobre todos los conjuntos de cambios y
165 parches aplicados para ver dónde se introdujo un fallo o dónde fue
166 arreglado. Puede usar la orden \hgcmd{annotate} para ver qué
167 conjuntos de cambios o parches modificaron una línea particular de un
168 archivo fuente. Y mucho más.
170 \section{Entender los parches}
171 \label{sec:mq:patch}
173 Dado que MQ no esconde su naturaleza parche-céntrica, es muy útil para
174 entender de qué se tratan los parches, y un poco acerca de las
175 herramientas que trabajan con ellos.
177 La orden de Unix tradicional \command{diff} compara dos ficheros, e
178 imprime una lista de diferencias de sus líneas. La orden
179 \command{patch} entiende esas diferencias como \emph{modificaciones}
180 para construir un fichero. Vea en la figura~\ref{ex:mq:diff} un
181 ejemplo sencillo de tales órdenes en acción.
183 \begin{figure}[ht]
184 \interaction{mq.dodiff.diff}
185 \caption{Uso sencillo de las órdenes \command{diff} y \command{patch}}
186 \label{ex:mq:diff}
187 \end{figure}
189 El tipo de fichero que \command{diff} genera (y que \command{patch}
190 toma como entrada) se llama un ``parche'' o un ``diff''; no hay
191 diferencia entre un parche y un diff. (Usaremos el término ``parche'',
192 dado que es el que más comunmente se usa.)
194 Un parche puede comenzar con un texto arbitrario; la orden \command{patch}
195 ignora este texto, pero MQ lo usa como el mensaje de consignación
196 cuando se crean conjuntos de cambios. Para encontrar el inicio del
197 contenido de un parche, la orden \command{patch} busca la primera
198 línea que comience con la cadena ``\texttt{diff~-}''.
200 MQ trabaja con diffs \emph{unificados} (\command{patch} acepta varios
201 formatos de diff adicionales, pero MQ no). Un diff unificado contiene
202 dos clases de encabezados. El \emph{encabezado de fichero} describe
203 el fichero que se está modificando; contiene el nombre del fichero a
204 modificar. Cuando \command{patch} ve un nuevo encabezado de fichero,
205 busca un fichero con ese nombre para modificarlo.
207 Después del encabezaado vienen varios \emph{trozos}. Cada trozo
208 comienza con un encabezado; que identifica el rango de líneas del
209 fichero que el trozo debe modificar. Después del encabezado, un trozo
210 comienza y termina con unas pocas líneas(usualmente tres) de texto del
211 fichero que no han sido modificadas; las cuales llamamos el
212 \emph{contexto} del trozo. Si solamente hay una pequeña cantidad de
213 contexto entre trozos sucesivos, \command{diff} no imprime un nuevo
214 encabezado para el trozo, continua integrando los trozos, con unas
215 líneas de contexto entre las modificaciones.
217 Cada línea de contexto comienza con un caracter de espacio. En el
218 trozo, si una línea comienza con ``\texttt{-}'' significa ``elimine
219 esta línea'', si la línea comienza con un ``\texttt{+}'' significa
220 ``inserte esta línea''. Por ejemplo, una línea que se modifica se
221 representa con una línea eliminada y una línea insertada.
223 Retomaremos aspectos más sutiles acerca de parches posteriormente(en
224 la sección~\ref{sec:mq:adv-patch}), pero en el momento usted ya
225 debería tener suficiente información para usar MQ.
227 \section{Comenzar a usar Colas de Mercurial}
228 \label{sec:mq:start}
230 Dado que MQ está implementado como una extensión, debe habilitarla
231 explícitamente antes de comenzar a usarla. (No necesita descargar
232 nada; MQ viene con la distribución estándar de Mercurial.) Para
233 habilitar MQ, edite su fichero \tildefile{.hgrc}, y añada las líneas
234 de la figura~\ref{ex:mq:config}.
236 \begin{figure}[ht]
237 \begin{codesample4}
238 [extensions]
239 hgext.mq =
240 \end{codesample4}
241 \label{ex:mq:config}
242 \caption{Líneas a añadir en \tildefile{.hgrc} para habilitar la extensión MQ}
243 \end{figure}
245 Cuando la extensión esté habilitada, aparecerán varios comandos. Para
246 verificar que la extensión está trabajando, puede usar \hgcmd{help}
247 para ver si la orden \hgxcmd{mq}{qinit} está disponible; vea un
248 ejemplo en la figura~\ref{ex:mq:enabled}.
250 \begin{figure}[ht]
251 \interaction{mq.qinit-help.help}
252 \caption{Cómo verificar que MQ está habilitado}
253 \label{ex:mq:enabled}
254 \end{figure}
256 Puede usar MQ en \emph{cualquier} repositorio de Mercurial, y sus
257 comandos solamente operarán con tal repositorio. Para comenzar, basta
258 con preparar el repositorio con la orden \hgxcmd{mq}{qinit}(ver la
259 figura~\ref{ex:mq:qinit}). Esta orden crea un directorio vacío
260 llamado \sdirname{.hg/patches}, donde MQ mantendrá sus metadatos. Como
261 otras ordenes de Mercurial, la orden \hgxcmd{mq}{qinit} no imprime
262 nada cuando es exitosa.
264 \begin{figure}[ht]
265 \interaction{mq.tutorial.qinit}
266 \caption{Preparar un repositorio para usar MQ}
267 \label{ex:mq:qinit}
268 \end{figure}
270 \begin{figure}[ht]
271 \interaction{mq.tutorial.qnew}
272 \caption{Crear un nuevo parche}
273 \label{ex:mq:qnew}
274 \end{figure}
276 \subsection{Crear un nuevo parche}
278 Para comenzar a trabajar en un nuevo parche use la orden
279 \hgxcmd{mq}{qnew}. Esta orden recibe un argumento, el nombre del
280 parche a crear. MQ lo usará como el nombre del fichero en el
281 directorio \sdirname{.hg/patches}, como puede apreciarlo en la
282 figura~\ref{ex:mq:qnew}.
284 También hay otros dos nuevos ficheros en el directorio
285 \sdirname{.hg/patches}: \sfilename{series} y \sfilename{status}. El
286 fichero \sfilename{series} lista todos los parches de los cuales MQ
287 tiene noticia para este repositorio, con un parche por línea.
288 Mercurial usa el fichero \sfilename{status} para mantener registros
289 interns; da seguimiento a todos los parches que MQ ha \emph{aplicado}
290 en el repositorio.
292 \begin{note}
293 En ciertas ocasiones usted querrá editar el fichero
294 \sfilename{series} a mano; por ejemplo, cambiar el orden en que se
295 aplican ciertos parches. A pesar de esto, es una mala idea editar
296 manualmente el fichero \sfilename{status}, dado que es fácil
297 desorientar a MQ acerca de lo que está pasando.
298 \end{note}
300 Una vez que haya creado un nuevo parche, puede editar los ficheros en
301 el directorio de trabajo, como lo haría usualmente. Toda las órdenes
302 que de a Mercurial, tales como \hgcmd{diff} y \hgcmd{annotate},
303 trabajarán de la misma forma como lo han hecho antes.
305 \subsection{Refrescar un parche}
307 Cuando usted llega a un punto en el cual desea guardar su trabajo, use
308 la orden \hgxcmd{mq}{qrefresh}(figura~\ref{ex:mq:qnew}) para
309 actualizar el parche en el cual está trabajando. Esta orden almacena
310 los cambios que haya hecho al directorio actual de trabajo en su
311 parche, y almacena el conjunto de cambios correspondiente que contiene
312 los cambios.
314 \begin{figure}[ht]
315 \interaction{mq.tutorial.qrefresh}
316 \caption{Refrescar un parche}
317 \label{ex:mq:qrefresh}
318 \end{figure}
320 Puede ejecutar la orden \hgxcmd{mq}{qrefresh} tan seguido como quiera,
321 y es una buena forma de ``colocar marcas'' a su trabajo. Refresque su
322 parche en momentos oportunos; intente un experimento; si el
323 experimento no funciona, Use \hgcmd{revert} sobre sus modificaciones
324 para volver al refresco anterior.
326 \begin{figure}[ht]
327 \interaction{mq.tutorial.qrefresh2}
328 \caption{Refrescar un parche muchas veces para acumular cambios}
329 \label{ex:mq:qrefresh2}
330 \end{figure}
332 \subsection{Aplicar un parche tras otro y dar seguimiento}
334 Cuando haya terminado de trabajar en un parche, o necesite trabajar en
335 otro, puede usar la orden \hgxcmd{mq}{qnew} para crear un nuevo
336 parche. Mercurial aplicará este parche sobre su parche anterior.
337 Para un ejemplo, ver la figura~\ref{ex:mq:qnew2}. Note que el parche
338 contiene los cambios en nuestro parche anterior como parte de su
339 contexto( lo verá más claramente en la salida de \hgcmd{annotate}).
341 \begin{figure}[ht]
342 \interaction{mq.tutorial.qnew2}
343 \caption{Aplicar un parche después del primero}
344 \label{ex:mq:qnew2}
345 \end{figure}
347 Hasta ahora, con excepción de \hgxcmd{mq}{qnew} y
348 \hgxcmd{mq}{qrefresh}, hemos sido cuidadosos para aplicar únicamente
349 órdenes usuaales de Mercurial. De todas maneras, MQ ofrece muchos
350 comandos que son más sencillos de usar cuando esté pensando acerca de
351 parches, como se puede ver en la figura~\ref{ex:mq:qseries}:
353 \begin{itemize}
354 \item La orden \hgxcmd{mq}{qseries} lista cada parche del cual MQ
355 tiene noticia en este repositorio, desde el más antiguo hasta el más
356 nuevo(El último \emph{creado}).
357 \item La orden \hgxcmd{mq}{qapplied} lista cada parche que MQ haya
358 \emph{aplicado} en este repositorio, de nuevo, desde el más antiguo
359 hasta el más nuevo (El aplicado más recientemente).
360 \end{itemize}
362 \begin{figure}[ht]
363 \interaction{mq.tutorial.qseries}
364 \caption{Entender la pila de parches con \hgxcmd{mq}{qseries} y
365 \hgxcmd{mq}{qapplied}}
366 \label{ex:mq:qseries}
367 \end{figure}
369 \subsection{Manipular la pila de parches}
371 La discusión previa indicó que debe haber una diferencia entre los
372 parches ``conocidos'' y ``aplicados'', y efectivamente la hay. MQ
373 puede manejar un parche sin que este haya sido aplicado al
374 repositorio.
376 Un parche \emph{aplicado} tiene su correspondiente conjunto de cambios
377 en el repositorio, y los efectos del parche y el conjunto de cambios
378 son visibles en el directorio de trabajo. Puede deshacer la
379 aplicación de un parche con la orden \hgxcmd{mq}{qpop}. MQ
380 \emph{sabe acerca de}, o maneja un parche sustraído, pero el parche ya
381 no tendrá un conjunto de cambios correspondientes en el repositorio, y
382 el directorio de trabajo no contendrá los cambios hechos por el
383 parche. La figura~\ref{fig:mq:stack} ilustra la diferencia entre
384 parches aplicados y seguidos.
386 \begin{figure}[ht]
387 \centering
388 \grafix{mq-stack}
389 \caption{Parches aplicados y no aplicados en la pila de parches de MQ}
390 \label{fig:mq:stack}
391 \end{figure}
393 Puede reaplicar un parche no aplicado o sustraído con la orden
394 \hgxcmd{mq}{qpush}. Esto crea un nuevo conjunto de cambios
395 correspondiente al parche, y los cambios del parche estarán presentes
396 de nuevo en el directorio de trabajo. Vea ejemplos de
397 \hgxcmd{mq}{qpop} y \hgxcmd{mq}{qpush} en acción en la
398 figura~\ref{ex:mq:qpop}. Vea que hemos sustraído uno o dos parches,
399 la salida de\hgxcmd{mq}{qseries} continúa igual, mientras que
400 \hgxcmd{mq}{qapplied} ha cambiado.
402 \begin{figure}[ht]
403 \interaction{mq.tutorial.qpop}
404 \caption{Modificar la pila de parches aplicados}
405 \label{ex:mq:qpop}
406 \end{figure}
408 \subsection{Introducir y sustraer muchos parches}
410 Mientras que \hgxcmd{mq}{qpush} y \hgxcmd{mq}{qpop} operan sobre un
411 único parche cada vez, puede introducir y sustraer varios parches de
412 una vez. La opción \hgxopt{mq}{qpush}{-a} de \hgxcmd{mq}{qpush}
413 introduce todos los cambios que no hayan sido aplicados, mientras que
414 la opción \hgxopt{mq}{qpop}{-a} de \hgxcmd{mq}{qpop} sustrae todos los
415 cambios aplicados. (Vea la sección~\ref{sec:mq:perf} más adelante
416 en la cual se explican otras formas de de introducir y sustraer varios
417 cambios.)
419 \begin{figure}[ht]
420 \interaction{mq.tutorial.qpush-a}
421 \caption{Pushing all unapplied patches}
422 \label{ex:mq:qpush-a}
423 \end{figure}
425 \subsection{Medidas de seguridad y cómo saltarlas}
427 Muchas órdenes MQ revisan el directorio de trabajo antes de hacer
428 cualquier cosa, y fallan si encuentran alguna modificación. Lo hacen
429 para garantizar que usted no pierda cambio alguno de los que haya
430 hecho, pero que no hayan sido incorporados en algún parche. La
431 figura~\ref{ex:mq:add} ilusta esto; la orden \hgxcmd{mq}{qnew} no
432 creará un nuevo parche si hay cambios notorios, causados en este caso
433 por aplicado la orden \hgcmd{add} a \filename{file3}.
435 \begin{figure}[ht]
436 \interaction{mq.tutorial.add}
437 \caption{Crear un parche a la fuerza}
438 \label{ex:mq:add}
439 \end{figure}
441 Las órdenes que revisan el directorio actual cuentan con una opción
442 ``Se lo que estoy haciendo'', que siempre está nombrada como
443 \option{-f}. El significado exacto de \option{-f} depende de la
444 orden. Por ejemplo, \hgcmdargs{qnew}{\hgxopt{mq}{qnew}{-f}}
445 incorporarán cualquier cambio notorio en el nuevo parche que crea pero
446 \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-f}} revertirá las modificaciones a
447 cualquier fichero que haya sido afectado por el parche que está siendo
448 sustraído. ¡Asegúrese de leer la documentación de la opción \option{-f}
449 de cada comando antes de usarla!
451 \subsection{Trabajar con varios parches a la vez}
453 La orden \hgxcmd{mq}{qrefresh} siempre refresca el \emph{último}
454 parche aplicado. Esto significa que usted puede suspender su trabajo
455 en un parche (refrescándolo), sustraerlo o introducirlo para lograr
456 que otro parche esté de último y trabajar en \emph{ese} parche por un
457 rato.
459 A continuación un ejemplo que ilustra cómo puede usar esta habilidad.
460 Digamos que está desarrollando una nueva característica en dos
461 parches. El primero es un cambio en la parte fundamental de su
462 programa, y el segundo--sobre el primero---cambia la interfaz de
463 usuario para usar el código que ha añadido a la parte fundamental. Si
464 ve que hay un fallo en la parte fundamental mientras está trabajando
465 en el parche de UI\ndt{Interfaz de Usuario, User Interface en inglés}, es fácil arreglar la parte fundamental.
466 Simplemente use \hgxcmd{mq}{qrefresh} sobre el parche de la UI para
467 guardar los cambios de su trabajo en progreso, y use \hgxcmd{mq}{qpop}
468 para sacar sustraer el parche de la parte fundamental. Arregla el
469 fallo sobre la parte fundamental, aplique \hgxcmd{mq}{qrefresh} sobre
470 el parche fundamental, y aplique \hgxcmd{mq}{qpush} sobre el parche de
471 UI para continuar donde había quedado.
473 \section{Más acerca de parches}
474 \label{sec:mq:adv-patch}
476 MQ usa la orden GNU \command{patch} para aplicar los parches, por lo
477 tanto es útil conocer ciertos detalles de cómo trabaja
478 \command{patch}, y también acerca de los parches.
480 \subsection{La cantidad de franjas}
482 Si ve el encabezado de un parche, notará que la ruta al archivo tiene
483 un componente adicional al principio, que no está presente en la
484 ruta. Esta es una traza de cómo generaba anteriormente los parches la
485 gente(algunos aún lo hacen, pero es raro con las herramientas de
486 control de revisiones del actuales).
488 Alicia desempaquetaría un comprimido, editaría sus archivos, y querría
489 crear un parche. Por lo tanto ella renombraría su directorio de
490 trabajo, desempacaría el comprimido de nuevo(para lo cual necesitó el
491 renombramiento), y usaría las opciones \cmdopt{diff}{-r} y
492 \cmdopt{diff}{-N} de \command{diff} para generar recursivamente un
493 parche entre el directorio original y el modificado. El resultado
494 sería que el nombre del directorio original estaría al principio de
495 toda ruta en cada encabezado de fichero, y el nombre del directorio
496 modificado estaría al frente de la porción derecha de la ruta del
497 archivo.
499 Since someone receiving a patch from the Alices of the net would be
500 unlikely to have unmodified and modified directories with exactly the
501 same names, the \command{patch} command has a \cmdopt{patch}{-p}
502 option that indicates the number of leading path name components to
503 strip when trying to apply a patch. This number is called the
504 \emph{strip count}.
506 An option of ``\texttt{-p1}'' means ``use a strip count of one''. If
507 \command{patch} sees a file name \filename{foo/bar/baz} in a file
508 header, it will strip \filename{foo} and try to patch a file named
509 \filename{bar/baz}. (Strictly speaking, the strip count refers to the
510 number of \emph{path separators} (and the components that go with them
511 ) to strip. A strip count of one will turn \filename{foo/bar} into
512 \filename{bar}, but \filename{/foo/bar} (notice the extra leading
513 slash) into \filename{foo/bar}.)
515 The ``standard'' strip count for patches is one; almost all patches
516 contain one leading path name component that needs to be stripped.
517 Mercurial's \hgcmd{diff} command generates path names in this form,
518 and the \hgcmd{import} command and MQ expect patches to have a strip
519 count of one.
521 If you receive a patch from someone that you want to add to your patch
522 queue, and the patch needs a strip count other than one, you cannot
523 just \hgxcmd{mq}{qimport} the patch, because \hgxcmd{mq}{qimport} does not yet
524 have a \texttt{-p} option (see~\bug{311}). Your best bet is to
525 \hgxcmd{mq}{qnew} a patch of your own, then use \cmdargs{patch}{-p\emph{N}}
526 to apply their patch, followed by \hgcmd{addremove} to pick up any
527 files added or removed by the patch, followed by \hgxcmd{mq}{qrefresh}.
528 This complexity may become unnecessary; see~\bug{311} for details.
529 \subsection{Strategies for applying a patch}
531 When \command{patch} applies a hunk, it tries a handful of
532 successively less accurate strategies to try to make the hunk apply.
533 This falling-back technique often makes it possible to take a patch
534 that was generated against an old version of a file, and apply it
535 against a newer version of that file.
537 First, \command{patch} tries an exact match, where the line numbers,
538 the context, and the text to be modified must apply exactly. If it
539 cannot make an exact match, it tries to find an exact match for the
540 context, without honouring the line numbering information. If this
541 succeeds, it prints a line of output saying that the hunk was applied,
542 but at some \emph{offset} from the original line number.
544 If a context-only match fails, \command{patch} removes the first and
545 last lines of the context, and tries a \emph{reduced} context-only
546 match. If the hunk with reduced context succeeds, it prints a message
547 saying that it applied the hunk with a \emph{fuzz factor} (the number
548 after the fuzz factor indicates how many lines of context
549 \command{patch} had to trim before the patch applied).
551 When neither of these techniques works, \command{patch} prints a
552 message saying that the hunk in question was rejected. It saves
553 rejected hunks (also simply called ``rejects'') to a file with the
554 same name, and an added \sfilename{.rej} extension. It also saves an
555 unmodified copy of the file with a \sfilename{.orig} extension; the
556 copy of the file without any extensions will contain any changes made
557 by hunks that \emph{did} apply cleanly. If you have a patch that
558 modifies \filename{foo} with six hunks, and one of them fails to
559 apply, you will have: an unmodified \filename{foo.orig}, a
560 \filename{foo.rej} containing one hunk, and \filename{foo}, containing
561 the changes made by the five successful five hunks.
563 \subsection{Some quirks of patch representation}
565 There are a few useful things to know about how \command{patch} works
566 with files.
567 \begin{itemize}
568 \item This should already be obvious, but \command{patch} cannot
569 handle binary files.
570 \item Neither does it care about the executable bit; it creates new
571 files as readable, but not executable.
572 \item \command{patch} treats the removal of a file as a diff between
573 the file to be removed and the empty file. So your idea of ``I
574 deleted this file'' looks like ``every line of this file was
575 deleted'' in a patch.
576 \item It treats the addition of a file as a diff between the empty
577 file and the file to be added. So in a patch, your idea of ``I
578 added this file'' looks like ``every line of this file was added''.
579 \item It treats a renamed file as the removal of the old name, and the
580 addition of the new name. This means that renamed files have a big
581 footprint in patches. (Note also that Mercurial does not currently
582 try to infer when files have been renamed or copied in a patch.)
583 \item \command{patch} cannot represent empty files, so you cannot use
584 a patch to represent the notion ``I added this empty file to the
585 tree''.
586 \end{itemize}
587 \subsection{Beware the fuzz}
589 While applying a hunk at an offset, or with a fuzz factor, will often
590 be completely successful, these inexact techniques naturally leave
591 open the possibility of corrupting the patched file. The most common
592 cases typically involve applying a patch twice, or at an incorrect
593 location in the file. If \command{patch} or \hgxcmd{mq}{qpush} ever
594 mentions an offset or fuzz factor, you should make sure that the
595 modified files are correct afterwards.
597 It's often a good idea to refresh a patch that has applied with an
598 offset or fuzz factor; refreshing the patch generates new context
599 information that will make it apply cleanly. I say ``often,'' not
600 ``always,'' because sometimes refreshing a patch will make it fail to
601 apply against a different revision of the underlying files. In some
602 cases, such as when you're maintaining a patch that must sit on top of
603 multiple versions of a source tree, it's acceptable to have a patch
604 apply with some fuzz, provided you've verified the results of the
605 patching process in such cases.
607 \subsection{Handling rejection}
609 If \hgxcmd{mq}{qpush} fails to apply a patch, it will print an error
610 message and exit. If it has left \sfilename{.rej} files behind, it is
611 usually best to fix up the rejected hunks before you push more patches
612 or do any further work.
614 If your patch \emph{used to} apply cleanly, and no longer does because
615 you've changed the underlying code that your patches are based on,
616 Mercurial Queues can help; see section~\ref{sec:mq:merge} for details.
618 Unfortunately, there aren't any great techniques for dealing with
619 rejected hunks. Most often, you'll need to view the \sfilename{.rej}
620 file and edit the target file, applying the rejected hunks by hand.
622 If you're feeling adventurous, Neil Brown, a Linux kernel hacker,
623 wrote a tool called \command{wiggle}~\cite{web:wiggle}, which is more
624 vigorous than \command{patch} in its attempts to make a patch apply.
626 Another Linux kernel hacker, Chris Mason (the author of Mercurial
627 Queues), wrote a similar tool called
628 \command{mpatch}~\cite{web:mpatch}, which takes a simple approach to
629 automating the application of hunks rejected by \command{patch}. The
630 \command{mpatch} command can help with four common reasons that a hunk
631 may be rejected:
633 \begin{itemize}
634 \item The context in the middle of a hunk has changed.
635 \item A hunk is missing some context at the beginning or end.
636 \item A large hunk might apply better---either entirely or in
637 part---if it was broken up into smaller hunks.
638 \item A hunk removes lines with slightly different content than those
639 currently present in the file.
640 \end{itemize}
642 If you use \command{wiggle} or \command{mpatch}, you should be doubly
643 careful to check your results when you're done. In fact,
644 \command{mpatch} enforces this method of double-checking the tool's
645 output, by automatically dropping you into a merge program when it has
646 done its job, so that you can verify its work and finish off any
647 remaining merges.
649 \section{Getting the best performance out of MQ}
650 \label{sec:mq:perf}
652 MQ is very efficient at handling a large number of patches. I ran
653 some performance experiments in mid-2006 for a talk that I gave at the
654 2006 EuroPython conference~\cite{web:europython}. I used as my data
655 set the Linux 2.6.17-mm1 patch series, which consists of 1,738
656 patches. I applied these on top of a Linux kernel repository
657 containing all 27,472 revisions between Linux 2.6.12-rc2 and Linux
658 2.6.17.
660 On my old, slow laptop, I was able to
661 \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-a}} all 1,738 patches in 3.5 minutes,
662 and \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}} them all in 30 seconds. (On a
663 newer laptop, the time to push all patches dropped to two minutes.) I
664 could \hgxcmd{mq}{qrefresh} one of the biggest patches (which made 22,779
665 lines of changes to 287 files) in 6.6 seconds.
667 Clearly, MQ is well suited to working in large trees, but there are a
668 few tricks you can use to get the best performance of it.
670 First of all, try to ``batch'' operations together. Every time you
671 run \hgxcmd{mq}{qpush} or \hgxcmd{mq}{qpop}, these commands scan the working
672 directory once to make sure you haven't made some changes and then
673 forgotten to run \hgxcmd{mq}{qrefresh}. On a small tree, the time that
674 this scan takes is unnoticeable. However, on a medium-sized tree
675 (containing tens of thousands of files), it can take a second or more.
677 The \hgxcmd{mq}{qpush} and \hgxcmd{mq}{qpop} commands allow you to push and pop
678 multiple patches at a time. You can identify the ``destination
679 patch'' that you want to end up at. When you \hgxcmd{mq}{qpush} with a
680 destination specified, it will push patches until that patch is at the
681 top of the applied stack. When you \hgxcmd{mq}{qpop} to a destination, MQ
682 will pop patches until the destination patch is at the top.
684 You can identify a destination patch using either the name of the
685 patch, or by number. If you use numeric addressing, patches are
686 counted from zero; this means that the first patch is zero, the second
687 is one, and so on.
689 \section{Updating your patches when the underlying code changes}
690 \label{sec:mq:merge}
692 It's common to have a stack of patches on top of an underlying
693 repository that you don't modify directly. If you're working on
694 changes to third-party code, or on a feature that is taking longer to
695 develop than the rate of change of the code beneath, you will often
696 need to sync up with the underlying code, and fix up any hunks in your
697 patches that no longer apply. This is called \emph{rebasing} your
698 patch series.
700 The simplest way to do this is to \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}}
701 your patches, then \hgcmd{pull} changes into the underlying
702 repository, and finally \hgcmdargs{qpush}{\hgxopt{mq}{qpop}{-a}} your
703 patches again. MQ will stop pushing any time it runs across a patch
704 that fails to apply during conflicts, allowing you to fix your
705 conflicts, \hgxcmd{mq}{qrefresh} the affected patch, and continue pushing
706 until you have fixed your entire stack.
708 This approach is easy to use and works well if you don't expect
709 changes to the underlying code to affect how well your patches apply.
710 If your patch stack touches code that is modified frequently or
711 invasively in the underlying repository, however, fixing up rejected
712 hunks by hand quickly becomes tiresome.
714 It's possible to partially automate the rebasing process. If your
715 patches apply cleanly against some revision of the underlying repo, MQ
716 can use this information to help you to resolve conflicts between your
717 patches and a different revision.
719 The process is a little involved.
720 \begin{enumerate}
721 \item To begin, \hgcmdargs{qpush}{-a} all of your patches on top of
722 the revision where you know that they apply cleanly.
723 \item Save a backup copy of your patch directory using
724 \hgcmdargs{qsave}{\hgxopt{mq}{qsave}{-e} \hgxopt{mq}{qsave}{-c}}. This prints
725 the name of the directory that it has saved the patches in. It will
726 save the patches to a directory called
727 \sdirname{.hg/patches.\emph{N}}, where \texttt{\emph{N}} is a small
728 integer. It also commits a ``save changeset'' on top of your
729 applied patches; this is for internal book-keeping, and records the
730 states of the \sfilename{series} and \sfilename{status} files.
731 \item Use \hgcmd{pull} to bring new changes into the underlying
732 repository. (Don't run \hgcmdargs{pull}{-u}; see below for why.)
733 \item Update to the new tip revision, using
734 \hgcmdargs{update}{\hgopt{update}{-C}} to override the patches you
735 have pushed.
736 \item Merge all patches using \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-m}
737 \hgxopt{mq}{qpush}{-a}}. The \hgxopt{mq}{qpush}{-m} option to \hgxcmd{mq}{qpush}
738 tells MQ to perform a three-way merge if the patch fails to apply.
739 \end{enumerate}
741 During the \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-m}}, each patch in the
742 \sfilename{series} file is applied normally. If a patch applies with
743 fuzz or rejects, MQ looks at the queue you \hgxcmd{mq}{qsave}d, and
744 performs a three-way merge with the corresponding changeset. This
745 merge uses Mercurial's normal merge machinery, so it may pop up a GUI
746 merge tool to help you to resolve problems.
748 When you finish resolving the effects of a patch, MQ refreshes your
749 patch based on the result of the merge.
751 At the end of this process, your repository will have one extra head
752 from the old patch queue, and a copy of the old patch queue will be in
753 \sdirname{.hg/patches.\emph{N}}. You can remove the extra head using
754 \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a} \hgxopt{mq}{qpop}{-n} patches.\emph{N}}
755 or \hgcmd{strip}. You can delete \sdirname{.hg/patches.\emph{N}} once
756 you are sure that you no longer need it as a backup.
758 \section{Identifying patches}
760 MQ commands that work with patches let you refer to a patch either by
761 using its name or by a number. By name is obvious enough; pass the
762 name \filename{foo.patch} to \hgxcmd{mq}{qpush}, for example, and it will
763 push patches until \filename{foo.patch} is applied.
765 As a shortcut, you can refer to a patch using both a name and a
766 numeric offset; \texttt{foo.patch-2} means ``two patches before
767 \texttt{foo.patch}'', while \texttt{bar.patch+4} means ``four patches
768 after \texttt{bar.patch}''.
770 Referring to a patch by index isn't much different. The first patch
771 printed in the output of \hgxcmd{mq}{qseries} is patch zero (yes, it's one
772 of those start-at-zero counting systems); the second is patch one; and
773 so on.
775 MQ also makes it easy to work with patches when you are using normal
776 Mercurial commands. Every command that accepts a changeset ID will
777 also accept the name of an applied patch. MQ augments the tags
778 normally in the repository with an eponymous one for each applied
779 patch. In addition, the special tags \index{tags!special tag
780 names!\texttt{qbase}}\texttt{qbase} and \index{tags!special tag
781 names!\texttt{qtip}}\texttt{qtip} identify the ``bottom-most'' and
782 topmost applied patches, respectively.
784 These additions to Mercurial's normal tagging capabilities make
785 dealing with patches even more of a breeze.
786 \begin{itemize}
787 \item Want to patchbomb a mailing list with your latest series of
788 changes?
789 \begin{codesample4}
790 hg email qbase:qtip
791 \end{codesample4}
792 (Don't know what ``patchbombing'' is? See
793 section~\ref{sec:hgext:patchbomb}.)
794 \item Need to see all of the patches since \texttt{foo.patch} that
795 have touched files in a subdirectory of your tree?
796 \begin{codesample4}
797 hg log -r foo.patch:qtip \emph{subdir}
798 \end{codesample4}
799 \end{itemize}
801 Because MQ makes the names of patches available to the rest of
802 Mercurial through its normal internal tag machinery, you don't need to
803 type in the entire name of a patch when you want to identify it by
804 name.
806 \begin{figure}[ht]
807 \interaction{mq.id.output}
808 \caption{Using MQ's tag features to work with patches}
809 \label{ex:mq:id}
810 \end{figure}
812 Another nice consequence of representing patch names as tags is that
813 when you run the \hgcmd{log} command, it will display a patch's name
814 as a tag, simply as part of its normal output. This makes it easy to
815 visually distinguish applied patches from underlying ``normal''
816 revisions. Figure~\ref{ex:mq:id} shows a few normal Mercurial
817 commands in use with applied patches.
819 \section{Useful things to know about}
821 There are a number of aspects of MQ usage that don't fit tidily into
822 sections of their own, but that are good to know. Here they are, in
823 one place.
825 \begin{itemize}
826 \item Normally, when you \hgxcmd{mq}{qpop} a patch and \hgxcmd{mq}{qpush} it
827 again, the changeset that represents the patch after the pop/push
828 will have a \emph{different identity} than the changeset that
829 represented the hash beforehand. See
830 section~\ref{sec:mqref:cmd:qpush} for information as to why this is.
831 \item It's not a good idea to \hgcmd{merge} changes from another
832 branch with a patch changeset, at least if you want to maintain the
833 ``patchiness'' of that changeset and changesets below it on the
834 patch stack. If you try to do this, it will appear to succeed, but
835 MQ will become confused.
836 \end{itemize}
838 \section{Managing patches in a repository}
839 \label{sec:mq:repo}
841 Because MQ's \sdirname{.hg/patches} directory resides outside a
842 Mercurial repository's working directory, the ``underlying'' Mercurial
843 repository knows nothing about the management or presence of patches.
845 This presents the interesting possibility of managing the contents of
846 the patch directory as a Mercurial repository in its own right. This
847 can be a useful way to work. For example, you can work on a patch for
848 a while, \hgxcmd{mq}{qrefresh} it, then \hgcmd{commit} the current state of
849 the patch. This lets you ``roll back'' to that version of the patch
850 later on.
852 You can then share different versions of the same patch stack among
853 multiple underlying repositories. I use this when I am developing a
854 Linux kernel feature. I have a pristine copy of my kernel sources for
855 each of several CPU architectures, and a cloned repository under each
856 that contains the patches I am working on. When I want to test a
857 change on a different architecture, I push my current patches to the
858 patch repository associated with that kernel tree, pop and push all of
859 my patches, and build and test that kernel.
861 Managing patches in a repository makes it possible for multiple
862 developers to work on the same patch series without colliding with
863 each other, all on top of an underlying source base that they may or
864 may not control.
866 \subsection{MQ support for patch repositories}
868 MQ helps you to work with the \sdirname{.hg/patches} directory as a
869 repository; when you prepare a repository for working with patches
870 using \hgxcmd{mq}{qinit}, you can pass the \hgxopt{mq}{qinit}{-c} option to
871 create the \sdirname{.hg/patches} directory as a Mercurial repository.
873 \begin{note}
874 If you forget to use the \hgxopt{mq}{qinit}{-c} option, you can simply go
875 into the \sdirname{.hg/patches} directory at any time and run
876 \hgcmd{init}. Don't forget to add an entry for the
877 \sfilename{status} file to the \sfilename{.hgignore} file, though
879 (\hgcmdargs{qinit}{\hgxopt{mq}{qinit}{-c}} does this for you
880 automatically); you \emph{really} don't want to manage the
881 \sfilename{status} file.
882 \end{note}
884 As a convenience, if MQ notices that the \dirname{.hg/patches}
885 directory is a repository, it will automatically \hgcmd{add} every
886 patch that you create and import.
888 MQ provides a shortcut command, \hgxcmd{mq}{qcommit}, that runs
889 \hgcmd{commit} in the \sdirname{.hg/patches} directory. This saves
890 some bothersome typing.
892 Finally, as a convenience to manage the patch directory, you can
893 define the alias \command{mq} on Unix systems. For example, on Linux
894 systems using the \command{bash} shell, you can include the following
895 snippet in your \tildefile{.bashrc}.
897 \begin{codesample2}
898 alias mq=`hg -R \$(hg root)/.hg/patches'
899 \end{codesample2}
901 You can then issue commands of the form \cmdargs{mq}{pull} from
902 the main repository.
904 \subsection{A few things to watch out for}
906 MQ's support for working with a repository full of patches is limited
907 in a few small respects.
909 MQ cannot automatically detect changes that you make to the patch
910 directory. If you \hgcmd{pull}, manually edit, or \hgcmd{update}
911 changes to patches or the \sfilename{series} file, you will have to
912 \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}} and then
913 \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-a}} in the underlying repository to
914 see those changes show up there. If you forget to do this, you can
915 confuse MQ's idea of which patches are applied.
917 \section{Third party tools for working with patches}
918 \label{sec:mq:tools}
920 Once you've been working with patches for a while, you'll find
921 yourself hungry for tools that will help you to understand and
922 manipulate the patches you're dealing with.
924 The \command{diffstat} command~\cite{web:diffstat} generates a
925 histogram of the modifications made to each file in a patch. It
926 provides a good way to ``get a sense of'' a patch---which files it
927 affects, and how much change it introduces to each file and as a
928 whole. (I find that it's a good idea to use \command{diffstat}'s
929 \cmdopt{diffstat}{-p} option as a matter of course, as otherwise it
930 will try to do clever things with prefixes of file names that
931 inevitably confuse at least me.)
933 \begin{figure}[ht]
934 \interaction{mq.tools.tools}
935 \caption{The \command{diffstat}, \command{filterdiff}, and \command{lsdiff} commands}
936 \label{ex:mq:tools}
937 \end{figure}
939 The \package{patchutils} package~\cite{web:patchutils} is invaluable.
940 It provides a set of small utilities that follow the ``Unix
941 philosophy;'' each does one useful thing with a patch. The
942 \package{patchutils} command I use most is \command{filterdiff}, which
943 extracts subsets from a patch file. For example, given a patch that
944 modifies hundreds of files across dozens of directories, a single
945 invocation of \command{filterdiff} can generate a smaller patch that
946 only touches files whose names match a particular glob pattern. See
947 section~\ref{mq-collab:tips:interdiff} for another example.
949 \section{Good ways to work with patches}
951 Whether you are working on a patch series to submit to a free software
952 or open source project, or a series that you intend to treat as a
953 sequence of regular changesets when you're done, you can use some
954 simple techniques to keep your work well organised.
956 Give your patches descriptive names. A good name for a patch might be
957 \filename{rework-device-alloc.patch}, because it will immediately give
958 you a hint what the purpose of the patch is. Long names shouldn't be
959 a problem; you won't be typing the names often, but you \emph{will} be
960 running commands like \hgxcmd{mq}{qapplied} and \hgxcmd{mq}{qtop} over and over.
961 Good naming becomes especially important when you have a number of
962 patches to work with, or if you are juggling a number of different
963 tasks and your patches only get a fraction of your attention.
965 Be aware of what patch you're working on. Use the \hgxcmd{mq}{qtop}
966 command and skim over the text of your patches frequently---for
967 example, using \hgcmdargs{tip}{\hgopt{tip}{-p}})---to be sure of where
968 you stand. I have several times worked on and \hgxcmd{mq}{qrefresh}ed a
969 patch other than the one I intended, and it's often tricky to migrate
970 changes into the right patch after making them in the wrong one.
972 For this reason, it is very much worth investing a little time to
973 learn how to use some of the third-party tools I described in
974 section~\ref{sec:mq:tools}, particularly \command{diffstat} and
975 \command{filterdiff}. The former will give you a quick idea of what
976 changes your patch is making, while the latter makes it easy to splice
977 hunks selectively out of one patch and into another.
979 \section{MQ cookbook}
981 \subsection{Manage ``trivial'' patches}
983 Because the overhead of dropping files into a new Mercurial repository
984 is so low, it makes a lot of sense to manage patches this way even if
985 you simply want to make a few changes to a source tarball that you
986 downloaded.
988 Begin by downloading and unpacking the source tarball,
989 and turning it into a Mercurial repository.
990 \interaction{mq.tarball.download}
992 Continue by creating a patch stack and making your changes.
993 \interaction{mq.tarball.qinit}
995 Let's say a few weeks or months pass, and your package author releases
996 a new version. First, bring their changes into the repository.
997 \interaction{mq.tarball.newsource}
998 The pipeline starting with \hgcmd{locate} above deletes all files in
999 the working directory, so that \hgcmd{commit}'s
1000 \hgopt{commit}{--addremove} option can actually tell which files have
1001 really been removed in the newer version of the source.
1003 Finally, you can apply your patches on top of the new tree.
1004 \interaction{mq.tarball.repush}
1006 \subsection{Combining entire patches}
1007 \label{sec:mq:combine}
1009 MQ provides a command, \hgxcmd{mq}{qfold} that lets you combine entire
1010 patches. This ``folds'' the patches you name, in the order you name
1011 them, into the topmost applied patch, and concatenates their
1012 descriptions onto the end of its description. The patches that you
1013 fold must be unapplied before you fold them.
1015 The order in which you fold patches matters. If your topmost applied
1016 patch is \texttt{foo}, and you \hgxcmd{mq}{qfold} \texttt{bar} and
1017 \texttt{quux} into it, you will end up with a patch that has the same
1018 effect as if you applied first \texttt{foo}, then \texttt{bar},
1019 followed by \texttt{quux}.
1021 \subsection{Merging part of one patch into another}
1023 Merging \emph{part} of one patch into another is more difficult than
1024 combining entire patches.
1026 If you want to move changes to entire files, you can use
1027 \command{filterdiff}'s \cmdopt{filterdiff}{-i} and
1028 \cmdopt{filterdiff}{-x} options to choose the modifications to snip
1029 out of one patch, concatenating its output onto the end of the patch
1030 you want to merge into. You usually won't need to modify the patch
1031 you've merged the changes from. Instead, MQ will report some rejected
1032 hunks when you \hgxcmd{mq}{qpush} it (from the hunks you moved into the
1033 other patch), and you can simply \hgxcmd{mq}{qrefresh} the patch to drop
1034 the duplicate hunks.
1036 If you have a patch that has multiple hunks modifying a file, and you
1037 only want to move a few of those hunks, the job becomes more messy,
1038 but you can still partly automate it. Use \cmdargs{lsdiff}{-nvv} to
1039 print some metadata about the patch.
1040 \interaction{mq.tools.lsdiff}
1042 This command prints three different kinds of number:
1043 \begin{itemize}
1044 \item (in the first column) a \emph{file number} to identify each file
1045 modified in the patch;
1046 \item (on the next line, indented) the line number within a modified
1047 file where a hunk starts; and
1048 \item (on the same line) a \emph{hunk number} to identify that hunk.
1049 \end{itemize}
1051 You'll have to use some visual inspection, and reading of the patch,
1052 to identify the file and hunk numbers you'll want, but you can then
1053 pass them to to \command{filterdiff}'s \cmdopt{filterdiff}{--files}
1054 and \cmdopt{filterdiff}{--hunks} options, to select exactly the file
1055 and hunk you want to extract.
1057 Once you have this hunk, you can concatenate it onto the end of your
1058 destination patch and continue with the remainder of
1059 section~\ref{sec:mq:combine}.
1061 \section{Differences between quilt and MQ}
1063 If you are already familiar with quilt, MQ provides a similar command
1064 set. There are a few differences in the way that it works.
1066 You will already have noticed that most quilt commands have MQ
1067 counterparts that simply begin with a ``\texttt{q}''. The exceptions
1068 are quilt's \texttt{add} and \texttt{remove} commands, the
1069 counterparts for which are the normal Mercurial \hgcmd{add} and
1070 \hgcmd{remove} commands. There is no MQ equivalent of the quilt
1071 \texttt{edit} command.
1073 %%% Local Variables:
1074 %%% mode: latex
1075 %%% TeX-master: "00book"
1076 %%% End: