hgbook

view es/template.tex @ 471:2449d5d3298e

updated template translation percentage
author Igor Támara <igor@tamarapatino.org>
date Sun Dec 28 00:30:00 2008 -0500 (2008-12-28)
parents b05e35d641e4
children 1b8b19825994
line source
1 \chapter{Personalizar los mensajes de Mercurial}
2 \label{chap:template}
4 Mercurial provee un poderoso mecanismo que permite controlar como
5 despliega la información. El mecanismo se basa en plantillas. Puede
6 usar plantillas para generar salida específica para una orden
7 particular o para especificar la visualización completa de la interfaz
8 web embebida.
10 \section{Usar estilos que vienen con Mercurial}
11 \label{sec:style}
13 Hay ciertos estilos listos que vienen con Mercurial. Un estilo es
14 simplemente una plantilla predeterminada que alguien escribió e
15 instaló en un sitio en el cual Mercurial puede encontrarla.
17 Antes de dar un vistazo a los estilos que trae Mercurial, revisemos su
18 salida usual.
20 \interaction{template.simple.normal}
22 Es en cierta medida informativa, pero ocupa mucho espacio---cinco
23 líneas de salida por cada conjunto de cambios. El estilo
24 \texttt{compact} lo reduce a tres líneas, presentadas de forma
25 suscinta.
27 \interaction{template.simple.compact}
29 El estilo de la \texttt{bitácora de cambios} vislumbra el poder
30 expresivo del sistema de plantillas de Mercurial. Este estilo busca
31 seguir los estándares de bitácora de cambios del proyecto
32 GNU\cite{web:changelog}.
34 \interaction{template.simple.changelog}
36 No es una sorpresa que el estilo predeterminado de Mercurial se llame
37 \texttt{default}\ndt{predeterminado}.
39 \subsection{Especificar un estilo predeterminado}
41 Puede modificar el estilo de presentación que Mercurial usará para
42 toda orden vía el fichero \hgrc\, indicando el estilo que prefiere
43 usar.
45 \begin{codesample2}
46 [ui]
47 style = compact
48 \end{codesample2}
50 Si escribe un estilo, puede usarlo bien sea proveyendo la ruta a su
51 fichero de estilo o copiando su fichero de estilo a un lugar en el
52 cual Mercurial pueda encontrarlo(típicamente el subdirectorio
53 \texttt{templates} de su directorio de instalación de Mercurial).
55 \section{Órdenes que soportan estilos y plantillas}
57 Todas las órdenes de Mercurial``relacionadas con \texttt{log}'' le
58 permiten usar estilos y plantillas: \hgcmd{incoming}, \hgcmd{log},
59 \hgcmd{outgoing} y \hgcmd{tip}.
61 Al momento de la escritura del manual estas son las únicas órdenes que
62 soportan estilos y plantillas. Dado que son las órdenes más
63 importantes que necesitan personalización, no ha habido muchas
64 solicitudes desde la comunidad de usuarios de Mercurial para añadir
65 soporte de plantillas y estilos a otras órdenes.
67 \section{Cuestiones básicas de plantillas}
69 Una plantilla de Mercurial es sencillamente una pieza de texto.
70 Cierta porción nunca cambia, otras partes se \emph{expanden}, o
71 reemplazan con texto nuevo cuando es necesario.
73 Antes de continuar, veamos de nuevo un ejemplo sencillo de la salida
74 usual de Mercurial:
76 \interaction{template.simple.normal}
78 Ahora, ejecutemos la misma orden, pero usemos una plantilla para
79 modificar su salida:
81 \interaction{template.simple.simplest}
83 El ejemplo anterior ilustra la plantilla más sencilla posible; es
84 solamente una porción estática de código que se imprime una vez por
85 cada conjunto de cambios. La opción \hgopt{log}{--template} de la
86 orden \hgcmd{log} indica a Mercurial usar el texto dado como la
87 plantilla cuando se imprime cada conjunto de cambios.
89 Observe que la cadena de plantilla anterior termina con el texto
90 ``\Verb+\n+''. Es una \emph{secuencia de control}, que le indica a
91 Mercurial imprimira una nueva línea al final de cada objeto de la
92 plantilla. Si omite esta nueva línea, Mercurial colocará cada pieza
93 de salida seguida. Si desea más detalles acerca de secuencias de
94 control, vea la sección~\ref{sec:template:escape}.
96 Una plantilla que imprime una cadena fija de texto siempre no es muy
97 útil; intentemos algo un poco más complejo.
99 \interaction{template.simple.simplesub}
101 Como puede ver, la cadena ``\Verb+{desc}+'' en la plantilla ha sido
102 reemplazada en la salida con la descricipción de cada conjunto de
103 cambios. Cada vez que Mercurial encuentra texto encerrado entre
104 corchetes(``\texttt{\{}'' y ``\texttt{\}}''), intentará reemplazar los
105 corchetes y el texto con la expansión de lo que sea está adentro.
106 Para imprimir un corchete de forma literal, debe escaparlo, como se
107 describe en la sección~\ref{sec:template:escape}.
109 \section{Palabras claves más comunes en las plantillas}
110 \label{sec:template:keyword}
112 Puede empezar a escribir plantillas sencillas rápidamente con las
113 palabras claves descritas a continuación:
115 \begin{itemize}
116 \item[\tplkword{author}] Cadena. El autor NO modificado del conjunto
117 de cambios.
118 \item[\tplkword{branches}] Cadena. El nombre de la rama en la cual se
119 consignó el conjunto de cambios. Será vacía si el nombre de la rama es
120 \texttt{default}.
121 \item[\tplkword{date}] Información de fecha. La fecha en la cual se
122 consignó el conjunto de cambios. \emph{No} es legible por un
123 humano, debe pasarla por un firltro que la desplegará
124 apropiadamente. En la sección~\ref{sec:template:filter} hay más
125 detalles acerca de filtros. La fecha se expresa como un par de
126 números. El primer número corresponde a una marca de tiempo UNIX
127 UTC(segundos desde el primero de enero de 1970); la segunda es el
128 corrimiento horario de la zona horaria del UTC en la cual se encontraba
129 quien hizo la consignación, en segundos.
130 \item[\tplkword{desc}] Cadena. La descripción en texto del conjunto
131 de cambios.
132 \item[\tplkword{files}] Lista de cadenas. Todos los ficheros
133 modificados, adicionados o eliminados por este conjunto de cambios.
134 \item[\tplkword{file\_adds}] Lista de cadenas. Ficheros adicionados
135 por este conjunto de cambios.
136 \item[\tplkword{file\_dels}] Lista de cadenas. Ficheros eliminados
137 por este conjunto de cambios.
138 \item[\tplkword{node}] Cadena. El hash de identificación de este
139 conjunto de cambios como una cadena hexadecimal de 40 caracteres.
140 \item[\tplkword{parents}] Lista de cadenas. Los ancestros del
141 conjunto de cambios.
142 \item[\tplkword{rev}] Entero. El número de revisión del repositorio
143 local.
144 \item[\tplkword{tags}] Lista de cadenas. Todas las etiquetas
145 asociadas al conjunto de cambios.
146 \end{itemize}
148 Unos experimentos sencillos nos mostrarán qué esperar cuando usamos
149 estas palabras claves; puede ver los resultados en la
150 figura~\ref{fig:template:keywords}.
152 \begin{figure}
153 \interaction{template.simple.keywords}
154 \caption{Template keywords in use}
155 \label{fig:template:keywords}
156 \end{figure}
158 Como mencionamos anteriormente, la palabra clave de fecha no produce
159 salida legible por un humano, debemos tratarla de forma especial.
160 Esto involucra usar un \emph{filtro}, acerca de lo cual hay más en la
161 sección~\ref{sec:template:filter}.
163 \interaction{template.simple.datekeyword}
165 \section{Secuencias de Control}
166 \label{sec:template:escape}
168 El motor de plantillas de Mercurial reconoce las secuencias de control
169 más comunmente usadas dentro de las cadenas. Cuando ve un backslash
170 (``\Verb+\+''), ve el caracter siguiente y sustituye los dos
171 caracteres con un reemplazo sencillo, como se describe a continuación:
173 \begin{itemize}
174 \item[\Verb+\textbackslash\textbackslash+] Backslash, ``\Verb+\+'',
175 ASCII~134.
176 \item[\Verb+\textbackslash n+] Nueva línea, ASCII~12.
177 \item[\Verb+\textbackslash r+] Cambio de línea, ASCII~15.
178 \item[\Verb+\textbackslash t+] Tab, ASCII~11.
179 \item[\Verb+\textbackslash v+] Tab Vertical, ASCII~13.
180 \item[\Verb+\textbackslash \{+] Corchete abierto, ``\Verb+{+'', ASCII~173.
181 \item[\Verb+\textbackslash \}+] Corchete cerrado, ``\Verb+}+'', ASCII~175.
182 \end{itemize}
184 Como se indicó arriba, si desea que la expansión en una plantilla
185 contenga un caracter literal ``\Verb+\+'', ``\Verb+{+'', o
186 ``\Verb+{+'', debe escaparlo.
188 \section{Uso de filtros con palabras claves}
189 \label{sec:template:filter}
191 Algunos de los resultados de la expansión de la plantilla no son
192 fáciles de usar de inmediato. Mercurial le permite especificar una
193 cadena de \emph{filtros} opcionales para modificar el resultado de
194 expandir una palabra clave. Ya ha visto el filtro usual
195 \tplkwfilt{date}{isodate} en acción con anterioridad para hacer
196 legible la fecha.
198 A continuación hay una lista de los filtros de Mercurial más
199 comunmente usados. Ciertos filtros pueden aplicarse a cualquier
200 texto, otros pueden usarse únicamente en circunstancias específicas.
201 El nombre de cada filtro está seguido de la indicación de dónde puede
202 ser usado y una descripción de su efecto.
204 \begin{itemize}
205 \item[\tplfilter{addbreaks}] Cualquier texto. Añade una etiqueta XHTML
206 ``\Verb+<br/>+'' antes del final de cada línea excepto en la final.
207 Por ejemplo, ``\Verb+foo\nbar+'' se convierte en ``\Verb+foo<br/>\nbar+''.
208 \item[\tplkwfilt{date}{age}] palabra clave \tplkword{date}. Muestra
209 la edad de la fecha, relativa al tiempo actual. Ofrece una cadena como
210 ``\Verb+10 minutes+''.
211 \item[\tplfilter{basename}] Cualquier texto, pero de utilidad sobre
212 todo en palabras claves relativas a \tplkword{ficheros}. Trata el
213 texto como una ruta, retornando el nombre base. Por ejemplo,
214 ``\Verb+foo/bar/baz+'', se convierte en ``\Verb+baz+''.
215 \item[\tplkwfilt{date}{date}] \tplkword{date} keyword. Render a date
216 in a similar format to the Unix \tplkword{date} command, but with
217 timezone included. Yields a string like
218 ``\Verb+Mon Sep 04 15:13:13 2006 -0700+''.
219 \item[\tplkwfilt{author}{domain}] Any text, but most useful for the
220 \tplkword{author} keyword. Finds the first string that looks like
221 an email address, and extract just the domain component. For
222 example, ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
223 ``\Verb+serpentine.com+''.
224 \item[\tplkwfilt{author}{email}] Any text, but most useful for the
225 \tplkword{author} keyword. Extract the first string that looks like
226 an email address. For example,
227 ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
228 ``\Verb+bos@serpentine.com+''.
229 \item[\tplfilter{escape}] Any text. Replace the special XML/XHTML
230 characters ``\Verb+&+'', ``\Verb+<+'' and ``\Verb+>+'' with
231 XML entities.
232 \item[\tplfilter{fill68}] Any text. Wrap the text to fit in 68
233 columns. This is useful before you pass text through the
234 \tplfilter{tabindent} filter, and still want it to fit in an
235 80-column fixed-font window.
236 \item[\tplfilter{fill76}] Any text. Wrap the text to fit in 76
237 columns.
238 \item[\tplfilter{firstline}] Any text. Yield the first line of text,
239 without any trailing newlines.
240 \item[\tplkwfilt{date}{hgdate}] \tplkword{date} keyword. Render the
241 date as a pair of readable numbers. Yields a string like
242 ``\Verb+1157407993 25200+''.
243 \item[\tplkwfilt{date}{isodate}] \tplkword{date} keyword. Render the
244 date as a text string in ISO~8601 format. Yields a string like
245 ``\Verb+2006-09-04 15:13:13 -0700+''.
246 \item[\tplfilter{obfuscate}] Any text, but most useful for the
247 \tplkword{author} keyword. Yield the input text rendered as a
248 sequence of XML entities. This helps to defeat some particularly
249 stupid screen-scraping email harvesting spambots.
250 \item[\tplkwfilt{author}{person}] Any text, but most useful for the
251 \tplkword{author} keyword. Yield the text before an email address.
252 For example, ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+''
253 becomes ``\Verb+Bryan O'Sullivan+''.
254 \item[\tplkwfilt{date}{rfc822date}] \tplkword{date} keyword. Render a
255 date using the same format used in email headers. Yields a string
256 like ``\Verb+Mon, 04 Sep 2006 15:13:13 -0700+''.
257 \item[\tplkwfilt{node}{short}] Changeset hash. Yield the short form
258 of a changeset hash, i.e.~a 12-byte hexadecimal string.
259 \item[\tplkwfilt{date}{shortdate}] \tplkword{date} keyword. Render
260 the year, month, and day of the date. Yields a string like
261 ``\Verb+2006-09-04+''.
262 \item[\tplfilter{strip}] Any text. Strip all leading and trailing
263 whitespace from the string.
264 \item[\tplfilter{tabindent}] Any text. Yield the text, with every line
265 except the first starting with a tab character.
266 \item[\tplfilter{urlescape}] Any text. Escape all characters that are
267 considered ``special'' by URL parsers. For example, \Verb+foo bar+
268 becomes \Verb+foo%20bar+.
269 \item[\tplkwfilt{author}{user}] Any text, but most useful for the
270 \tplkword{author} keyword. Return the ``user'' portion of an email
271 address. For example,
272 ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
273 ``\Verb+bos+''.
274 \end{itemize}
276 \begin{figure}
277 \interaction{template.simple.manyfilters}
278 \caption{Template filters in action}
279 \label{fig:template:filters}
280 \end{figure}
282 \begin{note}
283 If you try to apply a filter to a piece of data that it cannot
284 process, Mercurial will fail and print a Python exception. For
285 example, trying to run the output of the \tplkword{desc} keyword
286 into the \tplkwfilt{date}{isodate} filter is not a good idea.
287 \end{note}
289 \subsection{Combining filters}
291 It is easy to combine filters to yield output in the form you would
292 like. The following chain of filters tidies up a description, then
293 makes sure that it fits cleanly into 68 columns, then indents it by a
294 further 8~characters (at least on Unix-like systems, where a tab is
295 conventionally 8~characters wide).
297 \interaction{template.simple.combine}
299 Note the use of ``\Verb+\t+'' (a tab character) in the template to
300 force the first line to be indented; this is necessary since
301 \tplkword{tabindent} indents all lines \emph{except} the first.
303 Keep in mind that the order of filters in a chain is significant. The
304 first filter is applied to the result of the keyword; the second to
305 the result of the first filter; and so on. For example, using
306 \Verb+fill68|tabindent+ gives very different results from
307 \Verb+tabindent|fill68+.
310 \section{From templates to styles}
312 A command line template provides a quick and simple way to format some
313 output. Templates can become verbose, though, and it's useful to be
314 able to give a template a name. A style file is a template with a
315 name, stored in a file.
317 More than that, using a style file unlocks the power of Mercurial's
318 templating engine in ways that are not possible using the command line
319 \hgopt{log}{--template} option.
321 \subsection{The simplest of style files}
323 Our simple style file contains just one line:
325 \interaction{template.simple.rev}
327 This tells Mercurial, ``if you're printing a changeset, use the text
328 on the right as the template''.
330 \subsection{Style file syntax}
332 The syntax rules for a style file are simple.
334 \begin{itemize}
335 \item The file is processed one line at a time.
337 \item Leading and trailing white space are ignored.
339 \item Empty lines are skipped.
341 \item If a line starts with either of the characters ``\texttt{\#}'' or
342 ``\texttt{;}'', the entire line is treated as a comment, and skipped
343 as if empty.
345 \item A line starts with a keyword. This must start with an
346 alphabetic character or underscore, and can subsequently contain any
347 alphanumeric character or underscore. (In regexp notation, a
348 keyword must match \Verb+[A-Za-z_][A-Za-z0-9_]*+.)
350 \item The next element must be an ``\texttt{=}'' character, which can
351 be preceded or followed by an arbitrary amount of white space.
353 \item If the rest of the line starts and ends with matching quote
354 characters (either single or double quote), it is treated as a
355 template body.
357 \item If the rest of the line \emph{does not} start with a quote
358 character, it is treated as the name of a file; the contents of this
359 file will be read and used as a template body.
360 \end{itemize}
362 \section{Style files by example}
364 To illustrate how to write a style file, we will construct a few by
365 example. Rather than provide a complete style file and walk through
366 it, we'll mirror the usual process of developing a style file by
367 starting with something very simple, and walking through a series of
368 successively more complete examples.
370 \subsection{Identifying mistakes in style files}
372 If Mercurial encounters a problem in a style file you are working on,
373 it prints a terse error message that, once you figure out what it
374 means, is actually quite useful.
376 \interaction{template.svnstyle.syntax.input}
378 Notice that \filename{broken.style} attempts to define a
379 \texttt{changeset} keyword, but forgets to give any content for it.
380 When instructed to use this style file, Mercurial promptly complains.
382 \interaction{template.svnstyle.syntax.error}
384 This error message looks intimidating, but it is not too hard to
385 follow.
387 \begin{itemize}
388 \item The first component is simply Mercurial's way of saying ``I am
389 giving up''.
390 \begin{codesample4}
391 \textbf{abort:} broken.style:1: parse error
392 \end{codesample4}
394 \item Next comes the name of the style file that contains the error.
395 \begin{codesample4}
396 abort: \textbf{broken.style}:1: parse error
397 \end{codesample4}
399 \item Following the file name is the line number where the error was
400 encountered.
401 \begin{codesample4}
402 abort: broken.style:\textbf{1}: parse error
403 \end{codesample4}
405 \item Finally, a description of what went wrong.
406 \begin{codesample4}
407 abort: broken.style:1: \textbf{parse error}
408 \end{codesample4}
409 The description of the problem is not always clear (as in this
410 case), but even when it is cryptic, it is almost always trivial to
411 visually inspect the offending line in the style file and see what
412 is wrong.
413 \end{itemize}
415 \subsection{Uniquely identifying a repository}
417 If you would like to be able to identify a Mercurial repository
418 ``fairly uniquely'' using a short string as an identifier, you can
419 use the first revision in the repository.
420 \interaction{template.svnstyle.id}
421 This is not guaranteed to be unique, but it is nevertheless useful in
422 many cases.
423 \begin{itemize}
424 \item It will not work in a completely empty repository, because such
425 a repository does not have a revision~zero.
426 \item Neither will it work in the (extremely rare) case where a
427 repository is a merge of two or more formerly independent
428 repositories, and you still have those repositories around.
429 \end{itemize}
430 Here are some uses to which you could put this identifier:
431 \begin{itemize}
432 \item As a key into a table for a database that manages repositories
433 on a server.
434 \item As half of a \{\emph{repository~ID}, \emph{revision~ID}\} tuple.
435 Save this information away when you run an automated build or other
436 activity, so that you can ``replay'' the build later if necessary.
437 \end{itemize}
439 \subsection{Mimicking Subversion's output}
441 Let's try to emulate the default output format used by another
442 revision control tool, Subversion.
443 \interaction{template.svnstyle.short}
445 Since Subversion's output style is fairly simple, it is easy to
446 copy-and-paste a hunk of its output into a file, and replace the text
447 produced above by Subversion with the template values we'd like to see
448 expanded.
449 \interaction{template.svnstyle.template}
451 There are a few small ways in which this template deviates from the
452 output produced by Subversion.
453 \begin{itemize}
454 \item Subversion prints a ``readable'' date (the ``\texttt{Wed, 27 Sep
455 2006}'' in the example output above) in parentheses. Mercurial's
456 templating engine does not provide a way to display a date in this
457 format without also printing the time and time zone.
458 \item We emulate Subversion's printing of ``separator'' lines full of
459 ``\texttt{-}'' characters by ending the template with such a line.
460 We use the templating engine's \tplkword{header} keyword to print a
461 separator line as the first line of output (see below), thus
462 achieving similar output to Subversion.
463 \item Subversion's output includes a count in the header of the number
464 of lines in the commit message. We cannot replicate this in
465 Mercurial; the templating engine does not currently provide a filter
466 that counts the number of items it is passed.
467 \end{itemize}
468 It took me no more than a minute or two of work to replace literal
469 text from an example of Subversion's output with some keywords and
470 filters to give the template above. The style file simply refers to
471 the template.
472 \interaction{template.svnstyle.style}
474 We could have included the text of the template file directly in the
475 style file by enclosing it in quotes and replacing the newlines with
476 ``\verb!\n!'' sequences, but it would have made the style file too
477 difficult to read. Readability is a good guide when you're trying to
478 decide whether some text belongs in a style file, or in a template
479 file that the style file points to. If the style file will look too
480 big or cluttered if you insert a literal piece of text, drop it into a
481 template instead.
483 %%% Local Variables:
484 %%% mode: latex
485 %%% TeX-master: "00book"
486 %%% End: