hgbook

view es/mq.tex @ 443:2daeda01fe98

Started mq, please do look the translation terms about push and pop on this context
author Igor TAmara <igor@tamarapatino.org>
date Sun Dec 07 17:47:38 2008 -0500 (2008-12-07)
parents aeda195f54a6
children da4d34e0e250
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{More about patches}
474 \label{sec:mq:adv-patch}
476 MQ uses the GNU \command{patch} command to apply patches, so it's
477 helpful to know a few more detailed aspects of how \command{patch}
478 works, and about patches themselves.
480 \subsection{The strip count}
482 If you look at the file headers in a patch, you will notice that the
483 pathnames usually have an extra component on the front that isn't
484 present in the actual path name. This is a holdover from the way that
485 people used to generate patches (people still do this, but it's
486 somewhat rare with modern revision control tools).
488 Alice would unpack a tarball, edit her files, then decide that she
489 wanted to create a patch. So she'd rename her working directory,
490 unpack the tarball again (hence the need for the rename), and use the
491 \cmdopt{diff}{-r} and \cmdopt{diff}{-N} options to \command{diff} to
492 recursively generate a patch between the unmodified directory and the
493 modified one. The result would be that the name of the unmodified
494 directory would be at the front of the left-hand path in every file
495 header, and the name of the modified directory would be at the front
496 of the right-hand path.
498 Since someone receiving a patch from the Alices of the net would be
499 unlikely to have unmodified and modified directories with exactly the
500 same names, the \command{patch} command has a \cmdopt{patch}{-p}
501 option that indicates the number of leading path name components to
502 strip when trying to apply a patch. This number is called the
503 \emph{strip count}.
505 An option of ``\texttt{-p1}'' means ``use a strip count of one''. If
506 \command{patch} sees a file name \filename{foo/bar/baz} in a file
507 header, it will strip \filename{foo} and try to patch a file named
508 \filename{bar/baz}. (Strictly speaking, the strip count refers to the
509 number of \emph{path separators} (and the components that go with them
510 ) to strip. A strip count of one will turn \filename{foo/bar} into
511 \filename{bar}, but \filename{/foo/bar} (notice the extra leading
512 slash) into \filename{foo/bar}.)
514 The ``standard'' strip count for patches is one; almost all patches
515 contain one leading path name component that needs to be stripped.
516 Mercurial's \hgcmd{diff} command generates path names in this form,
517 and the \hgcmd{import} command and MQ expect patches to have a strip
518 count of one.
520 If you receive a patch from someone that you want to add to your patch
521 queue, and the patch needs a strip count other than one, you cannot
522 just \hgxcmd{mq}{qimport} the patch, because \hgxcmd{mq}{qimport} does not yet
523 have a \texttt{-p} option (see~\bug{311}). Your best bet is to
524 \hgxcmd{mq}{qnew} a patch of your own, then use \cmdargs{patch}{-p\emph{N}}
525 to apply their patch, followed by \hgcmd{addremove} to pick up any
526 files added or removed by the patch, followed by \hgxcmd{mq}{qrefresh}.
527 This complexity may become unnecessary; see~\bug{311} for details.
528 \subsection{Strategies for applying a patch}
530 When \command{patch} applies a hunk, it tries a handful of
531 successively less accurate strategies to try to make the hunk apply.
532 This falling-back technique often makes it possible to take a patch
533 that was generated against an old version of a file, and apply it
534 against a newer version of that file.
536 First, \command{patch} tries an exact match, where the line numbers,
537 the context, and the text to be modified must apply exactly. If it
538 cannot make an exact match, it tries to find an exact match for the
539 context, without honouring the line numbering information. If this
540 succeeds, it prints a line of output saying that the hunk was applied,
541 but at some \emph{offset} from the original line number.
543 If a context-only match fails, \command{patch} removes the first and
544 last lines of the context, and tries a \emph{reduced} context-only
545 match. If the hunk with reduced context succeeds, it prints a message
546 saying that it applied the hunk with a \emph{fuzz factor} (the number
547 after the fuzz factor indicates how many lines of context
548 \command{patch} had to trim before the patch applied).
550 When neither of these techniques works, \command{patch} prints a
551 message saying that the hunk in question was rejected. It saves
552 rejected hunks (also simply called ``rejects'') to a file with the
553 same name, and an added \sfilename{.rej} extension. It also saves an
554 unmodified copy of the file with a \sfilename{.orig} extension; the
555 copy of the file without any extensions will contain any changes made
556 by hunks that \emph{did} apply cleanly. If you have a patch that
557 modifies \filename{foo} with six hunks, and one of them fails to
558 apply, you will have: an unmodified \filename{foo.orig}, a
559 \filename{foo.rej} containing one hunk, and \filename{foo}, containing
560 the changes made by the five successful five hunks.
562 \subsection{Some quirks of patch representation}
564 There are a few useful things to know about how \command{patch} works
565 with files.
566 \begin{itemize}
567 \item This should already be obvious, but \command{patch} cannot
568 handle binary files.
569 \item Neither does it care about the executable bit; it creates new
570 files as readable, but not executable.
571 \item \command{patch} treats the removal of a file as a diff between
572 the file to be removed and the empty file. So your idea of ``I
573 deleted this file'' looks like ``every line of this file was
574 deleted'' in a patch.
575 \item It treats the addition of a file as a diff between the empty
576 file and the file to be added. So in a patch, your idea of ``I
577 added this file'' looks like ``every line of this file was added''.
578 \item It treats a renamed file as the removal of the old name, and the
579 addition of the new name. This means that renamed files have a big
580 footprint in patches. (Note also that Mercurial does not currently
581 try to infer when files have been renamed or copied in a patch.)
582 \item \command{patch} cannot represent empty files, so you cannot use
583 a patch to represent the notion ``I added this empty file to the
584 tree''.
585 \end{itemize}
586 \subsection{Beware the fuzz}
588 While applying a hunk at an offset, or with a fuzz factor, will often
589 be completely successful, these inexact techniques naturally leave
590 open the possibility of corrupting the patched file. The most common
591 cases typically involve applying a patch twice, or at an incorrect
592 location in the file. If \command{patch} or \hgxcmd{mq}{qpush} ever
593 mentions an offset or fuzz factor, you should make sure that the
594 modified files are correct afterwards.
596 It's often a good idea to refresh a patch that has applied with an
597 offset or fuzz factor; refreshing the patch generates new context
598 information that will make it apply cleanly. I say ``often,'' not
599 ``always,'' because sometimes refreshing a patch will make it fail to
600 apply against a different revision of the underlying files. In some
601 cases, such as when you're maintaining a patch that must sit on top of
602 multiple versions of a source tree, it's acceptable to have a patch
603 apply with some fuzz, provided you've verified the results of the
604 patching process in such cases.
606 \subsection{Handling rejection}
608 If \hgxcmd{mq}{qpush} fails to apply a patch, it will print an error
609 message and exit. If it has left \sfilename{.rej} files behind, it is
610 usually best to fix up the rejected hunks before you push more patches
611 or do any further work.
613 If your patch \emph{used to} apply cleanly, and no longer does because
614 you've changed the underlying code that your patches are based on,
615 Mercurial Queues can help; see section~\ref{sec:mq:merge} for details.
617 Unfortunately, there aren't any great techniques for dealing with
618 rejected hunks. Most often, you'll need to view the \sfilename{.rej}
619 file and edit the target file, applying the rejected hunks by hand.
621 If you're feeling adventurous, Neil Brown, a Linux kernel hacker,
622 wrote a tool called \command{wiggle}~\cite{web:wiggle}, which is more
623 vigorous than \command{patch} in its attempts to make a patch apply.
625 Another Linux kernel hacker, Chris Mason (the author of Mercurial
626 Queues), wrote a similar tool called
627 \command{mpatch}~\cite{web:mpatch}, which takes a simple approach to
628 automating the application of hunks rejected by \command{patch}. The
629 \command{mpatch} command can help with four common reasons that a hunk
630 may be rejected:
632 \begin{itemize}
633 \item The context in the middle of a hunk has changed.
634 \item A hunk is missing some context at the beginning or end.
635 \item A large hunk might apply better---either entirely or in
636 part---if it was broken up into smaller hunks.
637 \item A hunk removes lines with slightly different content than those
638 currently present in the file.
639 \end{itemize}
641 If you use \command{wiggle} or \command{mpatch}, you should be doubly
642 careful to check your results when you're done. In fact,
643 \command{mpatch} enforces this method of double-checking the tool's
644 output, by automatically dropping you into a merge program when it has
645 done its job, so that you can verify its work and finish off any
646 remaining merges.
648 \section{Getting the best performance out of MQ}
649 \label{sec:mq:perf}
651 MQ is very efficient at handling a large number of patches. I ran
652 some performance experiments in mid-2006 for a talk that I gave at the
653 2006 EuroPython conference~\cite{web:europython}. I used as my data
654 set the Linux 2.6.17-mm1 patch series, which consists of 1,738
655 patches. I applied these on top of a Linux kernel repository
656 containing all 27,472 revisions between Linux 2.6.12-rc2 and Linux
657 2.6.17.
659 On my old, slow laptop, I was able to
660 \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-a}} all 1,738 patches in 3.5 minutes,
661 and \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}} them all in 30 seconds. (On a
662 newer laptop, the time to push all patches dropped to two minutes.) I
663 could \hgxcmd{mq}{qrefresh} one of the biggest patches (which made 22,779
664 lines of changes to 287 files) in 6.6 seconds.
666 Clearly, MQ is well suited to working in large trees, but there are a
667 few tricks you can use to get the best performance of it.
669 First of all, try to ``batch'' operations together. Every time you
670 run \hgxcmd{mq}{qpush} or \hgxcmd{mq}{qpop}, these commands scan the working
671 directory once to make sure you haven't made some changes and then
672 forgotten to run \hgxcmd{mq}{qrefresh}. On a small tree, the time that
673 this scan takes is unnoticeable. However, on a medium-sized tree
674 (containing tens of thousands of files), it can take a second or more.
676 The \hgxcmd{mq}{qpush} and \hgxcmd{mq}{qpop} commands allow you to push and pop
677 multiple patches at a time. You can identify the ``destination
678 patch'' that you want to end up at. When you \hgxcmd{mq}{qpush} with a
679 destination specified, it will push patches until that patch is at the
680 top of the applied stack. When you \hgxcmd{mq}{qpop} to a destination, MQ
681 will pop patches until the destination patch is at the top.
683 You can identify a destination patch using either the name of the
684 patch, or by number. If you use numeric addressing, patches are
685 counted from zero; this means that the first patch is zero, the second
686 is one, and so on.
688 \section{Updating your patches when the underlying code changes}
689 \label{sec:mq:merge}
691 It's common to have a stack of patches on top of an underlying
692 repository that you don't modify directly. If you're working on
693 changes to third-party code, or on a feature that is taking longer to
694 develop than the rate of change of the code beneath, you will often
695 need to sync up with the underlying code, and fix up any hunks in your
696 patches that no longer apply. This is called \emph{rebasing} your
697 patch series.
699 The simplest way to do this is to \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}}
700 your patches, then \hgcmd{pull} changes into the underlying
701 repository, and finally \hgcmdargs{qpush}{\hgxopt{mq}{qpop}{-a}} your
702 patches again. MQ will stop pushing any time it runs across a patch
703 that fails to apply during conflicts, allowing you to fix your
704 conflicts, \hgxcmd{mq}{qrefresh} the affected patch, and continue pushing
705 until you have fixed your entire stack.
707 This approach is easy to use and works well if you don't expect
708 changes to the underlying code to affect how well your patches apply.
709 If your patch stack touches code that is modified frequently or
710 invasively in the underlying repository, however, fixing up rejected
711 hunks by hand quickly becomes tiresome.
713 It's possible to partially automate the rebasing process. If your
714 patches apply cleanly against some revision of the underlying repo, MQ
715 can use this information to help you to resolve conflicts between your
716 patches and a different revision.
718 The process is a little involved.
719 \begin{enumerate}
720 \item To begin, \hgcmdargs{qpush}{-a} all of your patches on top of
721 the revision where you know that they apply cleanly.
722 \item Save a backup copy of your patch directory using
723 \hgcmdargs{qsave}{\hgxopt{mq}{qsave}{-e} \hgxopt{mq}{qsave}{-c}}. This prints
724 the name of the directory that it has saved the patches in. It will
725 save the patches to a directory called
726 \sdirname{.hg/patches.\emph{N}}, where \texttt{\emph{N}} is a small
727 integer. It also commits a ``save changeset'' on top of your
728 applied patches; this is for internal book-keeping, and records the
729 states of the \sfilename{series} and \sfilename{status} files.
730 \item Use \hgcmd{pull} to bring new changes into the underlying
731 repository. (Don't run \hgcmdargs{pull}{-u}; see below for why.)
732 \item Update to the new tip revision, using
733 \hgcmdargs{update}{\hgopt{update}{-C}} to override the patches you
734 have pushed.
735 \item Merge all patches using \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-m}
736 \hgxopt{mq}{qpush}{-a}}. The \hgxopt{mq}{qpush}{-m} option to \hgxcmd{mq}{qpush}
737 tells MQ to perform a three-way merge if the patch fails to apply.
738 \end{enumerate}
740 During the \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-m}}, each patch in the
741 \sfilename{series} file is applied normally. If a patch applies with
742 fuzz or rejects, MQ looks at the queue you \hgxcmd{mq}{qsave}d, and
743 performs a three-way merge with the corresponding changeset. This
744 merge uses Mercurial's normal merge machinery, so it may pop up a GUI
745 merge tool to help you to resolve problems.
747 When you finish resolving the effects of a patch, MQ refreshes your
748 patch based on the result of the merge.
750 At the end of this process, your repository will have one extra head
751 from the old patch queue, and a copy of the old patch queue will be in
752 \sdirname{.hg/patches.\emph{N}}. You can remove the extra head using
753 \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a} \hgxopt{mq}{qpop}{-n} patches.\emph{N}}
754 or \hgcmd{strip}. You can delete \sdirname{.hg/patches.\emph{N}} once
755 you are sure that you no longer need it as a backup.
757 \section{Identifying patches}
759 MQ commands that work with patches let you refer to a patch either by
760 using its name or by a number. By name is obvious enough; pass the
761 name \filename{foo.patch} to \hgxcmd{mq}{qpush}, for example, and it will
762 push patches until \filename{foo.patch} is applied.
764 As a shortcut, you can refer to a patch using both a name and a
765 numeric offset; \texttt{foo.patch-2} means ``two patches before
766 \texttt{foo.patch}'', while \texttt{bar.patch+4} means ``four patches
767 after \texttt{bar.patch}''.
769 Referring to a patch by index isn't much different. The first patch
770 printed in the output of \hgxcmd{mq}{qseries} is patch zero (yes, it's one
771 of those start-at-zero counting systems); the second is patch one; and
772 so on.
774 MQ also makes it easy to work with patches when you are using normal
775 Mercurial commands. Every command that accepts a changeset ID will
776 also accept the name of an applied patch. MQ augments the tags
777 normally in the repository with an eponymous one for each applied
778 patch. In addition, the special tags \index{tags!special tag
779 names!\texttt{qbase}}\texttt{qbase} and \index{tags!special tag
780 names!\texttt{qtip}}\texttt{qtip} identify the ``bottom-most'' and
781 topmost applied patches, respectively.
783 These additions to Mercurial's normal tagging capabilities make
784 dealing with patches even more of a breeze.
785 \begin{itemize}
786 \item Want to patchbomb a mailing list with your latest series of
787 changes?
788 \begin{codesample4}
789 hg email qbase:qtip
790 \end{codesample4}
791 (Don't know what ``patchbombing'' is? See
792 section~\ref{sec:hgext:patchbomb}.)
793 \item Need to see all of the patches since \texttt{foo.patch} that
794 have touched files in a subdirectory of your tree?
795 \begin{codesample4}
796 hg log -r foo.patch:qtip \emph{subdir}
797 \end{codesample4}
798 \end{itemize}
800 Because MQ makes the names of patches available to the rest of
801 Mercurial through its normal internal tag machinery, you don't need to
802 type in the entire name of a patch when you want to identify it by
803 name.
805 \begin{figure}[ht]
806 \interaction{mq.id.output}
807 \caption{Using MQ's tag features to work with patches}
808 \label{ex:mq:id}
809 \end{figure}
811 Another nice consequence of representing patch names as tags is that
812 when you run the \hgcmd{log} command, it will display a patch's name
813 as a tag, simply as part of its normal output. This makes it easy to
814 visually distinguish applied patches from underlying ``normal''
815 revisions. Figure~\ref{ex:mq:id} shows a few normal Mercurial
816 commands in use with applied patches.
818 \section{Useful things to know about}
820 There are a number of aspects of MQ usage that don't fit tidily into
821 sections of their own, but that are good to know. Here they are, in
822 one place.
824 \begin{itemize}
825 \item Normally, when you \hgxcmd{mq}{qpop} a patch and \hgxcmd{mq}{qpush} it
826 again, the changeset that represents the patch after the pop/push
827 will have a \emph{different identity} than the changeset that
828 represented the hash beforehand. See
829 section~\ref{sec:mqref:cmd:qpush} for information as to why this is.
830 \item It's not a good idea to \hgcmd{merge} changes from another
831 branch with a patch changeset, at least if you want to maintain the
832 ``patchiness'' of that changeset and changesets below it on the
833 patch stack. If you try to do this, it will appear to succeed, but
834 MQ will become confused.
835 \end{itemize}
837 \section{Managing patches in a repository}
838 \label{sec:mq:repo}
840 Because MQ's \sdirname{.hg/patches} directory resides outside a
841 Mercurial repository's working directory, the ``underlying'' Mercurial
842 repository knows nothing about the management or presence of patches.
844 This presents the interesting possibility of managing the contents of
845 the patch directory as a Mercurial repository in its own right. This
846 can be a useful way to work. For example, you can work on a patch for
847 a while, \hgxcmd{mq}{qrefresh} it, then \hgcmd{commit} the current state of
848 the patch. This lets you ``roll back'' to that version of the patch
849 later on.
851 You can then share different versions of the same patch stack among
852 multiple underlying repositories. I use this when I am developing a
853 Linux kernel feature. I have a pristine copy of my kernel sources for
854 each of several CPU architectures, and a cloned repository under each
855 that contains the patches I am working on. When I want to test a
856 change on a different architecture, I push my current patches to the
857 patch repository associated with that kernel tree, pop and push all of
858 my patches, and build and test that kernel.
860 Managing patches in a repository makes it possible for multiple
861 developers to work on the same patch series without colliding with
862 each other, all on top of an underlying source base that they may or
863 may not control.
865 \subsection{MQ support for patch repositories}
867 MQ helps you to work with the \sdirname{.hg/patches} directory as a
868 repository; when you prepare a repository for working with patches
869 using \hgxcmd{mq}{qinit}, you can pass the \hgxopt{mq}{qinit}{-c} option to
870 create the \sdirname{.hg/patches} directory as a Mercurial repository.
872 \begin{note}
873 If you forget to use the \hgxopt{mq}{qinit}{-c} option, you can simply go
874 into the \sdirname{.hg/patches} directory at any time and run
875 \hgcmd{init}. Don't forget to add an entry for the
876 \sfilename{status} file to the \sfilename{.hgignore} file, though
878 (\hgcmdargs{qinit}{\hgxopt{mq}{qinit}{-c}} does this for you
879 automatically); you \emph{really} don't want to manage the
880 \sfilename{status} file.
881 \end{note}
883 As a convenience, if MQ notices that the \dirname{.hg/patches}
884 directory is a repository, it will automatically \hgcmd{add} every
885 patch that you create and import.
887 MQ provides a shortcut command, \hgxcmd{mq}{qcommit}, that runs
888 \hgcmd{commit} in the \sdirname{.hg/patches} directory. This saves
889 some bothersome typing.
891 Finally, as a convenience to manage the patch directory, you can
892 define the alias \command{mq} on Unix systems. For example, on Linux
893 systems using the \command{bash} shell, you can include the following
894 snippet in your \tildefile{.bashrc}.
896 \begin{codesample2}
897 alias mq=`hg -R \$(hg root)/.hg/patches'
898 \end{codesample2}
900 You can then issue commands of the form \cmdargs{mq}{pull} from
901 the main repository.
903 \subsection{A few things to watch out for}
905 MQ's support for working with a repository full of patches is limited
906 in a few small respects.
908 MQ cannot automatically detect changes that you make to the patch
909 directory. If you \hgcmd{pull}, manually edit, or \hgcmd{update}
910 changes to patches or the \sfilename{series} file, you will have to
911 \hgcmdargs{qpop}{\hgxopt{mq}{qpop}{-a}} and then
912 \hgcmdargs{qpush}{\hgxopt{mq}{qpush}{-a}} in the underlying repository to
913 see those changes show up there. If you forget to do this, you can
914 confuse MQ's idea of which patches are applied.
916 \section{Third party tools for working with patches}
917 \label{sec:mq:tools}
919 Once you've been working with patches for a while, you'll find
920 yourself hungry for tools that will help you to understand and
921 manipulate the patches you're dealing with.
923 The \command{diffstat} command~\cite{web:diffstat} generates a
924 histogram of the modifications made to each file in a patch. It
925 provides a good way to ``get a sense of'' a patch---which files it
926 affects, and how much change it introduces to each file and as a
927 whole. (I find that it's a good idea to use \command{diffstat}'s
928 \cmdopt{diffstat}{-p} option as a matter of course, as otherwise it
929 will try to do clever things with prefixes of file names that
930 inevitably confuse at least me.)
932 \begin{figure}[ht]
933 \interaction{mq.tools.tools}
934 \caption{The \command{diffstat}, \command{filterdiff}, and \command{lsdiff} commands}
935 \label{ex:mq:tools}
936 \end{figure}
938 The \package{patchutils} package~\cite{web:patchutils} is invaluable.
939 It provides a set of small utilities that follow the ``Unix
940 philosophy;'' each does one useful thing with a patch. The
941 \package{patchutils} command I use most is \command{filterdiff}, which
942 extracts subsets from a patch file. For example, given a patch that
943 modifies hundreds of files across dozens of directories, a single
944 invocation of \command{filterdiff} can generate a smaller patch that
945 only touches files whose names match a particular glob pattern. See
946 section~\ref{mq-collab:tips:interdiff} for another example.
948 \section{Good ways to work with patches}
950 Whether you are working on a patch series to submit to a free software
951 or open source project, or a series that you intend to treat as a
952 sequence of regular changesets when you're done, you can use some
953 simple techniques to keep your work well organised.
955 Give your patches descriptive names. A good name for a patch might be
956 \filename{rework-device-alloc.patch}, because it will immediately give
957 you a hint what the purpose of the patch is. Long names shouldn't be
958 a problem; you won't be typing the names often, but you \emph{will} be
959 running commands like \hgxcmd{mq}{qapplied} and \hgxcmd{mq}{qtop} over and over.
960 Good naming becomes especially important when you have a number of
961 patches to work with, or if you are juggling a number of different
962 tasks and your patches only get a fraction of your attention.
964 Be aware of what patch you're working on. Use the \hgxcmd{mq}{qtop}
965 command and skim over the text of your patches frequently---for
966 example, using \hgcmdargs{tip}{\hgopt{tip}{-p}})---to be sure of where
967 you stand. I have several times worked on and \hgxcmd{mq}{qrefresh}ed a
968 patch other than the one I intended, and it's often tricky to migrate
969 changes into the right patch after making them in the wrong one.
971 For this reason, it is very much worth investing a little time to
972 learn how to use some of the third-party tools I described in
973 section~\ref{sec:mq:tools}, particularly \command{diffstat} and
974 \command{filterdiff}. The former will give you a quick idea of what
975 changes your patch is making, while the latter makes it easy to splice
976 hunks selectively out of one patch and into another.
978 \section{MQ cookbook}
980 \subsection{Manage ``trivial'' patches}
982 Because the overhead of dropping files into a new Mercurial repository
983 is so low, it makes a lot of sense to manage patches this way even if
984 you simply want to make a few changes to a source tarball that you
985 downloaded.
987 Begin by downloading and unpacking the source tarball,
988 and turning it into a Mercurial repository.
989 \interaction{mq.tarball.download}
991 Continue by creating a patch stack and making your changes.
992 \interaction{mq.tarball.qinit}
994 Let's say a few weeks or months pass, and your package author releases
995 a new version. First, bring their changes into the repository.
996 \interaction{mq.tarball.newsource}
997 The pipeline starting with \hgcmd{locate} above deletes all files in
998 the working directory, so that \hgcmd{commit}'s
999 \hgopt{commit}{--addremove} option can actually tell which files have
1000 really been removed in the newer version of the source.
1002 Finally, you can apply your patches on top of the new tree.
1003 \interaction{mq.tarball.repush}
1005 \subsection{Combining entire patches}
1006 \label{sec:mq:combine}
1008 MQ provides a command, \hgxcmd{mq}{qfold} that lets you combine entire
1009 patches. This ``folds'' the patches you name, in the order you name
1010 them, into the topmost applied patch, and concatenates their
1011 descriptions onto the end of its description. The patches that you
1012 fold must be unapplied before you fold them.
1014 The order in which you fold patches matters. If your topmost applied
1015 patch is \texttt{foo}, and you \hgxcmd{mq}{qfold} \texttt{bar} and
1016 \texttt{quux} into it, you will end up with a patch that has the same
1017 effect as if you applied first \texttt{foo}, then \texttt{bar},
1018 followed by \texttt{quux}.
1020 \subsection{Merging part of one patch into another}
1022 Merging \emph{part} of one patch into another is more difficult than
1023 combining entire patches.
1025 If you want to move changes to entire files, you can use
1026 \command{filterdiff}'s \cmdopt{filterdiff}{-i} and
1027 \cmdopt{filterdiff}{-x} options to choose the modifications to snip
1028 out of one patch, concatenating its output onto the end of the patch
1029 you want to merge into. You usually won't need to modify the patch
1030 you've merged the changes from. Instead, MQ will report some rejected
1031 hunks when you \hgxcmd{mq}{qpush} it (from the hunks you moved into the
1032 other patch), and you can simply \hgxcmd{mq}{qrefresh} the patch to drop
1033 the duplicate hunks.
1035 If you have a patch that has multiple hunks modifying a file, and you
1036 only want to move a few of those hunks, the job becomes more messy,
1037 but you can still partly automate it. Use \cmdargs{lsdiff}{-nvv} to
1038 print some metadata about the patch.
1039 \interaction{mq.tools.lsdiff}
1041 This command prints three different kinds of number:
1042 \begin{itemize}
1043 \item (in the first column) a \emph{file number} to identify each file
1044 modified in the patch;
1045 \item (on the next line, indented) the line number within a modified
1046 file where a hunk starts; and
1047 \item (on the same line) a \emph{hunk number} to identify that hunk.
1048 \end{itemize}
1050 You'll have to use some visual inspection, and reading of the patch,
1051 to identify the file and hunk numbers you'll want, but you can then
1052 pass them to to \command{filterdiff}'s \cmdopt{filterdiff}{--files}
1053 and \cmdopt{filterdiff}{--hunks} options, to select exactly the file
1054 and hunk you want to extract.
1056 Once you have this hunk, you can concatenate it onto the end of your
1057 destination patch and continue with the remainder of
1058 section~\ref{sec:mq:combine}.
1060 \section{Differences between quilt and MQ}
1062 If you are already familiar with quilt, MQ provides a similar command
1063 set. There are a few differences in the way that it works.
1065 You will already have noticed that most quilt commands have MQ
1066 counterparts that simply begin with a ``\texttt{q}''. The exceptions
1067 are quilt's \texttt{add} and \texttt{remove} commands, the
1068 counterparts for which are the normal Mercurial \hgcmd{add} and
1069 \hgcmd{remove} commands. There is no MQ equivalent of the quilt
1070 \texttt{edit} command.
1072 %%% Local Variables:
1073 %%% mode: latex
1074 %%% TeX-master: "00book"
1075 %%% End: