hgbook

view es/hook.tex @ 451:f4904a9b4fdb

Started translating hgext
author Igor TAmara <igor@tamarapatino.org>
date Sat Dec 13 23:55:07 2008 -0500 (2008-12-13)
parents 4e0684e824e1
children 5a0401ba9faa
line source
1 \chapter{Manejo de eventos en repositorios mediante ganchos}
2 \label{chap:hook}
4 Mercurial ofrece un poderoso mecanismo para permitirle a usted
5 automatizar la ejecución de acciones en respuesta a eventos que
6 ocurran en un repositorio. En algunos casos, usted puede controlar
7 incluso la respuesta de Mercurial a dichos eventos.
9 Mercurial usa el término \emph{gancho} para identificar estas
10 acciones. Los ganchos son conocidos como ``disparadores'' en algunos
11 sistemas de control de revisiones, pero los dos nombres se refieren al
12 mismo concepto.
14 \section{Vistazo general de ganchos en Mercurial}
16 A continuación se encuentra una breve lista de los ganchos que
17 Mercurial soporta. Volveremos a cada uno de estos ganchos con más
18 detalle después, en la sección~\ref{sec:hook:ref}.
20 \begin{itemize}
21 \item[\small\hook{changegroup}] Es ejecutado luego de que un grupo de
22 conjuntos de cambios ha sido traído al repositorio desde algún
23 otro sitio.
24 \item[\small\hook{commit}] Es ejecutado después de la creación de
25 un conjunto de cambios en el repositorio local.
26 \item[\small\hook{incoming}] Es ejecutado una vez por cada conjunto de
27 cambios traído al repositorio desde otra ubicación. Note la
28 diferencia respecto al gancho \hook{changegroup}, que es ejecutado
29 una vez por cada \emph{grupo} de conjuntos de cambios que se
30 traiga.
31 \item[\small\hook{outgoing}] Es ejecutado luego de que un grupo de
32 conjuntos de cambios ha sido transmitido desde el repositorio.
33 \item[\small\hook{prechangegroup}] Es ejecutado antes de iniciar la
34 recepción de un grupo de conjuntos de cambios en el repositorio.
35 \item[\small\hook{precommit}] De control. Es ejecutado antes de
36 iniciar una consignación.
37 \item[\small\hook{preoutgoing}] De control. Es ejecutado antes de
38 iniciar la transmisión de un grupo de conjuntos de cambios desde
39 el repositorio.
40 \item[\small\hook{pretag}] De control. Es ejecutado antes de crear una
41 etiqueta.
42 \item[\small\hook{pretxnchangegroup}] De control. Es ejecutado después
43 de haber recibido un grupo de conjuntos de cambios en el
44 repositorio local, pero antes de que la transacción se complete y
45 los cambios sean permanentes dentro del repositorio.
46 \item[\small\hook{pretxncommit}] De control. Es ejecutado luego de la
47 creación de un conjunto de cambios en el repositorio local, pero
48 antes de que la transacción que hace permanente el cambio sea
49 completada.
50 \item[\small\hook{preupdate}] De control. Es ejecutado antes de
51 iniciar una actualización o fusión en el directorio de trabajo.
52 \item[\small\hook{tag}] Es ejecutado después de la creación de una
53 etiqueta.
54 \item[\small\hook{update}] Es ejecutado después de que termina una
55 actualización o una fusión.
56 \end{itemize}
57 Cada uno de los ganchos cuya descripción empieza con la frase
58 ``de control'' tiene la facultad de determinar si una actividad puede
59 continuar. Si el gancho se ejecuta con éxito, la actividad puede
60 continuar; si falla, o bien la actividad no es permitida, o se
61 deshacen los cambios que se puedan haber llevado a cabo, dependiendo
62 del gancho involucrado.
64 \section{Ganchos y seguridad}
66 \subsection{Los ganchos se ejecutan con sus privilegios de usuario}
68 Cuando usted ejecuta un comando de Mercurial en un repositorio, y el
69 comando causa la ejecución de un gancho, dicho gancho se ejecuta en
70 \emph{su} sistema, en \emph{su} cuenta de usuario, con \emph{sus}
71 privilegios. Ya que los ganchos son elementos arbitrarios de código
72 ejecutable, usted debería tratarlos con un nivel adecuado de
73 desconfianza. No instale un gancho a menos en que confíe en quien lo
74 creó y en lo que el gancho hace.
76 En algunos casos, usted puede estar expuesto a ganchos que usted no
77 %TODO acá introduzco algo de texto por mi cuenta, por claridad
78 instaló. Si usted usa Mercurial en un sistema extraño, tenga en cuenta
79 que Mercurial ejecutará los ganchos definidos en el fichero \hgrc.
81 Si está trabajando con un repositorio propiedad de otro usuario,
82 Mercurial podrá ejecutar los ganchos definidos en el repositorio de
83 dicho usuario, pero los ejecutará como ``usted''. Por ejemplo, si
84 usted jala (\hgcmd{pull}) desde ese repositorio, y el
85 \sfilename{.hg/hgrc} define un gancho saliente (\hook{outgoing}),
86 dicho gancho se ejecuta bajo su cuenta de usuario, aun cuando usted no
87 es el propietario del repositorio.
89 \begin{note}
90 Esto sólo aplica si usted está jalando desde un repositorio en un
91 sistema de ficheros local o de red. Si está jalando a través de http
92 o ssh, cualquier gancho saliente (\hook{outgoing}) se ejecutará bajo
93 la cuenta que está ejecutando el proceso servidor, en el servidor.
94 \end{note}
96 XXX Para ver qué ganchos han sido definidos en un repositorio, use el
97 comando \hgcmdargs{config}{hooks}. Si usted está trabajando en un
98 repositorio, pero comunicándose con otro que no le pertenece
99 (por ejemplo, usando \hgcmd{pull} o \hgcmd{incoming}), recuerde que
100 los ganchos que debe considerar son los del otro repositorio, no los
101 del suyo.
103 \subsection{Los ganchos no se propagan}
105 En Mercurial, no se hace control de revisiones de los ganchos, y no se
106 propagan cuando usted clona, o jala de, un repositorio. El motivo para
107 esto es simple: un gancho es código ejecutable arbitrario. Se ejecuta
108 bajo su identidad, con su nivel de privilegios, en su máquina.
110 Sería extremadamente descuidado de parte de cualquier sistema
111 distribuido de control de revisiones el implementar control de
112 revisiones para ganchos, ya que esto ofrecería maneras fácilmente
113 %TODO subvertir
114 aprovechables de subvertir las cuentas de los usuarios del sistema de
115 control de revisiones.
117 Ya que Mercurial no propaga los ganchos, si usted está colaborando con
118 otras personas en un proyecto común, no debería asumir que ellos están
119 usando los mismos ganchos para Mercurial que usted usa, o que los de
120 ellos están configurado correctamente. Usted debería documentar los
121 ganchos que usted espera que la gente use.
123 En una intranet corporativa, esto es algo más fácil de manejar, ya que
124 usted puede, por ejemplo, proveer una instalación ``estándar'' de
125 Mercurial en un sistema de ficheros NFS, y usar un fichero \hgrc\
126 global para definir los ganchos que verán todos los usuarios. Sin
127 embargo, este enfoque tiene sus límites; vea más abajo.
129 \subsection{Es posible hacer caso omiso de los ganchos}
131 Mercurial le permite hacer caso omiso de la deficinión de un gancho,
132 a través de la redefinición del mismo. Usted puede deshabilitar el
133 gancho fijando su valor como una cadena vacía, o cambiar su
134 comportamiento como desee.
136 Si usted instala un fichero \hgrc\ a nivel de sistema o sitio completo
137 que define algunos ganchos, debe entender que sus usuarios pueden
138 deshabilitar o hacer caso omiso de los mismos.
140 \subsection{Asegurarse de que ganchos críticos sean ejecutados}
142 Algunas veces usted puede querer hacer respetar una política, y no
143 permitir que los demás sean capaces de evitarla. Por ejemplo, usted
144 puede tener como requerimiento que cada conjunto de cambios debe pasar
145 un riguroso conjunto de pruebas. Definir este requerimientos a través
146 de un gancho en un fichero \hgrc\ global no servirá con usuarios
147 remotos en computadoras portátiles, y por supuesto que los usuarios
148 locales pueden evitar esto a voluntad haciendo caso omiso del gancho.
150 En vez de eso, usted puede definir las políticas para usar Mercurial
151 de tal forma que se espere que los usuarios propaguen los cambios a
152 través de un servidor ``canónico'' bien conocido que usted ha
153 asegurado y configurado apropiadamente.
155 Una manera de hacer esto es a través de una combinación de ingeniería
156 socual y tecnología. Cree una cuenta de acceso restringido; los
157 usuarios pueden empujar cambios a través de la red a los repositorios
158 administrados por esta cuenta, pero no podrán ingresar a dicha cuenta
159 para ejecutar órdenes en el intérprete de comandos. En este escenario,
160 un usuario puede enviar un conjunto de cambios que contenga la
161 porquería que él desee.
163 Cuando alguien empuja un conjunto de cambios al servidor del que todos
164 jalan, el servidor probará el conjunto de cambios antes de aceptarlo
165 como permanente, y lo rechazará si no logra pasar el conjunto de
166 pruebas. Si la gente sólo jala cambios desde este servidor de filtro,
167 servirá para asegurarse de que todos los cambios que la gente jala han
168 sido examinados automáticamente
170 \section{Precauciones con ganchos \texttt{pretxn} en un repositorio de
171 acceso compartido}
173 Si usted desea usar ganchos para llevar a cabo automáticamente algún
174 trabajo en un repositorio al que varias personas tienen acceso
175 compartido, debe tener cuidado con la forma de hacerlo.
177 Mercurial sólo bloquea un repositorio cuando está escribiendo al
178 mismo, y sólo las partes de Mercurial que escriben al repositorio le
179 prestan atención a los bloqueos. Los bloqueos de escritura son
180 necesarios para evitar que múltiples escritores simultáneos
181 interfieran entre sí, corrompiendo el repositorio.
183 Ya que Mercurial tiene cuidado con el orden en que lee y escribe
184 datos, no necesita adquirir un bloqueo cuando desea leer datos del
185 repositorio. Las partes de Mercurial que leen del repositorio nunca le
186 prestan atención a los bloqueos. Este esquema de lectura libre de
187 bloqueos incremententa en gran medida el desempeño y la concurrencia.
189 Sin embargo, para tener un gran desempeño es necesario hacer
190 sacrificios, uno de los cuales tiene el potencial de causarle
191 problemas a menos de que usted esté consciente de él. Describirlo
192 requiere algo de detalle respecto a cómo Mercurial añade conjuntos de
193 cambios al repositorio y cómo lee esos cambios de vuelta.
195 Cuando Mercurial \emph{escribe} metadatos, los escribe directamente en
196 el fichero de destino. Primero escribe los datos del fichero, luego
197 los datos del manifiesto (que contienen punteros a los nuevos datos
198 del fichero), luego datos de la bitácora de cambios (que contienen
199 punteros a los nuevos datos del manifiesto). Antes de la primera
200 escritura a cada fichero, se guarda un registro de dónde estaba el
201 final de fichero en su registro de transacciones. Si la transacción
202 debe ser deshecha, Mercurial simplemente trunca cada fichero de vuelta
203 al tamaño que tenía antes de que empezara la transacción.
205 Cuando Mercurial \emph{lee} metadatos, lee la bitácora de cambios
206 primero, y luego todo lo demás. Como un lector sólo accederá a las
207 partes del manifiesto o de los metadatos de fichero que él puede ver
208 en la bitácora de cambios, nunca puede ver datos parcialmente
209 escritos.
211 Algunos ganchos de control (\hook{pretxncommit} y
212 \hook{pretxnchangegroup}) se ejecutan cuando una transacción está casi
213 completa. Todos los metadatos han sido escritos, pero Mercurial aún
214 puede deshacer la transacción y hacer que los datos recién escritos
215 desaparezcan.
217 Si alguno de estos ganchos permanece en ejecución por mucho tiempo,
218 abre una ventana de tiempo en la que un lector puede ver los metadatos
219 de conjuntos de cambios que aún no son permanentes y que no debería
220 considerarse que estén ``realmante ahí''. Entre más tiempo tome la
221 ejecución del gancho, más tiempo estará abierta esta ventana.
223 \subsection{Ilustración del problema}
225 En principio, un buen uso del gancho \hook{pretxnchangegroup} sería
226 ensamblar y probar automáticamente todos los cambios entrantes antes
227 de que sean aceptados en un repositorio central. Esto le permitiría a
228 usted garantizar que nadie pueda empujar cambios que ``rompan el
229 ensamblaje''. Pero si un cliente puede jalar cambios mientras están
230 siendo probados, la utilidad de esta prueba es nula; alguien confiado
231 puede jalar cambios sin probar, lo que potencialmente podría romper su
232 proceso de ensamblaje.
234 La respuesta técnica más segura frente a este retos es montar dicho
235 repositorio ``guardián'' como \emph{unidireccional}. Permita que
236 reciba cambios desde el exterior, pero no permita que nadie jale
237 cambios de él (use el gancho \hook{preoutgoing} para bloquear esto).
238 Configure un gancho \hook{changegroup} para que si el ensamblaje o
239 prueba tiene éxito, el gancho empuje los nuevos cambios a otro
240 repositorio del que la gente \emph{pueda} jalar.
242 En la práctica, montar un cuello de botella centralizado como éste a
243 menudo no es una buena idea, y la visibilidad de las transacciones no
244 tiene nada que ver con el problema. A medida que el tamaño de un
245 proyecto---y el tiempo que toma ensamblarlo y probarlo---crece, usted
246 se acerca rápidamente a un límite con este enfoque ``pruebe antes de
247 comprar'', en el que tiene más conjuntos de cambios a probar que
248 tiempo para ocuparse de ellos. El resultado inevitable es frustración
249 para todos los que estén involucrados.
251 Una aproximación que permite manejar mejor el crecimiento es hacer que
252 la gente ensamble y pruebe antes de empujar, y ejecutar el ensamble y
253 pruebas automáticas centralmente \emph{después} de empujar, para
254 asegurarse de que todo esté bien. La ventaja de este enfoque es que no
255 impone un límite a la rata en la que un repositorio puede aceptar
256 cambios.
258 \section{Tutorial corto de uso de ganchos}
259 \label{sec:hook:simple}
261 Escribir un gancho para Mercurial es fácil. Empecemos con un gancho
262 que se ejecute cuando usted termine un \hgcmd{commit}, y simplemente
263 muestre el hash del conjunto de cambios que usted acaba de crear. El
264 gancho se llamará \hook{commit}.
266 \begin{figure}[ht]
267 \interaction{hook.simple.init}
268 \caption{Un gancho simple que se ejecuta al hacer la consignación de
269 un conjunto de cambios}
270 \label{ex:hook:init}
271 \end{figure}
273 Todos los ganchos siguen el patrón del ejemplo~\ref{ex:hook:init}.
274 Usted puede añadir una entrada a la sección \rcsection{hooks} de su
275 fichero \hgrc. A la izquierda está el nombre del evento respecto al
276 cual dispararse; a la derecha está la acción a llevar a cabo. Como
277 puede ver, es posible ejecutar cualquier orden de la línea de comandos
278 en un gancho. Mercurial le pasa información extra al gancho usando
279 variables de entorno (busque \envar{HG\_NODE} en el ejemplo).
281 \subsection{Llevar a cabo varias acciones por evento}
283 A menudo, usted querrá definir más de un gancho para un tipo de evento
284 particular, como se muestra en el ejemplo~\ref{ex:hook:ext}.
285 Mercurial le permite hacer esto añadiendo una \emph{extensión} al
286 final del nombre de un gancho. Usted extiende el nombre del gancho
287 %TODO Yuk, no me gusta ese "parada completa"
288 poniendo el nombre del gancho, seguido por una parada completa (el
289 caracter ``\texttt{.}''), seguido de algo más de texto de su elección.
290 Por ejemplo, Mercurial ejecutará tanto \texttt{commit.foo} como
291 \texttt{commit.bar} cuando ocurra el evento \texttt{commit}.
293 \begin{figure}[ht]
294 \interaction{hook.simple.ext}
295 \caption{Definición de un segundo gancho \hook{commit}}
296 \label{ex:hook:ext}
297 \end{figure}
299 Para dar un orden bien definido de ejecución cuando hay múltiples
300 ganchos definidos para un evento, Mercurial ordena los ganchos de
301 acuerdo a su extensión, y los ejecuta en dicho orden. En el ejemplo de
302 arribam \texttt{commit.bar} se ejecutará antes que
303 \texttt{commit.foo}, y \texttt{commit} se ejecutará antes de ambos.
305 Es una buena idea usar una extensión descriptiva cuando usted define
306 un gancho. Esto le ayudará a recordar para qué se usa el gancho. Si el
307 gancho falla, usted recibirá un mensaje de error que contiene el
308 nombre y la extensión del gancho, así que usar una extensión
309 descriptiva le dará una pista inmediata de porqué el gancho falló (vea
310 un ejemplo en la sección~\ref{sec:hook:perm}).
312 \subsection{Controlar cuándo puede llevarse a cabo una actividad}
313 \label{sec:hook:perm}
315 En los ejemplos anteriores, usamos el gancho \hook{commit}, que es
316 ejecutado después de que se ha completado una consignación. Este es
317 uno de los varios ganchos que Mercurial ejecuta luego de que una
318 actividad termina. Tales ganchos no tienen forma de influenciar la
319 actividad como tal.
321 Mercurial define un número de eventos que ocurren antes de que una
322 actividad empiece; o luego de que empiece, pero antes de que termine.
323 Los ganchos que se disparan con estos eventos tienen la capacidad
324 adicional de elegir si la actividad puede continuar, o si su ejecución
325 es abortada.
327 El gancho \hook{pretxncommit} se ejecuta justo antes de que una
328 consignación se ejecute. En otras palabras, los metadatos que
329 representan el conjunto de cambios han sido escritos al disco, pero no
330 se ha terminado la transacción. El gancho \hook{pretxncommit} tiene la
331 capacidad de decidir si una transacción se completa, o debe
332 deshacerse.
334 Si el gancho \hook{pretxncommit} termina con un código de salida de
335 cero, se permite que la transacción se complete; la consignación
336 termina; y el gancho \hook{commit} es ejecutado. Si el gancho
337 \hook{pretxncommit} termina con un código de salida diferente de cero,
338 la transacción es revertida; los metadatos representando el conjunto
339 de cambios son borrados; y el gancho \hook{commit} no es ejecutado.
341 \begin{figure}[ht]
342 \interaction{hook.simple.pretxncommit}
343 \caption{Uso del gancho \hook{pretxncommit} hook to control commits}
344 \label{ex:hook:pretxncommit}
345 \end{figure}
347 The hook in example~\ref{ex:hook:pretxncommit} checks that a commit
348 comment contains a bug ID. If it does, the commit can complete. If
349 not, the commit is rolled back.
351 \section{Writing your own hooks}
353 When you are writing a hook, you might find it useful to run Mercurial
354 either with the \hggopt{-v} option, or the \rcitem{ui}{verbose} config
355 item set to ``true''. When you do so, Mercurial will print a message
356 before it calls each hook.
358 \subsection{Choosing how your hook should run}
359 \label{sec:hook:lang}
361 You can write a hook either as a normal program---typically a shell
362 script---or as a Python function that is executed within the Mercurial
363 process.
365 Writing a hook as an external program has the advantage that it
366 requires no knowledge of Mercurial's internals. You can call normal
367 Mercurial commands to get any added information you need. The
368 trade-off is that external hooks are slower than in-process hooks.
370 An in-process Python hook has complete access to the Mercurial API,
371 and does not ``shell out'' to another process, so it is inherently
372 faster than an external hook. It is also easier to obtain much of the
373 information that a hook requires by using the Mercurial API than by
374 running Mercurial commands.
376 If you are comfortable with Python, or require high performance,
377 writing your hooks in Python may be a good choice. However, when you
378 have a straightforward hook to write and you don't need to care about
379 performance (probably the majority of hooks), a shell script is
380 perfectly fine.
382 \subsection{Hook parameters}
383 \label{sec:hook:param}
385 Mercurial calls each hook with a set of well-defined parameters. In
386 Python, a parameter is passed as a keyword argument to your hook
387 function. For an external program, a parameter is passed as an
388 environment variable.
390 Whether your hook is written in Python or as a shell script, the
391 hook-specific parameter names and values will be the same. A boolean
392 parameter will be represented as a boolean value in Python, but as the
393 number 1 (for ``true'') or 0 (for ``false'') as an environment
394 variable for an external hook. If a hook parameter is named
395 \texttt{foo}, the keyword argument for a Python hook will also be
396 named \texttt{foo}, while the environment variable for an external
397 hook will be named \texttt{HG\_FOO}.
399 \subsection{Hook return values and activity control}
401 A hook that executes successfully must exit with a status of zero if
402 external, or return boolean ``false'' if in-process. Failure is
403 indicated with a non-zero exit status from an external hook, or an
404 in-process hook returning boolean ``true''. If an in-process hook
405 raises an exception, the hook is considered to have failed.
407 For a hook that controls whether an activity can proceed, zero/false
408 means ``allow'', while non-zero/true/exception means ``deny''.
410 \subsection{Writing an external hook}
412 When you define an external hook in your \hgrc\ and the hook is run,
413 its value is passed to your shell, which interprets it. This means
414 that you can use normal shell constructs in the body of the hook.
416 An executable hook is always run with its current directory set to a
417 repository's root directory.
419 Each hook parameter is passed in as an environment variable; the name
420 is upper-cased, and prefixed with the string ``\texttt{HG\_}''.
422 With the exception of hook parameters, Mercurial does not set or
423 modify any environment variables when running a hook. This is useful
424 to remember if you are writing a site-wide hook that may be run by a
425 number of different users with differing environment variables set.
426 In multi-user situations, you should not rely on environment variables
427 being set to the values you have in your environment when testing the
428 hook.
430 \subsection{Telling Mercurial to use an in-process hook}
432 The \hgrc\ syntax for defining an in-process hook is slightly
433 different than for an executable hook. The value of the hook must
434 start with the text ``\texttt{python:}'', and continue with the
435 fully-qualified name of a callable object to use as the hook's value.
437 The module in which a hook lives is automatically imported when a hook
438 is run. So long as you have the module name and \envar{PYTHONPATH}
439 right, it should ``just work''.
441 The following \hgrc\ example snippet illustrates the syntax and
442 meaning of the notions we just described.
443 \begin{codesample2}
444 [hooks]
445 commit.example = python:mymodule.submodule.myhook
446 \end{codesample2}
447 When Mercurial runs the \texttt{commit.example} hook, it imports
448 \texttt{mymodule.submodule}, looks for the callable object named
449 \texttt{myhook}, and calls it.
451 \subsection{Writing an in-process hook}
453 The simplest in-process hook does nothing, but illustrates the basic
454 shape of the hook API:
455 \begin{codesample2}
456 def myhook(ui, repo, **kwargs):
457 pass
458 \end{codesample2}
459 The first argument to a Python hook is always a
460 \pymodclass{mercurial.ui}{ui} object. The second is a repository object;
461 at the moment, it is always an instance of
462 \pymodclass{mercurial.localrepo}{localrepository}. Following these two
463 arguments are other keyword arguments. Which ones are passed in
464 depends on the hook being called, but a hook can ignore arguments it
465 doesn't care about by dropping them into a keyword argument dict, as
466 with \texttt{**kwargs} above.
468 \section{Some hook examples}
470 \subsection{Writing meaningful commit messages}
472 It's hard to imagine a useful commit message being very short. The
473 simple \hook{pretxncommit} hook of figure~\ref{ex:hook:msglen.go}
474 will prevent you from committing a changeset with a message that is
475 less than ten bytes long.
477 \begin{figure}[ht]
478 \interaction{hook.msglen.go}
479 \caption{A hook that forbids overly short commit messages}
480 \label{ex:hook:msglen.go}
481 \end{figure}
483 \subsection{Checking for trailing whitespace}
485 An interesting use of a commit-related hook is to help you to write
486 cleaner code. A simple example of ``cleaner code'' is the dictum that
487 a change should not add any new lines of text that contain ``trailing
488 whitespace''. Trailing whitespace is a series of space and tab
489 characters at the end of a line of text. In most cases, trailing
490 whitespace is unnecessary, invisible noise, but it is occasionally
491 problematic, and people often prefer to get rid of it.
493 You can use either the \hook{precommit} or \hook{pretxncommit} hook to
494 tell whether you have a trailing whitespace problem. If you use the
495 \hook{precommit} hook, the hook will not know which files you are
496 committing, so it will have to check every modified file in the
497 repository for trailing white space. If you want to commit a change
498 to just the file \filename{foo}, but the file \filename{bar} contains
499 trailing whitespace, doing a check in the \hook{precommit} hook will
500 prevent you from committing \filename{foo} due to the problem with
501 \filename{bar}. This doesn't seem right.
503 Should you choose the \hook{pretxncommit} hook, the check won't occur
504 until just before the transaction for the commit completes. This will
505 allow you to check for problems only the exact files that are being
506 committed. However, if you entered the commit message interactively
507 and the hook fails, the transaction will roll back; you'll have to
508 re-enter the commit message after you fix the trailing whitespace and
509 run \hgcmd{commit} again.
511 \begin{figure}[ht]
512 \interaction{hook.ws.simple}
513 \caption{A simple hook that checks for trailing whitespace}
514 \label{ex:hook:ws.simple}
515 \end{figure}
517 Figure~\ref{ex:hook:ws.simple} introduces a simple \hook{pretxncommit}
518 hook that checks for trailing whitespace. This hook is short, but not
519 very helpful. It exits with an error status if a change adds a line
520 with trailing whitespace to any file, but does not print any
521 information that might help us to identify the offending file or
522 line. It also has the nice property of not paying attention to
523 unmodified lines; only lines that introduce new trailing whitespace
524 cause problems.
526 \begin{figure}[ht]
527 \interaction{hook.ws.better}
528 \caption{A better trailing whitespace hook}
529 \label{ex:hook:ws.better}
530 \end{figure}
532 The example of figure~\ref{ex:hook:ws.better} is much more complex,
533 but also more useful. It parses a unified diff to see if any lines
534 add trailing whitespace, and prints the name of the file and the line
535 number of each such occurrence. Even better, if the change adds
536 trailing whitespace, this hook saves the commit comment and prints the
537 name of the save file before exiting and telling Mercurial to roll the
538 transaction back, so you can use
539 \hgcmdargs{commit}{\hgopt{commit}{-l}~\emph{filename}} to reuse the
540 saved commit message once you've corrected the problem.
542 As a final aside, note in figure~\ref{ex:hook:ws.better} the use of
543 \command{perl}'s in-place editing feature to get rid of trailing
544 whitespace from a file. This is concise and useful enough that I will
545 reproduce it here.
546 \begin{codesample2}
547 perl -pi -e 's,\\s+\$,,' filename
548 \end{codesample2}
550 \section{Bundled hooks}
552 Mercurial ships with several bundled hooks. You can find them in the
553 \dirname{hgext} directory of a Mercurial source tree. If you are
554 using a Mercurial binary package, the hooks will be located in the
555 \dirname{hgext} directory of wherever your package installer put
556 Mercurial.
558 \subsection{\hgext{acl}---access control for parts of a repository}
560 The \hgext{acl} extension lets you control which remote users are
561 allowed to push changesets to a networked server. You can protect any
562 portion of a repository (including the entire repo), so that a
563 specific remote user can push changes that do not affect the protected
564 portion.
566 This extension implements access control based on the identity of the
567 user performing a push, \emph{not} on who committed the changesets
568 they're pushing. It makes sense to use this hook only if you have a
569 locked-down server environment that authenticates remote users, and
570 you want to be sure that only specific users are allowed to push
571 changes to that server.
573 \subsubsection{Configuring the \hook{acl} hook}
575 In order to manage incoming changesets, the \hgext{acl} hook must be
576 used as a \hook{pretxnchangegroup} hook. This lets it see which files
577 are modified by each incoming changeset, and roll back a group of
578 changesets if they modify ``forbidden'' files. Example:
579 \begin{codesample2}
580 [hooks]
581 pretxnchangegroup.acl = python:hgext.acl.hook
582 \end{codesample2}
584 The \hgext{acl} extension is configured using three sections.
586 The \rcsection{acl} section has only one entry, \rcitem{acl}{sources},
587 which lists the sources of incoming changesets that the hook should
588 pay attention to. You don't normally need to configure this section.
589 \begin{itemize}
590 \item[\rcitem{acl}{serve}] Control incoming changesets that are arriving
591 from a remote repository over http or ssh. This is the default
592 value of \rcitem{acl}{sources}, and usually the only setting you'll
593 need for this configuration item.
594 \item[\rcitem{acl}{pull}] Control incoming changesets that are
595 arriving via a pull from a local repository.
596 \item[\rcitem{acl}{push}] Control incoming changesets that are
597 arriving via a push from a local repository.
598 \item[\rcitem{acl}{bundle}] Control incoming changesets that are
599 arriving from another repository via a bundle.
600 \end{itemize}
602 The \rcsection{acl.allow} section controls the users that are allowed to
603 add changesets to the repository. If this section is not present, all
604 users that are not explicitly denied are allowed. If this section is
605 present, all users that are not explicitly allowed are denied (so an
606 empty section means that all users are denied).
608 The \rcsection{acl.deny} section determines which users are denied
609 from adding changesets to the repository. If this section is not
610 present or is empty, no users are denied.
612 The syntaxes for the \rcsection{acl.allow} and \rcsection{acl.deny}
613 sections are identical. On the left of each entry is a glob pattern
614 that matches files or directories, relative to the root of the
615 repository; on the right, a user name.
617 In the following example, the user \texttt{docwriter} can only push
618 changes to the \dirname{docs} subtree of the repository, while
619 \texttt{intern} can push changes to any file or directory except
620 \dirname{source/sensitive}.
621 \begin{codesample2}
622 [acl.allow]
623 docs/** = docwriter
625 [acl.deny]
626 source/sensitive/** = intern
627 \end{codesample2}
629 \subsubsection{Testing and troubleshooting}
631 If you want to test the \hgext{acl} hook, run it with Mercurial's
632 debugging output enabled. Since you'll probably be running it on a
633 server where it's not convenient (or sometimes possible) to pass in
634 the \hggopt{--debug} option, don't forget that you can enable
635 debugging output in your \hgrc:
636 \begin{codesample2}
637 [ui]
638 debug = true
639 \end{codesample2}
640 With this enabled, the \hgext{acl} hook will print enough information
641 to let you figure out why it is allowing or forbidding pushes from
642 specific users.
644 \subsection{\hgext{bugzilla}---integration with Bugzilla}
646 The \hgext{bugzilla} extension adds a comment to a Bugzilla bug
647 whenever it finds a reference to that bug ID in a commit comment. You
648 can install this hook on a shared server, so that any time a remote
649 user pushes changes to this server, the hook gets run.
651 It adds a comment to the bug that looks like this (you can configure
652 the contents of the comment---see below):
653 \begin{codesample2}
654 Changeset aad8b264143a, made by Joe User <joe.user@domain.com> in
655 the frobnitz repository, refers to this bug.
657 For complete details, see
658 http://hg.domain.com/frobnitz?cmd=changeset;node=aad8b264143a
660 Changeset description:
661 Fix bug 10483 by guarding against some NULL pointers
662 \end{codesample2}
663 The value of this hook is that it automates the process of updating a
664 bug any time a changeset refers to it. If you configure the hook
665 properly, it makes it easy for people to browse straight from a
666 Bugzilla bug to a changeset that refers to that bug.
668 You can use the code in this hook as a starting point for some more
669 exotic Bugzilla integration recipes. Here are a few possibilities:
670 \begin{itemize}
671 \item Require that every changeset pushed to the server have a valid
672 bug~ID in its commit comment. In this case, you'd want to configure
673 the hook as a \hook{pretxncommit} hook. This would allow the hook
674 to reject changes that didn't contain bug IDs.
675 \item Allow incoming changesets to automatically modify the
676 \emph{state} of a bug, as well as simply adding a comment. For
677 example, the hook could recognise the string ``fixed bug 31337'' as
678 indicating that it should update the state of bug 31337 to
679 ``requires testing''.
680 \end{itemize}
682 \subsubsection{Configuring the \hook{bugzilla} hook}
683 \label{sec:hook:bugzilla:config}
685 You should configure this hook in your server's \hgrc\ as an
686 \hook{incoming} hook, for example as follows:
687 \begin{codesample2}
688 [hooks]
689 incoming.bugzilla = python:hgext.bugzilla.hook
690 \end{codesample2}
692 Because of the specialised nature of this hook, and because Bugzilla
693 was not written with this kind of integration in mind, configuring
694 this hook is a somewhat involved process.
696 Before you begin, you must install the MySQL bindings for Python on
697 the host(s) where you'll be running the hook. If this is not
698 available as a binary package for your system, you can download it
699 from~\cite{web:mysql-python}.
701 Configuration information for this hook lives in the
702 \rcsection{bugzilla} section of your \hgrc.
703 \begin{itemize}
704 \item[\rcitem{bugzilla}{version}] The version of Bugzilla installed on
705 the server. The database schema that Bugzilla uses changes
706 occasionally, so this hook has to know exactly which schema to use.
707 At the moment, the only version supported is \texttt{2.16}.
708 \item[\rcitem{bugzilla}{host}] The hostname of the MySQL server that
709 stores your Bugzilla data. The database must be configured to allow
710 connections from whatever host you are running the \hook{bugzilla}
711 hook on.
712 \item[\rcitem{bugzilla}{user}] The username with which to connect to
713 the MySQL server. The database must be configured to allow this
714 user to connect from whatever host you are running the
715 \hook{bugzilla} hook on. This user must be able to access and
716 modify Bugzilla tables. The default value of this item is
717 \texttt{bugs}, which is the standard name of the Bugzilla user in a
718 MySQL database.
719 \item[\rcitem{bugzilla}{password}] The MySQL password for the user you
720 configured above. This is stored as plain text, so you should make
721 sure that unauthorised users cannot read the \hgrc\ file where you
722 store this information.
723 \item[\rcitem{bugzilla}{db}] The name of the Bugzilla database on the
724 MySQL server. The default value of this item is \texttt{bugs},
725 which is the standard name of the MySQL database where Bugzilla
726 stores its data.
727 \item[\rcitem{bugzilla}{notify}] If you want Bugzilla to send out a
728 notification email to subscribers after this hook has added a
729 comment to a bug, you will need this hook to run a command whenever
730 it updates the database. The command to run depends on where you
731 have installed Bugzilla, but it will typically look something like
732 this, if you have Bugzilla installed in
733 \dirname{/var/www/html/bugzilla}:
734 \begin{codesample4}
735 cd /var/www/html/bugzilla && ./processmail %s nobody@nowhere.com
736 \end{codesample4}
737 The Bugzilla \texttt{processmail} program expects to be given a
738 bug~ID (the hook replaces ``\texttt{\%s}'' with the bug~ID) and an
739 email address. It also expects to be able to write to some files in
740 the directory that it runs in. If Bugzilla and this hook are not
741 installed on the same machine, you will need to find a way to run
742 \texttt{processmail} on the server where Bugzilla is installed.
743 \end{itemize}
745 \subsubsection{Mapping committer names to Bugzilla user names}
747 By default, the \hgext{bugzilla} hook tries to use the email address
748 of a changeset's committer as the Bugzilla user name with which to
749 update a bug. If this does not suit your needs, you can map committer
750 email addresses to Bugzilla user names using a \rcsection{usermap}
751 section.
753 Each item in the \rcsection{usermap} section contains an email address
754 on the left, and a Bugzilla user name on the right.
755 \begin{codesample2}
756 [usermap]
757 jane.user@example.com = jane
758 \end{codesample2}
759 You can either keep the \rcsection{usermap} data in a normal \hgrc, or
760 tell the \hgext{bugzilla} hook to read the information from an
761 external \filename{usermap} file. In the latter case, you can store
762 \filename{usermap} data by itself in (for example) a user-modifiable
763 repository. This makes it possible to let your users maintain their
764 own \rcitem{bugzilla}{usermap} entries. The main \hgrc\ file might
765 look like this:
766 \begin{codesample2}
767 # regular hgrc file refers to external usermap file
768 [bugzilla]
769 usermap = /home/hg/repos/userdata/bugzilla-usermap.conf
770 \end{codesample2}
771 While the \filename{usermap} file that it refers to might look like
772 this:
773 \begin{codesample2}
774 # bugzilla-usermap.conf - inside a hg repository
775 [usermap]
776 stephanie@example.com = steph
777 \end{codesample2}
779 \subsubsection{Configuring the text that gets added to a bug}
781 You can configure the text that this hook adds as a comment; you
782 specify it in the form of a Mercurial template. Several \hgrc\
783 entries (still in the \rcsection{bugzilla} section) control this
784 behaviour.
785 \begin{itemize}
786 \item[\texttt{strip}] The number of leading path elements to strip
787 from a repository's path name to construct a partial path for a URL.
788 For example, if the repositories on your server live under
789 \dirname{/home/hg/repos}, and you have a repository whose path is
790 \dirname{/home/hg/repos/app/tests}, then setting \texttt{strip} to
791 \texttt{4} will give a partial path of \dirname{app/tests}. The
792 hook will make this partial path available when expanding a
793 template, as \texttt{webroot}.
794 \item[\texttt{template}] The text of the template to use. In addition
795 to the usual changeset-related variables, this template can use
796 \texttt{hgweb} (the value of the \texttt{hgweb} configuration item
797 above) and \texttt{webroot} (the path constructed using
798 \texttt{strip} above).
799 \end{itemize}
801 In addition, you can add a \rcitem{web}{baseurl} item to the
802 \rcsection{web} section of your \hgrc. The \hgext{bugzilla} hook will
803 make this available when expanding a template, as the base string to
804 use when constructing a URL that will let users browse from a Bugzilla
805 comment to view a changeset. Example:
806 \begin{codesample2}
807 [web]
808 baseurl = http://hg.domain.com/
809 \end{codesample2}
811 Here is an example set of \hgext{bugzilla} hook config information.
812 \begin{codesample2}
813 [bugzilla]
814 host = bugzilla.example.com
815 password = mypassword
816 version = 2.16
817 # server-side repos live in /home/hg/repos, so strip 4 leading
818 # separators
819 strip = 4
820 hgweb = http://hg.example.com/
821 usermap = /home/hg/repos/notify/bugzilla.conf
822 template = Changeset \{node|short\}, made by \{author\} in the \{webroot\}
823 repo, refers to this bug.\\nFor complete details, see
824 \{hgweb\}\{webroot\}?cmd=changeset;node=\{node|short\}\\nChangeset
825 description:\\n\\t\{desc|tabindent\}
826 \end{codesample2}
828 \subsubsection{Testing and troubleshooting}
830 The most common problems with configuring the \hgext{bugzilla} hook
831 relate to running Bugzilla's \filename{processmail} script and mapping
832 committer names to user names.
834 Recall from section~\ref{sec:hook:bugzilla:config} above that the user
835 that runs the Mercurial process on the server is also the one that
836 will run the \filename{processmail} script. The
837 \filename{processmail} script sometimes causes Bugzilla to write to
838 files in its configuration directory, and Bugzilla's configuration
839 files are usually owned by the user that your web server runs under.
841 You can cause \filename{processmail} to be run with the suitable
842 user's identity using the \command{sudo} command. Here is an example
843 entry for a \filename{sudoers} file.
844 \begin{codesample2}
845 hg_user = (httpd_user) NOPASSWD: /var/www/html/bugzilla/processmail-wrapper %s
846 \end{codesample2}
847 This allows the \texttt{hg\_user} user to run a
848 \filename{processmail-wrapper} program under the identity of
849 \texttt{httpd\_user}.
851 This indirection through a wrapper script is necessary, because
852 \filename{processmail} expects to be run with its current directory
853 set to wherever you installed Bugzilla; you can't specify that kind of
854 constraint in a \filename{sudoers} file. The contents of the wrapper
855 script are simple:
856 \begin{codesample2}
857 #!/bin/sh
858 cd `dirname $0` && ./processmail "$1" nobody@example.com
859 \end{codesample2}
860 It doesn't seem to matter what email address you pass to
861 \filename{processmail}.
863 If your \rcsection{usermap} is not set up correctly, users will see an
864 error message from the \hgext{bugzilla} hook when they push changes
865 to the server. The error message will look like this:
866 \begin{codesample2}
867 cannot find bugzilla user id for john.q.public@example.com
868 \end{codesample2}
869 What this means is that the committer's address,
870 \texttt{john.q.public@example.com}, is not a valid Bugzilla user name,
871 nor does it have an entry in your \rcsection{usermap} that maps it to
872 a valid Bugzilla user name.
874 \subsection{\hgext{notify}---send email notifications}
876 Although Mercurial's built-in web server provides RSS feeds of changes
877 in every repository, many people prefer to receive change
878 notifications via email. The \hgext{notify} hook lets you send out
879 notifications to a set of email addresses whenever changesets arrive
880 that those subscribers are interested in.
882 As with the \hgext{bugzilla} hook, the \hgext{notify} hook is
883 template-driven, so you can customise the contents of the notification
884 messages that it sends.
886 By default, the \hgext{notify} hook includes a diff of every changeset
887 that it sends out; you can limit the size of the diff, or turn this
888 feature off entirely. It is useful for letting subscribers review
889 changes immediately, rather than clicking to follow a URL.
891 \subsubsection{Configuring the \hgext{notify} hook}
893 You can set up the \hgext{notify} hook to send one email message per
894 incoming changeset, or one per incoming group of changesets (all those
895 that arrived in a single pull or push).
896 \begin{codesample2}
897 [hooks]
898 # send one email per group of changes
899 changegroup.notify = python:hgext.notify.hook
900 # send one email per change
901 incoming.notify = python:hgext.notify.hook
902 \end{codesample2}
904 Configuration information for this hook lives in the
905 \rcsection{notify} section of a \hgrc\ file.
906 \begin{itemize}
907 \item[\rcitem{notify}{test}] By default, this hook does not send out
908 email at all; instead, it prints the message that it \emph{would}
909 send. Set this item to \texttt{false} to allow email to be sent.
910 The reason that sending of email is turned off by default is that it
911 takes several tries to configure this extension exactly as you would
912 like, and it would be bad form to spam subscribers with a number of
913 ``broken'' notifications while you debug your configuration.
914 \item[\rcitem{notify}{config}] The path to a configuration file that
915 contains subscription information. This is kept separate from the
916 main \hgrc\ so that you can maintain it in a repository of its own.
917 People can then clone that repository, update their subscriptions,
918 and push the changes back to your server.
919 \item[\rcitem{notify}{strip}] The number of leading path separator
920 characters to strip from a repository's path, when deciding whether
921 a repository has subscribers. For example, if the repositories on
922 your server live in \dirname{/home/hg/repos}, and \hgext{notify} is
923 considering a repository named \dirname{/home/hg/repos/shared/test},
924 setting \rcitem{notify}{strip} to \texttt{4} will cause
925 \hgext{notify} to trim the path it considers down to
926 \dirname{shared/test}, and it will match subscribers against that.
927 \item[\rcitem{notify}{template}] The template text to use when sending
928 messages. This specifies both the contents of the message header
929 and its body.
930 \item[\rcitem{notify}{maxdiff}] The maximum number of lines of diff
931 data to append to the end of a message. If a diff is longer than
932 this, it is truncated. By default, this is set to 300. Set this to
933 \texttt{0} to omit diffs from notification emails.
934 \item[\rcitem{notify}{sources}] A list of sources of changesets to
935 consider. This lets you limit \hgext{notify} to only sending out
936 email about changes that remote users pushed into this repository
937 via a server, for example. See section~\ref{sec:hook:sources} for
938 the sources you can specify here.
939 \end{itemize}
941 If you set the \rcitem{web}{baseurl} item in the \rcsection{web}
942 section, you can use it in a template; it will be available as
943 \texttt{webroot}.
945 Here is an example set of \hgext{notify} configuration information.
946 \begin{codesample2}
947 [notify]
948 # really send email
949 test = false
950 # subscriber data lives in the notify repo
951 config = /home/hg/repos/notify/notify.conf
952 # repos live in /home/hg/repos on server, so strip 4 "/" chars
953 strip = 4
954 template = X-Hg-Repo: \{webroot\}
955 Subject: \{webroot\}: \{desc|firstline|strip\}
956 From: \{author\}
958 changeset \{node|short\} in \{root\}
959 details: \{baseurl\}\{webroot\}?cmd=changeset;node=\{node|short\}
960 description:
961 \{desc|tabindent|strip\}
963 [web]
964 baseurl = http://hg.example.com/
965 \end{codesample2}
967 This will produce a message that looks like the following:
968 \begin{codesample2}
969 X-Hg-Repo: tests/slave
970 Subject: tests/slave: Handle error case when slave has no buffers
971 Date: Wed, 2 Aug 2006 15:25:46 -0700 (PDT)
973 changeset 3cba9bfe74b5 in /home/hg/repos/tests/slave
974 details: http://hg.example.com/tests/slave?cmd=changeset;node=3cba9bfe74b5
975 description:
976 Handle error case when slave has no buffers
977 diffs (54 lines):
979 diff -r 9d95df7cf2ad -r 3cba9bfe74b5 include/tests.h
980 --- a/include/tests.h Wed Aug 02 15:19:52 2006 -0700
981 +++ b/include/tests.h Wed Aug 02 15:25:26 2006 -0700
982 @@ -212,6 +212,15 @@ static __inline__ void test_headers(void *h)
983 [...snip...]
984 \end{codesample2}
986 \subsubsection{Testing and troubleshooting}
988 Do not forget that by default, the \hgext{notify} extension \emph{will
989 not send any mail} until you explicitly configure it to do so, by
990 setting \rcitem{notify}{test} to \texttt{false}. Until you do that,
991 it simply prints the message it \emph{would} send.
993 \section{Information for writers of hooks}
994 \label{sec:hook:ref}
996 \subsection{In-process hook execution}
998 An in-process hook is called with arguments of the following form:
999 \begin{codesample2}
1000 def myhook(ui, repo, **kwargs):
1001 pass
1002 \end{codesample2}
1003 The \texttt{ui} parameter is a \pymodclass{mercurial.ui}{ui} object.
1004 The \texttt{repo} parameter is a
1005 \pymodclass{mercurial.localrepo}{localrepository} object. The
1006 names and values of the \texttt{**kwargs} parameters depend on the
1007 hook being invoked, with the following common features:
1008 \begin{itemize}
1009 \item If a parameter is named \texttt{node} or
1010 \texttt{parent\emph{N}}, it will contain a hexadecimal changeset ID.
1011 The empty string is used to represent ``null changeset ID'' instead
1012 of a string of zeroes.
1013 \item If a parameter is named \texttt{url}, it will contain the URL of
1014 a remote repository, if that can be determined.
1015 \item Boolean-valued parameters are represented as Python
1016 \texttt{bool} objects.
1017 \end{itemize}
1019 An in-process hook is called without a change to the process's working
1020 directory (unlike external hooks, which are run in the root of the
1021 repository). It must not change the process's working directory, or
1022 it will cause any calls it makes into the Mercurial API to fail.
1024 If a hook returns a boolean ``false'' value, it is considered to have
1025 succeeded. If it returns a boolean ``true'' value or raises an
1026 exception, it is considered to have failed. A useful way to think of
1027 the calling convention is ``tell me if you fail''.
1029 Note that changeset IDs are passed into Python hooks as hexadecimal
1030 strings, not the binary hashes that Mercurial's APIs normally use. To
1031 convert a hash from hex to binary, use the
1032 \pymodfunc{mercurial.node}{bin} function.
1034 \subsection{External hook execution}
1036 An external hook is passed to the shell of the user running Mercurial.
1037 Features of that shell, such as variable substitution and command
1038 redirection, are available. The hook is run in the root directory of
1039 the repository (unlike in-process hooks, which are run in the same
1040 directory that Mercurial was run in).
1042 Hook parameters are passed to the hook as environment variables. Each
1043 environment variable's name is converted in upper case and prefixed
1044 with the string ``\texttt{HG\_}''. For example, if the name of a
1045 parameter is ``\texttt{node}'', the name of the environment variable
1046 representing that parameter will be ``\texttt{HG\_NODE}''.
1048 A boolean parameter is represented as the string ``\texttt{1}'' for
1049 ``true'', ``\texttt{0}'' for ``false''. If an environment variable is
1050 named \envar{HG\_NODE}, \envar{HG\_PARENT1} or \envar{HG\_PARENT2}, it
1051 contains a changeset ID represented as a hexadecimal string. The
1052 empty string is used to represent ``null changeset ID'' instead of a
1053 string of zeroes. If an environment variable is named
1054 \envar{HG\_URL}, it will contain the URL of a remote repository, if
1055 that can be determined.
1057 If a hook exits with a status of zero, it is considered to have
1058 succeeded. If it exits with a non-zero status, it is considered to
1059 have failed.
1061 \subsection{Finding out where changesets come from}
1063 A hook that involves the transfer of changesets between a local
1064 repository and another may be able to find out information about the
1065 ``far side''. Mercurial knows \emph{how} changes are being
1066 transferred, and in many cases \emph{where} they are being transferred
1067 to or from.
1069 \subsubsection{Sources of changesets}
1070 \label{sec:hook:sources}
1072 Mercurial will tell a hook what means are, or were, used to transfer
1073 changesets between repositories. This is provided by Mercurial in a
1074 Python parameter named \texttt{source}, or an environment variable named
1075 \envar{HG\_SOURCE}.
1077 \begin{itemize}
1078 \item[\texttt{serve}] Changesets are transferred to or from a remote
1079 repository over http or ssh.
1080 \item[\texttt{pull}] Changesets are being transferred via a pull from
1081 one repository into another.
1082 \item[\texttt{push}] Changesets are being transferred via a push from
1083 one repository into another.
1084 \item[\texttt{bundle}] Changesets are being transferred to or from a
1085 bundle.
1086 \end{itemize}
1088 \subsubsection{Where changes are going---remote repository URLs}
1089 \label{sec:hook:url}
1091 When possible, Mercurial will tell a hook the location of the ``far
1092 side'' of an activity that transfers changeset data between
1093 repositories. This is provided by Mercurial in a Python parameter
1094 named \texttt{url}, or an environment variable named \envar{HG\_URL}.
1096 This information is not always known. If a hook is invoked in a
1097 repository that is being served via http or ssh, Mercurial cannot tell
1098 where the remote repository is, but it may know where the client is
1099 connecting from. In such cases, the URL will take one of the
1100 following forms:
1101 \begin{itemize}
1102 \item \texttt{remote:ssh:\emph{ip-address}}---remote ssh client, at
1103 the given IP address.
1104 \item \texttt{remote:http:\emph{ip-address}}---remote http client, at
1105 the given IP address. If the client is using SSL, this will be of
1106 the form \texttt{remote:https:\emph{ip-address}}.
1107 \item Empty---no information could be discovered about the remote
1108 client.
1109 \end{itemize}
1111 \section{Hook reference}
1113 \subsection{\hook{changegroup}---after remote changesets added}
1114 \label{sec:hook:changegroup}
1116 This hook is run after a group of pre-existing changesets has been
1117 added to the repository, for example via a \hgcmd{pull} or
1118 \hgcmd{unbundle}. This hook is run once per operation that added one
1119 or more changesets. This is in contrast to the \hook{incoming} hook,
1120 which is run once per changeset, regardless of whether the changesets
1121 arrive in a group.
1123 Some possible uses for this hook include kicking off an automated
1124 build or test of the added changesets, updating a bug database, or
1125 notifying subscribers that a repository contains new changes.
1127 Parameters to this hook:
1128 \begin{itemize}
1129 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1130 changeset in the group that was added. All changesets between this
1131 and \index{tags!\texttt{tip}}\texttt{tip}, inclusive, were added by
1132 a single \hgcmd{pull}, \hgcmd{push} or \hgcmd{unbundle}.
1133 \item[\texttt{source}] A string. The source of these changes. See
1134 section~\ref{sec:hook:sources} for details.
1135 \item[\texttt{url}] A URL. The location of the remote repository, if
1136 known. See section~\ref{sec:hook:url} for more information.
1137 \end{itemize}
1139 See also: \hook{incoming} (section~\ref{sec:hook:incoming}),
1140 \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup}),
1141 \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1143 \subsection{\hook{commit}---after a new changeset is created}
1144 \label{sec:hook:commit}
1146 This hook is run after a new changeset has been created.
1148 Parameters to this hook:
1149 \begin{itemize}
1150 \item[\texttt{node}] A changeset ID. The changeset ID of the newly
1151 committed changeset.
1152 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1153 parent of the newly committed changeset.
1154 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1155 parent of the newly committed changeset.
1156 \end{itemize}
1158 See also: \hook{precommit} (section~\ref{sec:hook:precommit}),
1159 \hook{pretxncommit} (section~\ref{sec:hook:pretxncommit})
1161 \subsection{\hook{incoming}---after one remote changeset is added}
1162 \label{sec:hook:incoming}
1164 This hook is run after a pre-existing changeset has been added to the
1165 repository, for example via a \hgcmd{push}. If a group of changesets
1166 was added in a single operation, this hook is called once for each
1167 added changeset.
1169 You can use this hook for the same purposes as the \hook{changegroup}
1170 hook (section~\ref{sec:hook:changegroup}); it's simply more convenient
1171 sometimes to run a hook once per group of changesets, while other
1172 times it's handier once per changeset.
1174 Parameters to this hook:
1175 \begin{itemize}
1176 \item[\texttt{node}] A changeset ID. The ID of the newly added
1177 changeset.
1178 \item[\texttt{source}] A string. The source of these changes. See
1179 section~\ref{sec:hook:sources} for details.
1180 \item[\texttt{url}] A URL. The location of the remote repository, if
1181 known. See section~\ref{sec:hook:url} for more information.
1182 \end{itemize}
1184 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}) \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup}), \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1186 \subsection{\hook{outgoing}---after changesets are propagated}
1187 \label{sec:hook:outgoing}
1189 This hook is run after a group of changesets has been propagated out
1190 of this repository, for example by a \hgcmd{push} or \hgcmd{bundle}
1191 command.
1193 One possible use for this hook is to notify administrators that
1194 changes have been pulled.
1196 Parameters to this hook:
1197 \begin{itemize}
1198 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1199 changeset of the group that was sent.
1200 \item[\texttt{source}] A string. The source of the of the operation
1201 (see section~\ref{sec:hook:sources}). If a remote client pulled
1202 changes from this repository, \texttt{source} will be
1203 \texttt{serve}. If the client that obtained changes from this
1204 repository was local, \texttt{source} will be \texttt{bundle},
1205 \texttt{pull}, or \texttt{push}, depending on the operation the
1206 client performed.
1207 \item[\texttt{url}] A URL. The location of the remote repository, if
1208 known. See section~\ref{sec:hook:url} for more information.
1209 \end{itemize}
1211 See also: \hook{preoutgoing} (section~\ref{sec:hook:preoutgoing})
1213 \subsection{\hook{prechangegroup}---before starting to add remote changesets}
1214 \label{sec:hook:prechangegroup}
1216 This controlling hook is run before Mercurial begins to add a group of
1217 changesets from another repository.
1219 This hook does not have any information about the changesets to be
1220 added, because it is run before transmission of those changesets is
1221 allowed to begin. If this hook fails, the changesets will not be
1222 transmitted.
1224 One use for this hook is to prevent external changes from being added
1225 to a repository. For example, you could use this to ``freeze'' a
1226 server-hosted branch temporarily or permanently so that users cannot
1227 push to it, while still allowing a local administrator to modify the
1228 repository.
1230 Parameters to this hook:
1231 \begin{itemize}
1232 \item[\texttt{source}] A string. The source of these changes. See
1233 section~\ref{sec:hook:sources} for details.
1234 \item[\texttt{url}] A URL. The location of the remote repository, if
1235 known. See section~\ref{sec:hook:url} for more information.
1236 \end{itemize}
1238 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}),
1239 \hook{incoming} (section~\ref{sec:hook:incoming}), ,
1240 \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1242 \subsection{\hook{precommit}---before starting to commit a changeset}
1243 \label{sec:hook:precommit}
1245 This hook is run before Mercurial begins to commit a new changeset.
1246 It is run before Mercurial has any of the metadata for the commit,
1247 such as the files to be committed, the commit message, or the commit
1248 date.
1250 One use for this hook is to disable the ability to commit new
1251 changesets, while still allowing incoming changesets. Another is to
1252 run a build or test, and only allow the commit to begin if the build
1253 or test succeeds.
1255 Parameters to this hook:
1256 \begin{itemize}
1257 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1258 parent of the working directory.
1259 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1260 parent of the working directory.
1261 \end{itemize}
1262 If the commit proceeds, the parents of the working directory will
1263 become the parents of the new changeset.
1265 See also: \hook{commit} (section~\ref{sec:hook:commit}),
1266 \hook{pretxncommit} (section~\ref{sec:hook:pretxncommit})
1268 \subsection{\hook{preoutgoing}---before starting to propagate changesets}
1269 \label{sec:hook:preoutgoing}
1271 This hook is invoked before Mercurial knows the identities of the
1272 changesets to be transmitted.
1274 One use for this hook is to prevent changes from being transmitted to
1275 another repository.
1277 Parameters to this hook:
1278 \begin{itemize}
1279 \item[\texttt{source}] A string. The source of the operation that is
1280 attempting to obtain changes from this repository (see
1281 section~\ref{sec:hook:sources}). See the documentation for the
1282 \texttt{source} parameter to the \hook{outgoing} hook, in
1283 section~\ref{sec:hook:outgoing}, for possible values of this
1284 parameter.
1285 \item[\texttt{url}] A URL. The location of the remote repository, if
1286 known. See section~\ref{sec:hook:url} for more information.
1287 \end{itemize}
1289 See also: \hook{outgoing} (section~\ref{sec:hook:outgoing})
1291 \subsection{\hook{pretag}---before tagging a changeset}
1292 \label{sec:hook:pretag}
1294 This controlling hook is run before a tag is created. If the hook
1295 succeeds, creation of the tag proceeds. If the hook fails, the tag is
1296 not created.
1298 Parameters to this hook:
1299 \begin{itemize}
1300 \item[\texttt{local}] A boolean. Whether the tag is local to this
1301 repository instance (i.e.~stored in \sfilename{.hg/localtags}) or
1302 managed by Mercurial (stored in \sfilename{.hgtags}).
1303 \item[\texttt{node}] A changeset ID. The ID of the changeset to be tagged.
1304 \item[\texttt{tag}] A string. The name of the tag to be created.
1305 \end{itemize}
1307 If the tag to be created is revision-controlled, the \hook{precommit}
1308 and \hook{pretxncommit} hooks (sections~\ref{sec:hook:commit}
1309 and~\ref{sec:hook:pretxncommit}) will also be run.
1311 See also: \hook{tag} (section~\ref{sec:hook:tag})
1313 \subsection{\hook{pretxnchangegroup}---before completing addition of
1314 remote changesets}
1315 \label{sec:hook:pretxnchangegroup}
1317 This controlling hook is run before a transaction---that manages the
1318 addition of a group of new changesets from outside the
1319 repository---completes. If the hook succeeds, the transaction
1320 completes, and all of the changesets become permanent within this
1321 repository. If the hook fails, the transaction is rolled back, and
1322 the data for the changesets is erased.
1324 This hook can access the metadata associated with the almost-added
1325 changesets, but it should not do anything permanent with this data.
1326 It must also not modify the working directory.
1328 While this hook is running, if other Mercurial processes access this
1329 repository, they will be able to see the almost-added changesets as if
1330 they are permanent. This may lead to race conditions if you do not
1331 take steps to avoid them.
1333 This hook can be used to automatically vet a group of changesets. If
1334 the hook fails, all of the changesets are ``rejected'' when the
1335 transaction rolls back.
1337 Parameters to this hook:
1338 \begin{itemize}
1339 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1340 changeset in the group that was added. All changesets between this
1341 and \index{tags!\texttt{tip}}\texttt{tip}, inclusive, were added by
1342 a single \hgcmd{pull}, \hgcmd{push} or \hgcmd{unbundle}.
1343 \item[\texttt{source}] A string. The source of these changes. See
1344 section~\ref{sec:hook:sources} for details.
1345 \item[\texttt{url}] A URL. The location of the remote repository, if
1346 known. See section~\ref{sec:hook:url} for more information.
1347 \end{itemize}
1349 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}),
1350 \hook{incoming} (section~\ref{sec:hook:incoming}),
1351 \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup})
1353 \subsection{\hook{pretxncommit}---before completing commit of new changeset}
1354 \label{sec:hook:pretxncommit}
1356 This controlling hook is run before a transaction---that manages a new
1357 commit---completes. If the hook succeeds, the transaction completes
1358 and the changeset becomes permanent within this repository. If the
1359 hook fails, the transaction is rolled back, and the commit data is
1360 erased.
1362 This hook can access the metadata associated with the almost-new
1363 changeset, but it should not do anything permanent with this data. It
1364 must also not modify the working directory.
1366 While this hook is running, if other Mercurial processes access this
1367 repository, they will be able to see the almost-new changeset as if it
1368 is permanent. This may lead to race conditions if you do not take
1369 steps to avoid them.
1371 Parameters to this hook:
1372 \begin{itemize}
1373 \item[\texttt{node}] A changeset ID. The changeset ID of the newly
1374 committed changeset.
1375 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1376 parent of the newly committed changeset.
1377 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1378 parent of the newly committed changeset.
1379 \end{itemize}
1381 See also: \hook{precommit} (section~\ref{sec:hook:precommit})
1383 \subsection{\hook{preupdate}---before updating or merging working directory}
1384 \label{sec:hook:preupdate}
1386 This controlling hook is run before an update or merge of the working
1387 directory begins. It is run only if Mercurial's normal pre-update
1388 checks determine that the update or merge can proceed. If the hook
1389 succeeds, the update or merge may proceed; if it fails, the update or
1390 merge does not start.
1392 Parameters to this hook:
1393 \begin{itemize}
1394 \item[\texttt{parent1}] A changeset ID. The ID of the parent that the
1395 working directory is to be updated to. If the working directory is
1396 being merged, it will not change this parent.
1397 \item[\texttt{parent2}] A changeset ID. Only set if the working
1398 directory is being merged. The ID of the revision that the working
1399 directory is being merged with.
1400 \end{itemize}
1402 See also: \hook{update} (section~\ref{sec:hook:update})
1404 \subsection{\hook{tag}---after tagging a changeset}
1405 \label{sec:hook:tag}
1407 This hook is run after a tag has been created.
1409 Parameters to this hook:
1410 \begin{itemize}
1411 \item[\texttt{local}] A boolean. Whether the new tag is local to this
1412 repository instance (i.e.~stored in \sfilename{.hg/localtags}) or
1413 managed by Mercurial (stored in \sfilename{.hgtags}).
1414 \item[\texttt{node}] A changeset ID. The ID of the changeset that was
1415 tagged.
1416 \item[\texttt{tag}] A string. The name of the tag that was created.
1417 \end{itemize}
1419 If the created tag is revision-controlled, the \hook{commit} hook
1420 (section~\ref{sec:hook:commit}) is run before this hook.
1422 See also: \hook{pretag} (section~\ref{sec:hook:pretag})
1424 \subsection{\hook{update}---after updating or merging working directory}
1425 \label{sec:hook:update}
1427 This hook is run after an update or merge of the working directory
1428 completes. Since a merge can fail (if the external \command{hgmerge}
1429 command fails to resolve conflicts in a file), this hook communicates
1430 whether the update or merge completed cleanly.
1432 \begin{itemize}
1433 \item[\texttt{error}] A boolean. Indicates whether the update or
1434 merge completed successfully.
1435 \item[\texttt{parent1}] A changeset ID. The ID of the parent that the
1436 working directory was updated to. If the working directory was
1437 merged, it will not have changed this parent.
1438 \item[\texttt{parent2}] A changeset ID. Only set if the working
1439 directory was merged. The ID of the revision that the working
1440 directory was merged with.
1441 \end{itemize}
1443 See also: \hook{preupdate} (section~\ref{sec:hook:preupdate})
1445 %%% Local Variables:
1446 %%% mode: latex
1447 %%% TeX-master: "00book"
1448 %%% End: