hgbook

view es/hook.tex @ 441:4e0684e824e1

translated up to the tutorial on using hooks
author jerojasro@abu.no-ip.org
date Mon Dec 08 11:16:54 2008 -0500 (2008-12-08)
parents 05bfbe50e7e4
children 606295a87ff2
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 It is easy to write a Mercurial hook. Let's start with a hook that
262 runs when you finish a \hgcmd{commit}, and simply prints the hash of
263 the changeset you just created. The hook is called \hook{commit}.
265 \begin{figure}[ht]
266 \interaction{hook.simple.init}
267 \caption{A simple hook that runs when a changeset is committed}
268 \label{ex:hook:init}
269 \end{figure}
271 All hooks follow the pattern in example~\ref{ex:hook:init}. You add
272 an entry to the \rcsection{hooks} section of your \hgrc. On the left
273 is the name of the event to trigger on; on the right is the action to
274 take. As you can see, you can run an arbitrary shell command in a
275 hook. Mercurial passes extra information to the hook using
276 environment variables (look for \envar{HG\_NODE} in the example).
278 \subsection{Performing multiple actions per event}
280 Quite often, you will want to define more than one hook for a
281 particular kind of event, as shown in example~\ref{ex:hook:ext}.
282 Mercurial lets you do this by adding an \emph{extension} to the end of
283 a hook's name. You extend a hook's name by giving the name of the
284 hook, followed by a full stop (the ``\texttt{.}'' character), followed
285 by some more text of your choosing. For example, Mercurial will run
286 both \texttt{commit.foo} and \texttt{commit.bar} when the
287 \texttt{commit} event occurs.
289 \begin{figure}[ht]
290 \interaction{hook.simple.ext}
291 \caption{Defining a second \hook{commit} hook}
292 \label{ex:hook:ext}
293 \end{figure}
295 To give a well-defined order of execution when there are multiple
296 hooks defined for an event, Mercurial sorts hooks by extension, and
297 executes the hook commands in this sorted order. In the above
298 example, it will execute \texttt{commit.bar} before
299 \texttt{commit.foo}, and \texttt{commit} before both.
301 It is a good idea to use a somewhat descriptive extension when you
302 define a new hook. This will help you to remember what the hook was
303 for. If the hook fails, you'll get an error message that contains the
304 hook name and extension, so using a descriptive extension could give
305 you an immediate hint as to why the hook failed (see
306 section~\ref{sec:hook:perm} for an example).
308 \subsection{Controlling whether an activity can proceed}
309 \label{sec:hook:perm}
311 In our earlier examples, we used the \hook{commit} hook, which is
312 run after a commit has completed. This is one of several Mercurial
313 hooks that run after an activity finishes. Such hooks have no way of
314 influencing the activity itself.
316 Mercurial defines a number of events that occur before an activity
317 starts; or after it starts, but before it finishes. Hooks that
318 trigger on these events have the added ability to choose whether the
319 activity can continue, or will abort.
321 The \hook{pretxncommit} hook runs after a commit has all but
322 completed. In other words, the metadata representing the changeset
323 has been written out to disk, but the transaction has not yet been
324 allowed to complete. The \hook{pretxncommit} hook has the ability to
325 decide whether the transaction can complete, or must be rolled back.
327 If the \hook{pretxncommit} hook exits with a status code of zero, the
328 transaction is allowed to complete; the commit finishes; and the
329 \hook{commit} hook is run. If the \hook{pretxncommit} hook exits with
330 a non-zero status code, the transaction is rolled back; the metadata
331 representing the changeset is erased; and the \hook{commit} hook is
332 not run.
334 \begin{figure}[ht]
335 \interaction{hook.simple.pretxncommit}
336 \caption{Using the \hook{pretxncommit} hook to control commits}
337 \label{ex:hook:pretxncommit}
338 \end{figure}
340 The hook in example~\ref{ex:hook:pretxncommit} checks that a commit
341 comment contains a bug ID. If it does, the commit can complete. If
342 not, the commit is rolled back.
344 \section{Writing your own hooks}
346 When you are writing a hook, you might find it useful to run Mercurial
347 either with the \hggopt{-v} option, or the \rcitem{ui}{verbose} config
348 item set to ``true''. When you do so, Mercurial will print a message
349 before it calls each hook.
351 \subsection{Choosing how your hook should run}
352 \label{sec:hook:lang}
354 You can write a hook either as a normal program---typically a shell
355 script---or as a Python function that is executed within the Mercurial
356 process.
358 Writing a hook as an external program has the advantage that it
359 requires no knowledge of Mercurial's internals. You can call normal
360 Mercurial commands to get any added information you need. The
361 trade-off is that external hooks are slower than in-process hooks.
363 An in-process Python hook has complete access to the Mercurial API,
364 and does not ``shell out'' to another process, so it is inherently
365 faster than an external hook. It is also easier to obtain much of the
366 information that a hook requires by using the Mercurial API than by
367 running Mercurial commands.
369 If you are comfortable with Python, or require high performance,
370 writing your hooks in Python may be a good choice. However, when you
371 have a straightforward hook to write and you don't need to care about
372 performance (probably the majority of hooks), a shell script is
373 perfectly fine.
375 \subsection{Hook parameters}
376 \label{sec:hook:param}
378 Mercurial calls each hook with a set of well-defined parameters. In
379 Python, a parameter is passed as a keyword argument to your hook
380 function. For an external program, a parameter is passed as an
381 environment variable.
383 Whether your hook is written in Python or as a shell script, the
384 hook-specific parameter names and values will be the same. A boolean
385 parameter will be represented as a boolean value in Python, but as the
386 number 1 (for ``true'') or 0 (for ``false'') as an environment
387 variable for an external hook. If a hook parameter is named
388 \texttt{foo}, the keyword argument for a Python hook will also be
389 named \texttt{foo}, while the environment variable for an external
390 hook will be named \texttt{HG\_FOO}.
392 \subsection{Hook return values and activity control}
394 A hook that executes successfully must exit with a status of zero if
395 external, or return boolean ``false'' if in-process. Failure is
396 indicated with a non-zero exit status from an external hook, or an
397 in-process hook returning boolean ``true''. If an in-process hook
398 raises an exception, the hook is considered to have failed.
400 For a hook that controls whether an activity can proceed, zero/false
401 means ``allow'', while non-zero/true/exception means ``deny''.
403 \subsection{Writing an external hook}
405 When you define an external hook in your \hgrc\ and the hook is run,
406 its value is passed to your shell, which interprets it. This means
407 that you can use normal shell constructs in the body of the hook.
409 An executable hook is always run with its current directory set to a
410 repository's root directory.
412 Each hook parameter is passed in as an environment variable; the name
413 is upper-cased, and prefixed with the string ``\texttt{HG\_}''.
415 With the exception of hook parameters, Mercurial does not set or
416 modify any environment variables when running a hook. This is useful
417 to remember if you are writing a site-wide hook that may be run by a
418 number of different users with differing environment variables set.
419 In multi-user situations, you should not rely on environment variables
420 being set to the values you have in your environment when testing the
421 hook.
423 \subsection{Telling Mercurial to use an in-process hook}
425 The \hgrc\ syntax for defining an in-process hook is slightly
426 different than for an executable hook. The value of the hook must
427 start with the text ``\texttt{python:}'', and continue with the
428 fully-qualified name of a callable object to use as the hook's value.
430 The module in which a hook lives is automatically imported when a hook
431 is run. So long as you have the module name and \envar{PYTHONPATH}
432 right, it should ``just work''.
434 The following \hgrc\ example snippet illustrates the syntax and
435 meaning of the notions we just described.
436 \begin{codesample2}
437 [hooks]
438 commit.example = python:mymodule.submodule.myhook
439 \end{codesample2}
440 When Mercurial runs the \texttt{commit.example} hook, it imports
441 \texttt{mymodule.submodule}, looks for the callable object named
442 \texttt{myhook}, and calls it.
444 \subsection{Writing an in-process hook}
446 The simplest in-process hook does nothing, but illustrates the basic
447 shape of the hook API:
448 \begin{codesample2}
449 def myhook(ui, repo, **kwargs):
450 pass
451 \end{codesample2}
452 The first argument to a Python hook is always a
453 \pymodclass{mercurial.ui}{ui} object. The second is a repository object;
454 at the moment, it is always an instance of
455 \pymodclass{mercurial.localrepo}{localrepository}. Following these two
456 arguments are other keyword arguments. Which ones are passed in
457 depends on the hook being called, but a hook can ignore arguments it
458 doesn't care about by dropping them into a keyword argument dict, as
459 with \texttt{**kwargs} above.
461 \section{Some hook examples}
463 \subsection{Writing meaningful commit messages}
465 It's hard to imagine a useful commit message being very short. The
466 simple \hook{pretxncommit} hook of figure~\ref{ex:hook:msglen.go}
467 will prevent you from committing a changeset with a message that is
468 less than ten bytes long.
470 \begin{figure}[ht]
471 \interaction{hook.msglen.go}
472 \caption{A hook that forbids overly short commit messages}
473 \label{ex:hook:msglen.go}
474 \end{figure}
476 \subsection{Checking for trailing whitespace}
478 An interesting use of a commit-related hook is to help you to write
479 cleaner code. A simple example of ``cleaner code'' is the dictum that
480 a change should not add any new lines of text that contain ``trailing
481 whitespace''. Trailing whitespace is a series of space and tab
482 characters at the end of a line of text. In most cases, trailing
483 whitespace is unnecessary, invisible noise, but it is occasionally
484 problematic, and people often prefer to get rid of it.
486 You can use either the \hook{precommit} or \hook{pretxncommit} hook to
487 tell whether you have a trailing whitespace problem. If you use the
488 \hook{precommit} hook, the hook will not know which files you are
489 committing, so it will have to check every modified file in the
490 repository for trailing white space. If you want to commit a change
491 to just the file \filename{foo}, but the file \filename{bar} contains
492 trailing whitespace, doing a check in the \hook{precommit} hook will
493 prevent you from committing \filename{foo} due to the problem with
494 \filename{bar}. This doesn't seem right.
496 Should you choose the \hook{pretxncommit} hook, the check won't occur
497 until just before the transaction for the commit completes. This will
498 allow you to check for problems only the exact files that are being
499 committed. However, if you entered the commit message interactively
500 and the hook fails, the transaction will roll back; you'll have to
501 re-enter the commit message after you fix the trailing whitespace and
502 run \hgcmd{commit} again.
504 \begin{figure}[ht]
505 \interaction{hook.ws.simple}
506 \caption{A simple hook that checks for trailing whitespace}
507 \label{ex:hook:ws.simple}
508 \end{figure}
510 Figure~\ref{ex:hook:ws.simple} introduces a simple \hook{pretxncommit}
511 hook that checks for trailing whitespace. This hook is short, but not
512 very helpful. It exits with an error status if a change adds a line
513 with trailing whitespace to any file, but does not print any
514 information that might help us to identify the offending file or
515 line. It also has the nice property of not paying attention to
516 unmodified lines; only lines that introduce new trailing whitespace
517 cause problems.
519 \begin{figure}[ht]
520 \interaction{hook.ws.better}
521 \caption{A better trailing whitespace hook}
522 \label{ex:hook:ws.better}
523 \end{figure}
525 The example of figure~\ref{ex:hook:ws.better} is much more complex,
526 but also more useful. It parses a unified diff to see if any lines
527 add trailing whitespace, and prints the name of the file and the line
528 number of each such occurrence. Even better, if the change adds
529 trailing whitespace, this hook saves the commit comment and prints the
530 name of the save file before exiting and telling Mercurial to roll the
531 transaction back, so you can use
532 \hgcmdargs{commit}{\hgopt{commit}{-l}~\emph{filename}} to reuse the
533 saved commit message once you've corrected the problem.
535 As a final aside, note in figure~\ref{ex:hook:ws.better} the use of
536 \command{perl}'s in-place editing feature to get rid of trailing
537 whitespace from a file. This is concise and useful enough that I will
538 reproduce it here.
539 \begin{codesample2}
540 perl -pi -e 's,\\s+\$,,' filename
541 \end{codesample2}
543 \section{Bundled hooks}
545 Mercurial ships with several bundled hooks. You can find them in the
546 \dirname{hgext} directory of a Mercurial source tree. If you are
547 using a Mercurial binary package, the hooks will be located in the
548 \dirname{hgext} directory of wherever your package installer put
549 Mercurial.
551 \subsection{\hgext{acl}---access control for parts of a repository}
553 The \hgext{acl} extension lets you control which remote users are
554 allowed to push changesets to a networked server. You can protect any
555 portion of a repository (including the entire repo), so that a
556 specific remote user can push changes that do not affect the protected
557 portion.
559 This extension implements access control based on the identity of the
560 user performing a push, \emph{not} on who committed the changesets
561 they're pushing. It makes sense to use this hook only if you have a
562 locked-down server environment that authenticates remote users, and
563 you want to be sure that only specific users are allowed to push
564 changes to that server.
566 \subsubsection{Configuring the \hook{acl} hook}
568 In order to manage incoming changesets, the \hgext{acl} hook must be
569 used as a \hook{pretxnchangegroup} hook. This lets it see which files
570 are modified by each incoming changeset, and roll back a group of
571 changesets if they modify ``forbidden'' files. Example:
572 \begin{codesample2}
573 [hooks]
574 pretxnchangegroup.acl = python:hgext.acl.hook
575 \end{codesample2}
577 The \hgext{acl} extension is configured using three sections.
579 The \rcsection{acl} section has only one entry, \rcitem{acl}{sources},
580 which lists the sources of incoming changesets that the hook should
581 pay attention to. You don't normally need to configure this section.
582 \begin{itemize}
583 \item[\rcitem{acl}{serve}] Control incoming changesets that are arriving
584 from a remote repository over http or ssh. This is the default
585 value of \rcitem{acl}{sources}, and usually the only setting you'll
586 need for this configuration item.
587 \item[\rcitem{acl}{pull}] Control incoming changesets that are
588 arriving via a pull from a local repository.
589 \item[\rcitem{acl}{push}] Control incoming changesets that are
590 arriving via a push from a local repository.
591 \item[\rcitem{acl}{bundle}] Control incoming changesets that are
592 arriving from another repository via a bundle.
593 \end{itemize}
595 The \rcsection{acl.allow} section controls the users that are allowed to
596 add changesets to the repository. If this section is not present, all
597 users that are not explicitly denied are allowed. If this section is
598 present, all users that are not explicitly allowed are denied (so an
599 empty section means that all users are denied).
601 The \rcsection{acl.deny} section determines which users are denied
602 from adding changesets to the repository. If this section is not
603 present or is empty, no users are denied.
605 The syntaxes for the \rcsection{acl.allow} and \rcsection{acl.deny}
606 sections are identical. On the left of each entry is a glob pattern
607 that matches files or directories, relative to the root of the
608 repository; on the right, a user name.
610 In the following example, the user \texttt{docwriter} can only push
611 changes to the \dirname{docs} subtree of the repository, while
612 \texttt{intern} can push changes to any file or directory except
613 \dirname{source/sensitive}.
614 \begin{codesample2}
615 [acl.allow]
616 docs/** = docwriter
618 [acl.deny]
619 source/sensitive/** = intern
620 \end{codesample2}
622 \subsubsection{Testing and troubleshooting}
624 If you want to test the \hgext{acl} hook, run it with Mercurial's
625 debugging output enabled. Since you'll probably be running it on a
626 server where it's not convenient (or sometimes possible) to pass in
627 the \hggopt{--debug} option, don't forget that you can enable
628 debugging output in your \hgrc:
629 \begin{codesample2}
630 [ui]
631 debug = true
632 \end{codesample2}
633 With this enabled, the \hgext{acl} hook will print enough information
634 to let you figure out why it is allowing or forbidding pushes from
635 specific users.
637 \subsection{\hgext{bugzilla}---integration with Bugzilla}
639 The \hgext{bugzilla} extension adds a comment to a Bugzilla bug
640 whenever it finds a reference to that bug ID in a commit comment. You
641 can install this hook on a shared server, so that any time a remote
642 user pushes changes to this server, the hook gets run.
644 It adds a comment to the bug that looks like this (you can configure
645 the contents of the comment---see below):
646 \begin{codesample2}
647 Changeset aad8b264143a, made by Joe User <joe.user@domain.com> in
648 the frobnitz repository, refers to this bug.
650 For complete details, see
651 http://hg.domain.com/frobnitz?cmd=changeset;node=aad8b264143a
653 Changeset description:
654 Fix bug 10483 by guarding against some NULL pointers
655 \end{codesample2}
656 The value of this hook is that it automates the process of updating a
657 bug any time a changeset refers to it. If you configure the hook
658 properly, it makes it easy for people to browse straight from a
659 Bugzilla bug to a changeset that refers to that bug.
661 You can use the code in this hook as a starting point for some more
662 exotic Bugzilla integration recipes. Here are a few possibilities:
663 \begin{itemize}
664 \item Require that every changeset pushed to the server have a valid
665 bug~ID in its commit comment. In this case, you'd want to configure
666 the hook as a \hook{pretxncommit} hook. This would allow the hook
667 to reject changes that didn't contain bug IDs.
668 \item Allow incoming changesets to automatically modify the
669 \emph{state} of a bug, as well as simply adding a comment. For
670 example, the hook could recognise the string ``fixed bug 31337'' as
671 indicating that it should update the state of bug 31337 to
672 ``requires testing''.
673 \end{itemize}
675 \subsubsection{Configuring the \hook{bugzilla} hook}
676 \label{sec:hook:bugzilla:config}
678 You should configure this hook in your server's \hgrc\ as an
679 \hook{incoming} hook, for example as follows:
680 \begin{codesample2}
681 [hooks]
682 incoming.bugzilla = python:hgext.bugzilla.hook
683 \end{codesample2}
685 Because of the specialised nature of this hook, and because Bugzilla
686 was not written with this kind of integration in mind, configuring
687 this hook is a somewhat involved process.
689 Before you begin, you must install the MySQL bindings for Python on
690 the host(s) where you'll be running the hook. If this is not
691 available as a binary package for your system, you can download it
692 from~\cite{web:mysql-python}.
694 Configuration information for this hook lives in the
695 \rcsection{bugzilla} section of your \hgrc.
696 \begin{itemize}
697 \item[\rcitem{bugzilla}{version}] The version of Bugzilla installed on
698 the server. The database schema that Bugzilla uses changes
699 occasionally, so this hook has to know exactly which schema to use.
700 At the moment, the only version supported is \texttt{2.16}.
701 \item[\rcitem{bugzilla}{host}] The hostname of the MySQL server that
702 stores your Bugzilla data. The database must be configured to allow
703 connections from whatever host you are running the \hook{bugzilla}
704 hook on.
705 \item[\rcitem{bugzilla}{user}] The username with which to connect to
706 the MySQL server. The database must be configured to allow this
707 user to connect from whatever host you are running the
708 \hook{bugzilla} hook on. This user must be able to access and
709 modify Bugzilla tables. The default value of this item is
710 \texttt{bugs}, which is the standard name of the Bugzilla user in a
711 MySQL database.
712 \item[\rcitem{bugzilla}{password}] The MySQL password for the user you
713 configured above. This is stored as plain text, so you should make
714 sure that unauthorised users cannot read the \hgrc\ file where you
715 store this information.
716 \item[\rcitem{bugzilla}{db}] The name of the Bugzilla database on the
717 MySQL server. The default value of this item is \texttt{bugs},
718 which is the standard name of the MySQL database where Bugzilla
719 stores its data.
720 \item[\rcitem{bugzilla}{notify}] If you want Bugzilla to send out a
721 notification email to subscribers after this hook has added a
722 comment to a bug, you will need this hook to run a command whenever
723 it updates the database. The command to run depends on where you
724 have installed Bugzilla, but it will typically look something like
725 this, if you have Bugzilla installed in
726 \dirname{/var/www/html/bugzilla}:
727 \begin{codesample4}
728 cd /var/www/html/bugzilla && ./processmail %s nobody@nowhere.com
729 \end{codesample4}
730 The Bugzilla \texttt{processmail} program expects to be given a
731 bug~ID (the hook replaces ``\texttt{\%s}'' with the bug~ID) and an
732 email address. It also expects to be able to write to some files in
733 the directory that it runs in. If Bugzilla and this hook are not
734 installed on the same machine, you will need to find a way to run
735 \texttt{processmail} on the server where Bugzilla is installed.
736 \end{itemize}
738 \subsubsection{Mapping committer names to Bugzilla user names}
740 By default, the \hgext{bugzilla} hook tries to use the email address
741 of a changeset's committer as the Bugzilla user name with which to
742 update a bug. If this does not suit your needs, you can map committer
743 email addresses to Bugzilla user names using a \rcsection{usermap}
744 section.
746 Each item in the \rcsection{usermap} section contains an email address
747 on the left, and a Bugzilla user name on the right.
748 \begin{codesample2}
749 [usermap]
750 jane.user@example.com = jane
751 \end{codesample2}
752 You can either keep the \rcsection{usermap} data in a normal \hgrc, or
753 tell the \hgext{bugzilla} hook to read the information from an
754 external \filename{usermap} file. In the latter case, you can store
755 \filename{usermap} data by itself in (for example) a user-modifiable
756 repository. This makes it possible to let your users maintain their
757 own \rcitem{bugzilla}{usermap} entries. The main \hgrc\ file might
758 look like this:
759 \begin{codesample2}
760 # regular hgrc file refers to external usermap file
761 [bugzilla]
762 usermap = /home/hg/repos/userdata/bugzilla-usermap.conf
763 \end{codesample2}
764 While the \filename{usermap} file that it refers to might look like
765 this:
766 \begin{codesample2}
767 # bugzilla-usermap.conf - inside a hg repository
768 [usermap]
769 stephanie@example.com = steph
770 \end{codesample2}
772 \subsubsection{Configuring the text that gets added to a bug}
774 You can configure the text that this hook adds as a comment; you
775 specify it in the form of a Mercurial template. Several \hgrc\
776 entries (still in the \rcsection{bugzilla} section) control this
777 behaviour.
778 \begin{itemize}
779 \item[\texttt{strip}] The number of leading path elements to strip
780 from a repository's path name to construct a partial path for a URL.
781 For example, if the repositories on your server live under
782 \dirname{/home/hg/repos}, and you have a repository whose path is
783 \dirname{/home/hg/repos/app/tests}, then setting \texttt{strip} to
784 \texttt{4} will give a partial path of \dirname{app/tests}. The
785 hook will make this partial path available when expanding a
786 template, as \texttt{webroot}.
787 \item[\texttt{template}] The text of the template to use. In addition
788 to the usual changeset-related variables, this template can use
789 \texttt{hgweb} (the value of the \texttt{hgweb} configuration item
790 above) and \texttt{webroot} (the path constructed using
791 \texttt{strip} above).
792 \end{itemize}
794 In addition, you can add a \rcitem{web}{baseurl} item to the
795 \rcsection{web} section of your \hgrc. The \hgext{bugzilla} hook will
796 make this available when expanding a template, as the base string to
797 use when constructing a URL that will let users browse from a Bugzilla
798 comment to view a changeset. Example:
799 \begin{codesample2}
800 [web]
801 baseurl = http://hg.domain.com/
802 \end{codesample2}
804 Here is an example set of \hgext{bugzilla} hook config information.
805 \begin{codesample2}
806 [bugzilla]
807 host = bugzilla.example.com
808 password = mypassword
809 version = 2.16
810 # server-side repos live in /home/hg/repos, so strip 4 leading
811 # separators
812 strip = 4
813 hgweb = http://hg.example.com/
814 usermap = /home/hg/repos/notify/bugzilla.conf
815 template = Changeset \{node|short\}, made by \{author\} in the \{webroot\}
816 repo, refers to this bug.\\nFor complete details, see
817 \{hgweb\}\{webroot\}?cmd=changeset;node=\{node|short\}\\nChangeset
818 description:\\n\\t\{desc|tabindent\}
819 \end{codesample2}
821 \subsubsection{Testing and troubleshooting}
823 The most common problems with configuring the \hgext{bugzilla} hook
824 relate to running Bugzilla's \filename{processmail} script and mapping
825 committer names to user names.
827 Recall from section~\ref{sec:hook:bugzilla:config} above that the user
828 that runs the Mercurial process on the server is also the one that
829 will run the \filename{processmail} script. The
830 \filename{processmail} script sometimes causes Bugzilla to write to
831 files in its configuration directory, and Bugzilla's configuration
832 files are usually owned by the user that your web server runs under.
834 You can cause \filename{processmail} to be run with the suitable
835 user's identity using the \command{sudo} command. Here is an example
836 entry for a \filename{sudoers} file.
837 \begin{codesample2}
838 hg_user = (httpd_user) NOPASSWD: /var/www/html/bugzilla/processmail-wrapper %s
839 \end{codesample2}
840 This allows the \texttt{hg\_user} user to run a
841 \filename{processmail-wrapper} program under the identity of
842 \texttt{httpd\_user}.
844 This indirection through a wrapper script is necessary, because
845 \filename{processmail} expects to be run with its current directory
846 set to wherever you installed Bugzilla; you can't specify that kind of
847 constraint in a \filename{sudoers} file. The contents of the wrapper
848 script are simple:
849 \begin{codesample2}
850 #!/bin/sh
851 cd `dirname $0` && ./processmail "$1" nobody@example.com
852 \end{codesample2}
853 It doesn't seem to matter what email address you pass to
854 \filename{processmail}.
856 If your \rcsection{usermap} is not set up correctly, users will see an
857 error message from the \hgext{bugzilla} hook when they push changes
858 to the server. The error message will look like this:
859 \begin{codesample2}
860 cannot find bugzilla user id for john.q.public@example.com
861 \end{codesample2}
862 What this means is that the committer's address,
863 \texttt{john.q.public@example.com}, is not a valid Bugzilla user name,
864 nor does it have an entry in your \rcsection{usermap} that maps it to
865 a valid Bugzilla user name.
867 \subsection{\hgext{notify}---send email notifications}
869 Although Mercurial's built-in web server provides RSS feeds of changes
870 in every repository, many people prefer to receive change
871 notifications via email. The \hgext{notify} hook lets you send out
872 notifications to a set of email addresses whenever changesets arrive
873 that those subscribers are interested in.
875 As with the \hgext{bugzilla} hook, the \hgext{notify} hook is
876 template-driven, so you can customise the contents of the notification
877 messages that it sends.
879 By default, the \hgext{notify} hook includes a diff of every changeset
880 that it sends out; you can limit the size of the diff, or turn this
881 feature off entirely. It is useful for letting subscribers review
882 changes immediately, rather than clicking to follow a URL.
884 \subsubsection{Configuring the \hgext{notify} hook}
886 You can set up the \hgext{notify} hook to send one email message per
887 incoming changeset, or one per incoming group of changesets (all those
888 that arrived in a single pull or push).
889 \begin{codesample2}
890 [hooks]
891 # send one email per group of changes
892 changegroup.notify = python:hgext.notify.hook
893 # send one email per change
894 incoming.notify = python:hgext.notify.hook
895 \end{codesample2}
897 Configuration information for this hook lives in the
898 \rcsection{notify} section of a \hgrc\ file.
899 \begin{itemize}
900 \item[\rcitem{notify}{test}] By default, this hook does not send out
901 email at all; instead, it prints the message that it \emph{would}
902 send. Set this item to \texttt{false} to allow email to be sent.
903 The reason that sending of email is turned off by default is that it
904 takes several tries to configure this extension exactly as you would
905 like, and it would be bad form to spam subscribers with a number of
906 ``broken'' notifications while you debug your configuration.
907 \item[\rcitem{notify}{config}] The path to a configuration file that
908 contains subscription information. This is kept separate from the
909 main \hgrc\ so that you can maintain it in a repository of its own.
910 People can then clone that repository, update their subscriptions,
911 and push the changes back to your server.
912 \item[\rcitem{notify}{strip}] The number of leading path separator
913 characters to strip from a repository's path, when deciding whether
914 a repository has subscribers. For example, if the repositories on
915 your server live in \dirname{/home/hg/repos}, and \hgext{notify} is
916 considering a repository named \dirname{/home/hg/repos/shared/test},
917 setting \rcitem{notify}{strip} to \texttt{4} will cause
918 \hgext{notify} to trim the path it considers down to
919 \dirname{shared/test}, and it will match subscribers against that.
920 \item[\rcitem{notify}{template}] The template text to use when sending
921 messages. This specifies both the contents of the message header
922 and its body.
923 \item[\rcitem{notify}{maxdiff}] The maximum number of lines of diff
924 data to append to the end of a message. If a diff is longer than
925 this, it is truncated. By default, this is set to 300. Set this to
926 \texttt{0} to omit diffs from notification emails.
927 \item[\rcitem{notify}{sources}] A list of sources of changesets to
928 consider. This lets you limit \hgext{notify} to only sending out
929 email about changes that remote users pushed into this repository
930 via a server, for example. See section~\ref{sec:hook:sources} for
931 the sources you can specify here.
932 \end{itemize}
934 If you set the \rcitem{web}{baseurl} item in the \rcsection{web}
935 section, you can use it in a template; it will be available as
936 \texttt{webroot}.
938 Here is an example set of \hgext{notify} configuration information.
939 \begin{codesample2}
940 [notify]
941 # really send email
942 test = false
943 # subscriber data lives in the notify repo
944 config = /home/hg/repos/notify/notify.conf
945 # repos live in /home/hg/repos on server, so strip 4 "/" chars
946 strip = 4
947 template = X-Hg-Repo: \{webroot\}
948 Subject: \{webroot\}: \{desc|firstline|strip\}
949 From: \{author\}
951 changeset \{node|short\} in \{root\}
952 details: \{baseurl\}\{webroot\}?cmd=changeset;node=\{node|short\}
953 description:
954 \{desc|tabindent|strip\}
956 [web]
957 baseurl = http://hg.example.com/
958 \end{codesample2}
960 This will produce a message that looks like the following:
961 \begin{codesample2}
962 X-Hg-Repo: tests/slave
963 Subject: tests/slave: Handle error case when slave has no buffers
964 Date: Wed, 2 Aug 2006 15:25:46 -0700 (PDT)
966 changeset 3cba9bfe74b5 in /home/hg/repos/tests/slave
967 details: http://hg.example.com/tests/slave?cmd=changeset;node=3cba9bfe74b5
968 description:
969 Handle error case when slave has no buffers
970 diffs (54 lines):
972 diff -r 9d95df7cf2ad -r 3cba9bfe74b5 include/tests.h
973 --- a/include/tests.h Wed Aug 02 15:19:52 2006 -0700
974 +++ b/include/tests.h Wed Aug 02 15:25:26 2006 -0700
975 @@ -212,6 +212,15 @@ static __inline__ void test_headers(void *h)
976 [...snip...]
977 \end{codesample2}
979 \subsubsection{Testing and troubleshooting}
981 Do not forget that by default, the \hgext{notify} extension \emph{will
982 not send any mail} until you explicitly configure it to do so, by
983 setting \rcitem{notify}{test} to \texttt{false}. Until you do that,
984 it simply prints the message it \emph{would} send.
986 \section{Information for writers of hooks}
987 \label{sec:hook:ref}
989 \subsection{In-process hook execution}
991 An in-process hook is called with arguments of the following form:
992 \begin{codesample2}
993 def myhook(ui, repo, **kwargs):
994 pass
995 \end{codesample2}
996 The \texttt{ui} parameter is a \pymodclass{mercurial.ui}{ui} object.
997 The \texttt{repo} parameter is a
998 \pymodclass{mercurial.localrepo}{localrepository} object. The
999 names and values of the \texttt{**kwargs} parameters depend on the
1000 hook being invoked, with the following common features:
1001 \begin{itemize}
1002 \item If a parameter is named \texttt{node} or
1003 \texttt{parent\emph{N}}, it will contain a hexadecimal changeset ID.
1004 The empty string is used to represent ``null changeset ID'' instead
1005 of a string of zeroes.
1006 \item If a parameter is named \texttt{url}, it will contain the URL of
1007 a remote repository, if that can be determined.
1008 \item Boolean-valued parameters are represented as Python
1009 \texttt{bool} objects.
1010 \end{itemize}
1012 An in-process hook is called without a change to the process's working
1013 directory (unlike external hooks, which are run in the root of the
1014 repository). It must not change the process's working directory, or
1015 it will cause any calls it makes into the Mercurial API to fail.
1017 If a hook returns a boolean ``false'' value, it is considered to have
1018 succeeded. If it returns a boolean ``true'' value or raises an
1019 exception, it is considered to have failed. A useful way to think of
1020 the calling convention is ``tell me if you fail''.
1022 Note that changeset IDs are passed into Python hooks as hexadecimal
1023 strings, not the binary hashes that Mercurial's APIs normally use. To
1024 convert a hash from hex to binary, use the
1025 \pymodfunc{mercurial.node}{bin} function.
1027 \subsection{External hook execution}
1029 An external hook is passed to the shell of the user running Mercurial.
1030 Features of that shell, such as variable substitution and command
1031 redirection, are available. The hook is run in the root directory of
1032 the repository (unlike in-process hooks, which are run in the same
1033 directory that Mercurial was run in).
1035 Hook parameters are passed to the hook as environment variables. Each
1036 environment variable's name is converted in upper case and prefixed
1037 with the string ``\texttt{HG\_}''. For example, if the name of a
1038 parameter is ``\texttt{node}'', the name of the environment variable
1039 representing that parameter will be ``\texttt{HG\_NODE}''.
1041 A boolean parameter is represented as the string ``\texttt{1}'' for
1042 ``true'', ``\texttt{0}'' for ``false''. If an environment variable is
1043 named \envar{HG\_NODE}, \envar{HG\_PARENT1} or \envar{HG\_PARENT2}, it
1044 contains a changeset ID represented as a hexadecimal string. The
1045 empty string is used to represent ``null changeset ID'' instead of a
1046 string of zeroes. If an environment variable is named
1047 \envar{HG\_URL}, it will contain the URL of a remote repository, if
1048 that can be determined.
1050 If a hook exits with a status of zero, it is considered to have
1051 succeeded. If it exits with a non-zero status, it is considered to
1052 have failed.
1054 \subsection{Finding out where changesets come from}
1056 A hook that involves the transfer of changesets between a local
1057 repository and another may be able to find out information about the
1058 ``far side''. Mercurial knows \emph{how} changes are being
1059 transferred, and in many cases \emph{where} they are being transferred
1060 to or from.
1062 \subsubsection{Sources of changesets}
1063 \label{sec:hook:sources}
1065 Mercurial will tell a hook what means are, or were, used to transfer
1066 changesets between repositories. This is provided by Mercurial in a
1067 Python parameter named \texttt{source}, or an environment variable named
1068 \envar{HG\_SOURCE}.
1070 \begin{itemize}
1071 \item[\texttt{serve}] Changesets are transferred to or from a remote
1072 repository over http or ssh.
1073 \item[\texttt{pull}] Changesets are being transferred via a pull from
1074 one repository into another.
1075 \item[\texttt{push}] Changesets are being transferred via a push from
1076 one repository into another.
1077 \item[\texttt{bundle}] Changesets are being transferred to or from a
1078 bundle.
1079 \end{itemize}
1081 \subsubsection{Where changes are going---remote repository URLs}
1082 \label{sec:hook:url}
1084 When possible, Mercurial will tell a hook the location of the ``far
1085 side'' of an activity that transfers changeset data between
1086 repositories. This is provided by Mercurial in a Python parameter
1087 named \texttt{url}, or an environment variable named \envar{HG\_URL}.
1089 This information is not always known. If a hook is invoked in a
1090 repository that is being served via http or ssh, Mercurial cannot tell
1091 where the remote repository is, but it may know where the client is
1092 connecting from. In such cases, the URL will take one of the
1093 following forms:
1094 \begin{itemize}
1095 \item \texttt{remote:ssh:\emph{ip-address}}---remote ssh client, at
1096 the given IP address.
1097 \item \texttt{remote:http:\emph{ip-address}}---remote http client, at
1098 the given IP address. If the client is using SSL, this will be of
1099 the form \texttt{remote:https:\emph{ip-address}}.
1100 \item Empty---no information could be discovered about the remote
1101 client.
1102 \end{itemize}
1104 \section{Hook reference}
1106 \subsection{\hook{changegroup}---after remote changesets added}
1107 \label{sec:hook:changegroup}
1109 This hook is run after a group of pre-existing changesets has been
1110 added to the repository, for example via a \hgcmd{pull} or
1111 \hgcmd{unbundle}. This hook is run once per operation that added one
1112 or more changesets. This is in contrast to the \hook{incoming} hook,
1113 which is run once per changeset, regardless of whether the changesets
1114 arrive in a group.
1116 Some possible uses for this hook include kicking off an automated
1117 build or test of the added changesets, updating a bug database, or
1118 notifying subscribers that a repository contains new changes.
1120 Parameters to this hook:
1121 \begin{itemize}
1122 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1123 changeset in the group that was added. All changesets between this
1124 and \index{tags!\texttt{tip}}\texttt{tip}, inclusive, were added by
1125 a single \hgcmd{pull}, \hgcmd{push} or \hgcmd{unbundle}.
1126 \item[\texttt{source}] A string. The source of these changes. See
1127 section~\ref{sec:hook:sources} for details.
1128 \item[\texttt{url}] A URL. The location of the remote repository, if
1129 known. See section~\ref{sec:hook:url} for more information.
1130 \end{itemize}
1132 See also: \hook{incoming} (section~\ref{sec:hook:incoming}),
1133 \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup}),
1134 \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1136 \subsection{\hook{commit}---after a new changeset is created}
1137 \label{sec:hook:commit}
1139 This hook is run after a new changeset has been created.
1141 Parameters to this hook:
1142 \begin{itemize}
1143 \item[\texttt{node}] A changeset ID. The changeset ID of the newly
1144 committed changeset.
1145 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1146 parent of the newly committed changeset.
1147 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1148 parent of the newly committed changeset.
1149 \end{itemize}
1151 See also: \hook{precommit} (section~\ref{sec:hook:precommit}),
1152 \hook{pretxncommit} (section~\ref{sec:hook:pretxncommit})
1154 \subsection{\hook{incoming}---after one remote changeset is added}
1155 \label{sec:hook:incoming}
1157 This hook is run after a pre-existing changeset has been added to the
1158 repository, for example via a \hgcmd{push}. If a group of changesets
1159 was added in a single operation, this hook is called once for each
1160 added changeset.
1162 You can use this hook for the same purposes as the \hook{changegroup}
1163 hook (section~\ref{sec:hook:changegroup}); it's simply more convenient
1164 sometimes to run a hook once per group of changesets, while other
1165 times it's handier once per changeset.
1167 Parameters to this hook:
1168 \begin{itemize}
1169 \item[\texttt{node}] A changeset ID. The ID of the newly added
1170 changeset.
1171 \item[\texttt{source}] A string. The source of these changes. See
1172 section~\ref{sec:hook:sources} for details.
1173 \item[\texttt{url}] A URL. The location of the remote repository, if
1174 known. See section~\ref{sec:hook:url} for more information.
1175 \end{itemize}
1177 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}) \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup}), \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1179 \subsection{\hook{outgoing}---after changesets are propagated}
1180 \label{sec:hook:outgoing}
1182 This hook is run after a group of changesets has been propagated out
1183 of this repository, for example by a \hgcmd{push} or \hgcmd{bundle}
1184 command.
1186 One possible use for this hook is to notify administrators that
1187 changes have been pulled.
1189 Parameters to this hook:
1190 \begin{itemize}
1191 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1192 changeset of the group that was sent.
1193 \item[\texttt{source}] A string. The source of the of the operation
1194 (see section~\ref{sec:hook:sources}). If a remote client pulled
1195 changes from this repository, \texttt{source} will be
1196 \texttt{serve}. If the client that obtained changes from this
1197 repository was local, \texttt{source} will be \texttt{bundle},
1198 \texttt{pull}, or \texttt{push}, depending on the operation the
1199 client performed.
1200 \item[\texttt{url}] A URL. The location of the remote repository, if
1201 known. See section~\ref{sec:hook:url} for more information.
1202 \end{itemize}
1204 See also: \hook{preoutgoing} (section~\ref{sec:hook:preoutgoing})
1206 \subsection{\hook{prechangegroup}---before starting to add remote changesets}
1207 \label{sec:hook:prechangegroup}
1209 This controlling hook is run before Mercurial begins to add a group of
1210 changesets from another repository.
1212 This hook does not have any information about the changesets to be
1213 added, because it is run before transmission of those changesets is
1214 allowed to begin. If this hook fails, the changesets will not be
1215 transmitted.
1217 One use for this hook is to prevent external changes from being added
1218 to a repository. For example, you could use this to ``freeze'' a
1219 server-hosted branch temporarily or permanently so that users cannot
1220 push to it, while still allowing a local administrator to modify the
1221 repository.
1223 Parameters to this hook:
1224 \begin{itemize}
1225 \item[\texttt{source}] A string. The source of these changes. See
1226 section~\ref{sec:hook:sources} for details.
1227 \item[\texttt{url}] A URL. The location of the remote repository, if
1228 known. See section~\ref{sec:hook:url} for more information.
1229 \end{itemize}
1231 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}),
1232 \hook{incoming} (section~\ref{sec:hook:incoming}), ,
1233 \hook{pretxnchangegroup} (section~\ref{sec:hook:pretxnchangegroup})
1235 \subsection{\hook{precommit}---before starting to commit a changeset}
1236 \label{sec:hook:precommit}
1238 This hook is run before Mercurial begins to commit a new changeset.
1239 It is run before Mercurial has any of the metadata for the commit,
1240 such as the files to be committed, the commit message, or the commit
1241 date.
1243 One use for this hook is to disable the ability to commit new
1244 changesets, while still allowing incoming changesets. Another is to
1245 run a build or test, and only allow the commit to begin if the build
1246 or test succeeds.
1248 Parameters to this hook:
1249 \begin{itemize}
1250 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1251 parent of the working directory.
1252 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1253 parent of the working directory.
1254 \end{itemize}
1255 If the commit proceeds, the parents of the working directory will
1256 become the parents of the new changeset.
1258 See also: \hook{commit} (section~\ref{sec:hook:commit}),
1259 \hook{pretxncommit} (section~\ref{sec:hook:pretxncommit})
1261 \subsection{\hook{preoutgoing}---before starting to propagate changesets}
1262 \label{sec:hook:preoutgoing}
1264 This hook is invoked before Mercurial knows the identities of the
1265 changesets to be transmitted.
1267 One use for this hook is to prevent changes from being transmitted to
1268 another repository.
1270 Parameters to this hook:
1271 \begin{itemize}
1272 \item[\texttt{source}] A string. The source of the operation that is
1273 attempting to obtain changes from this repository (see
1274 section~\ref{sec:hook:sources}). See the documentation for the
1275 \texttt{source} parameter to the \hook{outgoing} hook, in
1276 section~\ref{sec:hook:outgoing}, for possible values of this
1277 parameter.
1278 \item[\texttt{url}] A URL. The location of the remote repository, if
1279 known. See section~\ref{sec:hook:url} for more information.
1280 \end{itemize}
1282 See also: \hook{outgoing} (section~\ref{sec:hook:outgoing})
1284 \subsection{\hook{pretag}---before tagging a changeset}
1285 \label{sec:hook:pretag}
1287 This controlling hook is run before a tag is created. If the hook
1288 succeeds, creation of the tag proceeds. If the hook fails, the tag is
1289 not created.
1291 Parameters to this hook:
1292 \begin{itemize}
1293 \item[\texttt{local}] A boolean. Whether the tag is local to this
1294 repository instance (i.e.~stored in \sfilename{.hg/localtags}) or
1295 managed by Mercurial (stored in \sfilename{.hgtags}).
1296 \item[\texttt{node}] A changeset ID. The ID of the changeset to be tagged.
1297 \item[\texttt{tag}] A string. The name of the tag to be created.
1298 \end{itemize}
1300 If the tag to be created is revision-controlled, the \hook{precommit}
1301 and \hook{pretxncommit} hooks (sections~\ref{sec:hook:commit}
1302 and~\ref{sec:hook:pretxncommit}) will also be run.
1304 See also: \hook{tag} (section~\ref{sec:hook:tag})
1306 \subsection{\hook{pretxnchangegroup}---before completing addition of
1307 remote changesets}
1308 \label{sec:hook:pretxnchangegroup}
1310 This controlling hook is run before a transaction---that manages the
1311 addition of a group of new changesets from outside the
1312 repository---completes. If the hook succeeds, the transaction
1313 completes, and all of the changesets become permanent within this
1314 repository. If the hook fails, the transaction is rolled back, and
1315 the data for the changesets is erased.
1317 This hook can access the metadata associated with the almost-added
1318 changesets, but it should not do anything permanent with this data.
1319 It must also not modify the working directory.
1321 While this hook is running, if other Mercurial processes access this
1322 repository, they will be able to see the almost-added changesets as if
1323 they are permanent. This may lead to race conditions if you do not
1324 take steps to avoid them.
1326 This hook can be used to automatically vet a group of changesets. If
1327 the hook fails, all of the changesets are ``rejected'' when the
1328 transaction rolls back.
1330 Parameters to this hook:
1331 \begin{itemize}
1332 \item[\texttt{node}] A changeset ID. The changeset ID of the first
1333 changeset in the group that was added. All changesets between this
1334 and \index{tags!\texttt{tip}}\texttt{tip}, inclusive, were added by
1335 a single \hgcmd{pull}, \hgcmd{push} or \hgcmd{unbundle}.
1336 \item[\texttt{source}] A string. The source of these changes. See
1337 section~\ref{sec:hook:sources} for details.
1338 \item[\texttt{url}] A URL. The location of the remote repository, if
1339 known. See section~\ref{sec:hook:url} for more information.
1340 \end{itemize}
1342 See also: \hook{changegroup} (section~\ref{sec:hook:changegroup}),
1343 \hook{incoming} (section~\ref{sec:hook:incoming}),
1344 \hook{prechangegroup} (section~\ref{sec:hook:prechangegroup})
1346 \subsection{\hook{pretxncommit}---before completing commit of new changeset}
1347 \label{sec:hook:pretxncommit}
1349 This controlling hook is run before a transaction---that manages a new
1350 commit---completes. If the hook succeeds, the transaction completes
1351 and the changeset becomes permanent within this repository. If the
1352 hook fails, the transaction is rolled back, and the commit data is
1353 erased.
1355 This hook can access the metadata associated with the almost-new
1356 changeset, but it should not do anything permanent with this data. It
1357 must also not modify the working directory.
1359 While this hook is running, if other Mercurial processes access this
1360 repository, they will be able to see the almost-new changeset as if it
1361 is permanent. This may lead to race conditions if you do not take
1362 steps to avoid them.
1364 Parameters to this hook:
1365 \begin{itemize}
1366 \item[\texttt{node}] A changeset ID. The changeset ID of the newly
1367 committed changeset.
1368 \item[\texttt{parent1}] A changeset ID. The changeset ID of the first
1369 parent of the newly committed changeset.
1370 \item[\texttt{parent2}] A changeset ID. The changeset ID of the second
1371 parent of the newly committed changeset.
1372 \end{itemize}
1374 See also: \hook{precommit} (section~\ref{sec:hook:precommit})
1376 \subsection{\hook{preupdate}---before updating or merging working directory}
1377 \label{sec:hook:preupdate}
1379 This controlling hook is run before an update or merge of the working
1380 directory begins. It is run only if Mercurial's normal pre-update
1381 checks determine that the update or merge can proceed. If the hook
1382 succeeds, the update or merge may proceed; if it fails, the update or
1383 merge does not start.
1385 Parameters to this hook:
1386 \begin{itemize}
1387 \item[\texttt{parent1}] A changeset ID. The ID of the parent that the
1388 working directory is to be updated to. If the working directory is
1389 being merged, it will not change this parent.
1390 \item[\texttt{parent2}] A changeset ID. Only set if the working
1391 directory is being merged. The ID of the revision that the working
1392 directory is being merged with.
1393 \end{itemize}
1395 See also: \hook{update} (section~\ref{sec:hook:update})
1397 \subsection{\hook{tag}---after tagging a changeset}
1398 \label{sec:hook:tag}
1400 This hook is run after a tag has been created.
1402 Parameters to this hook:
1403 \begin{itemize}
1404 \item[\texttt{local}] A boolean. Whether the new tag is local to this
1405 repository instance (i.e.~stored in \sfilename{.hg/localtags}) or
1406 managed by Mercurial (stored in \sfilename{.hgtags}).
1407 \item[\texttt{node}] A changeset ID. The ID of the changeset that was
1408 tagged.
1409 \item[\texttt{tag}] A string. The name of the tag that was created.
1410 \end{itemize}
1412 If the created tag is revision-controlled, the \hook{commit} hook
1413 (section~\ref{sec:hook:commit}) is run before this hook.
1415 See also: \hook{pretag} (section~\ref{sec:hook:pretag})
1417 \subsection{\hook{update}---after updating or merging working directory}
1418 \label{sec:hook:update}
1420 This hook is run after an update or merge of the working directory
1421 completes. Since a merge can fail (if the external \command{hgmerge}
1422 command fails to resolve conflicts in a file), this hook communicates
1423 whether the update or merge completed cleanly.
1425 \begin{itemize}
1426 \item[\texttt{error}] A boolean. Indicates whether the update or
1427 merge completed successfully.
1428 \item[\texttt{parent1}] A changeset ID. The ID of the parent that the
1429 working directory was updated to. If the working directory was
1430 merged, it will not have changed this parent.
1431 \item[\texttt{parent2}] A changeset ID. Only set if the working
1432 directory was merged. The ID of the revision that the working
1433 directory was merged with.
1434 \end{itemize}
1436 See also: \hook{preupdate} (section~\ref{sec:hook:preupdate})
1438 %%% Local Variables:
1439 %%% mode: latex
1440 %%% TeX-master: "00book"
1441 %%% End: